feat(policy): add request policies settings and routing decision records

Group sensitive-word checks, channel selection, retries and channel health
under one "Request policies" settings area with a session rules editor,
per-rule session modes (inherit/off/prefer/strict) and a global default.
Record routing decisions per attempt into log admin info, expose
GET/PATCH /api/option/request_policy with whole-policy validation, and
redirect the legacy settings URLs to the new sections.
This commit is contained in:
CaIon committed 2026-09-18 11:24:29 +08:00
1 parent 8b2c7105f9
commit 73a471f3a8
69 files changed
+4891 -943

No files matched your search

+18 -1
View File
@@ -156,8 +156,25 @@ func buildChannelListQuery(group string, statusFilter int, typeFilter int) *gorm
}
func GetChannelOps(c *gin.Context) {
snapshot := model.CurrentRequestPolicy()
automaticDisable, source := snapshot.AutoDisable, "global"
if value, present := c.GetQuery("auto_ban"); present {
autoBan, err := strconv.ParseBool(value)
if err != nil {
common.ApiError(c, err)
return
}
automaticDisable = snapshot.AutoDisable && autoBan
if snapshot.AutoDisable {
source = "global_and_channel"
if !autoBan {
source = "channel"
}
}
}
common.ApiSuccess(c, gin.H{
"retry_times": common.RetryTimes,
"retry_times": snapshot.RetryTimes,
"request_policy": gin.H{"automatic_disable": automaticDisable, "source": source},
})
}
+132 -8
View File
@@ -2,13 +2,25 @@ package controller
import (
"errors"
"fmt"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/middleware"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/QuantumNous/new-api/setting/ratio_setting"
"net/http"
"net/http/httptest"
"os"
"slices"
"strings"
"testing"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -18,7 +30,7 @@ func TestShouldRetryHonorsPinRetryMode(t *testing.T) {
openaiErr := types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusInternalServerError)
c := newPinRetryContext()
assert.True(t, shouldRetry(c, openaiErr, 1))
assert.True(t, service.ShouldRetryRelayError(c, openaiErr, 1))
origin := newPinRetryContext()
service.GetChannelConstraints(origin).AddPin(dto.ChannelPin{
@@ -27,7 +39,7 @@ func TestShouldRetryHonorsPinRetryMode(t *testing.T) {
Rank: dto.PinRankOriginTask,
RetryMode: dto.PinRetrySameChannel,
})
assert.True(t, shouldRetry(origin, openaiErr, 1), "origin pin retries on the same channel")
assert.True(t, service.ShouldRetryRelayError(origin, openaiErr, 1), "origin pin retries on the same channel")
token := newPinRetryContext()
service.GetChannelConstraints(token).AddPin(dto.ChannelPin{
@@ -36,14 +48,14 @@ func TestShouldRetryHonorsPinRetryMode(t *testing.T) {
Rank: dto.PinRankToken,
RetryMode: dto.PinRetrySingleAttempt,
})
assert.False(t, shouldRetry(token, openaiErr, 1), "token pin suppresses retry")
assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"}, service.DecideRelayRetry(token, openaiErr, 1), "token pin suppresses retry")
}
func TestShouldRetryTaskRelayHonorsPinRetryMode(t *testing.T) {
taskErr := &dto.TaskError{StatusCode: http.StatusInternalServerError}
c := newPinRetryContext()
assert.True(t, shouldRetryTaskRelay(c, 1, taskErr, 1))
assert.Equal(t, "retry", decideTaskRetry(c, taskErr, 1).Action)
origin := newPinRetryContext()
service.GetChannelConstraints(origin).AddPin(dto.ChannelPin{
@@ -52,7 +64,7 @@ func TestShouldRetryTaskRelayHonorsPinRetryMode(t *testing.T) {
Rank: dto.PinRankOriginTask,
RetryMode: dto.PinRetrySameChannel,
})
assert.True(t, shouldRetryTaskRelay(origin, 2, taskErr, 1))
assert.Equal(t, "retry", decideTaskRetry(origin, taskErr, 1).Action)
token := newPinRetryContext()
service.GetChannelConstraints(token).AddPin(dto.ChannelPin{
@@ -61,7 +73,7 @@ func TestShouldRetryTaskRelayHonorsPinRetryMode(t *testing.T) {
Rank: dto.PinRankToken,
RetryMode: dto.PinRetrySingleAttempt,
})
assert.False(t, shouldRetryTaskRelay(token, 1, taskErr, 1))
assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"}, decideTaskRetry(token, taskErr, 1))
}
func TestSameChannelPinsMergeToStricterRetryMode(t *testing.T) {
@@ -84,7 +96,7 @@ func TestSameChannelPinsMergeToStricterRetryMode(t *testing.T) {
assert.Equal(t, 7, pin.ChannelId)
assert.Equal(t, dto.PinRetrySingleAttempt, pin.RetryMode)
assert.Empty(t, overridden)
assert.False(t, shouldRetry(c, types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusInternalServerError), 1))
assert.False(t, service.ShouldRetryRelayError(c, types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusInternalServerError), 1))
}
func newPinRetryContext() *gin.Context {
@@ -93,3 +105,115 @@ func newPinRetryContext() *gin.Context {
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
return c
}
func TestRequestPolicyConfigReturnsSettingsWithoutMigration(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
GetRequestPolicy(ctx)
assert.Equal(t, http.StatusOK, recorder.Code)
var response struct {
Success bool `json:"success"`
Data map[string]any `json:"data"`
}
require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response))
assert.True(t, response.Success)
assert.Contains(t, response.Data, "options")
assert.NotContains(t, response.Data, "migration")
assert.NotContains(t, response.Data, "differences")
}
func TestRequestPolicyRoutingDatabaseMatrix(t *testing.T) {
require.NoError(t, i18n.Init())
for _, dialect := range []struct{ kind, env string }{{"sqlite", ""}, {"mysql", "TEST_MYSQL_DSN"}, {"postgres", "TEST_POSTGRES_DSN"}} {
t.Run(dialect.kind, func(t *testing.T) {
dsn := ""
if dialect.env != "" {
dsn = os.Getenv(dialect.env)
if dsn == "" {
t.Skipf("%s not configured", dialect.env)
}
}
db := modelManagementDB(t, dialect.kind, dsn)
previousGroups := setting.UserUsableGroups2JSONString()
previousRatios, err := common.Marshal(ratio_setting.GetGroupRatioCopy())
require.NoError(t, err)
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{"default":"Default"}`))
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1}`))
t.Cleanup(func() {
require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(previousGroups))
require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(string(previousRatios)))
})
// Channel 1 holds the session binding but is no longer usable.
channels := []model.Channel{
{Id: 1, Name: "A", Type: 1, Key: "test-only", Status: common.ChannelStatusAutoDisabled, Models: "policy-test", Group: "default", Priority: common.GetPointer(int64(10))},
{Id: 2, Name: "B", Type: 1, Key: "test-only", Status: common.ChannelStatusEnabled, Models: "policy-test", Group: "default", Priority: common.GetPointer(int64(5))},
}
for i := range channels {
require.NoError(t, db.Create(&channels[i]).Error)
require.NoError(t, channels[i].AddAbilities(db))
}
affinity := operation_setting.GetChannelAffinitySetting()
previousAffinity := *affinity
t.Cleanup(func() { *affinity = previousAffinity })
for _, cached := range []bool{false, true} {
for _, keep := range []bool{false, true} {
for _, tc := range []struct {
globalMode, ruleMode string
blocked bool
}{
{"strict", "inherit", true},
{"prefer", "strict", true},
{"prefer", "inherit", false},
{"strict", "prefer", false},
} {
t.Run(fmt.Sprintf("cache=%t/keep=%t/global=%s/rule=%s", cached, keep, tc.globalMode, tc.ruleMode), func(t *testing.T) {
common.MemoryCacheEnabled = cached
model.InitChannelCache()
snapshot, err := model.BuildRequestPolicy(map[string]string{
"channel_affinity_setting.enabled": "true",
"channel_affinity_setting.session_mode": tc.globalMode,
"channel_affinity_setting.keep_on_channel_disabled": fmt.Sprint(keep),
"channel_affinity_setting.rules": fmt.Sprintf(`[{"name":"session","model_regex":[".*"],"key_sources":[{"type":"request_header","key":"X-Session"}],"session_mode":%q}]`, tc.ruleMode),
})
require.NoError(t, err)
*affinity = snapshot.Affinity
seed := newPinRetryContext()
seed.Request.Header.Set("X-Session", t.Name())
_, found := service.GetPreferredChannelByAffinity(seed, "policy-test", "default")
require.False(t, found)
seed.Set("channel_id", 1)
service.RecordChannelAffinity(seed, 1)
t.Cleanup(func() { service.ClearCurrentChannelAffinityCache(seed) })
bound, found := service.GetPreferredChannelByAffinity(seed, "policy-test", "default")
require.True(t, found)
require.Equal(t, 1, bound)
request := newPinRetryContext()
request.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"policy-test"}`))
request.Request.Header.Set("Content-Type", "application/json")
request.Request.Header.Set("X-Session", t.Name())
common.SetContextKey(request, constant.ContextKeyUsingGroup, "default")
middleware.Distribute()(request)
events := service.RequestPolicy(request).Events()
assert.True(t, slices.ContainsFunc(events, func(event service.PolicyEvent) bool { return event.Decision.Reason == "session_rule_matched" }), "decision events are recorded for every request")
bound, found = service.GetPreferredChannelByAffinity(seed, "policy-test", "default")
if tc.blocked {
assert.Equal(t, http.StatusServiceUnavailable, request.Writer.Status())
assert.True(t, request.IsAborted())
assert.Equal(t, keep, found, "binding retention is independent of strict request handling")
if found {
assert.Equal(t, 1, bound)
}
return
}
assert.False(t, request.IsAborted())
assert.Equal(t, 2, common.GetContextKeyInt(request, constant.ContextKeyChannelId), "prefer falls back to the next eligible channel")
require.True(t, found)
assert.Equal(t, 2, bound, "a successful fallback rebinds the session")
})
}
}
}
})
}
}
+75 -44
View File
@@ -90,6 +90,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
defer func() {
if newAPIError != nil {
service.RecordRequestPolicyTermination(c, newAPIError)
logger.LogError(c, fmt.Sprintf("relay error: %s", common.LocalLogPreview(newAPIError.Error())))
newAPIError.SetMessage(common.MessageWithRequestId(newAPIError.Error(), requestId))
switch relayFormat {
@@ -180,6 +181,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
}
if newAPIError == nil {
service.MarkRequestPolicySuccess(c, relayInfo.StreamStatus)
relayInfo.LastError = nil
return
}
@@ -187,9 +189,11 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
newAPIError = service.NormalizeViolationFeeError(newAPIError)
relayInfo.LastError = newAPIError
decision := service.DecideRelayRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry())
service.RecordPolicyFailure(c, channel.Id, newAPIError, decision)
processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError, relayInfo)
if !shouldRetry(c, newAPIError, common.RetryTimes-retryParam.GetRetry()) {
if decision.Action != "retry" {
break
}
}
@@ -258,12 +262,14 @@ func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service
if !autoBan {
autoBanInt = 0
}
return &model.Channel{
channel := &model.Channel{
Id: c.GetInt("channel_id"),
Type: c.GetInt("channel_type"),
Name: c.GetString("channel_name"),
AutoBan: &autoBanInt,
}, nil
}
service.RequestPolicy(c).BeginAttempt(channel, info.UsingGroup)
return channel, nil
}
channel, selectGroup, err := service.CacheGetRandomSatisfiedChannel(retryParam)
if err != nil {
@@ -275,6 +281,7 @@ func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service
info.PriceData.GroupRatioInfo = helper.HandleGroupRatio(c, info)
service.RequestPolicy(c).BeginAttempt(channel, selectGroup)
newAPIError := middleware.SetupContextForSelectedChannel(c, channel, info.OriginModelName)
if newAPIError != nil {
return nil, newAPIError
@@ -282,15 +289,17 @@ func getChannel(c *gin.Context, info *relaycommon.RelayInfo, retryParam *service
return channel, nil
}
func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
return service.ShouldRetryRelayError(c, openaiErr, retryTimes)
}
func processChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError, relayInfo *relaycommon.RelayInfo) {
service.ProcessChannelError(c, channelError, err, relayInfo)
}
func RelayMidjourney(c *gin.Context) {
policy := service.RequestPolicy(c)
defer func() {
if policy.Attempts > 0 && !policy.Successful {
service.RecordRequestPolicyTermination(c, types.NewErrorWithStatusCode(errors.New("Midjourney submission failed"), types.ErrorCodeBadResponseStatusCode, http.StatusBadGateway, types.ErrOptionWithSkipRetry()))
}
}()
relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatMjProxy, nil, nil)
if err != nil {
@@ -318,6 +327,7 @@ func RelayMidjourney(c *gin.Context) {
//err = relayMidjourneySubmit(c, relayMode)
log.Println(mjErr)
if mjErr != nil {
policy.Successful = false
statusCode := http.StatusBadRequest
if mjErr.Code == 30 {
mjErr.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
@@ -457,6 +467,7 @@ func executeTaskSubmissionWith(
relayInfo *relaycommon.RelayInfo,
submit taskSubmitAttempt,
) (*taskSubmissionOutcome, *taskdto.TaskError) {
policy := service.RequestPolicy(c)
diagnostics := newTaskPluginSubmitDiagnostics(c)
diagnostics.start(relayInfo)
var result *relay.TaskSubmitResult
@@ -494,6 +505,7 @@ func executeTaskSubmissionWith(
if lockedCh, ok := relayInfo.LockedChannel.(*model.Channel); ok && lockedCh != nil {
channel = lockedCh
policy.BeginAttempt(channel, relayInfo.UsingGroup)
if retryParam.GetRetry() > 0 {
if setupErr := middleware.SetupContextForSelectedChannel(c, channel, relayInfo.OriginModelName); setupErr != nil {
taskErr = service.TaskErrorWrapperLocal(setupErr.Err, "setup_locked_channel_failed", http.StatusInternalServerError)
@@ -505,7 +517,7 @@ func executeTaskSubmissionWith(
channel, channelErr = getChannel(c, relayInfo, retryParam)
if channelErr != nil {
logger.LogError(c, channelErr.Error())
taskErr = service.TaskErrorWrapperLocal(channelErr.Err, "get_channel_failed", http.StatusInternalServerError)
taskErr = service.TaskErrorWrapperLocal(channelErr.Err, "get_channel_failed", channelErr.StatusCode)
break
}
}
@@ -536,15 +548,19 @@ func executeTaskSubmissionWith(
break
}
taskAPIError := taskSubmissionAPIError(taskErr)
relayInfo.LastError = taskAPIError
decision := decideTaskRetry(c, taskErr, common.RetryTimes-retryParam.GetRetry())
service.RecordPolicyFailure(c, channel.Id, taskAPIError, decision)
if !taskErr.LocalError {
processChannelError(c,
*types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey,
common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()),
types.NewOpenAIError(taskErr.Error, types.ErrorCodeBadResponseStatusCode, taskErr.StatusCode),
taskAPIError,
relayInfo)
}
willRetry := shouldRetryTaskRelay(c, channel.Id, taskErr, common.RetryTimes-retryParam.GetRetry())
willRetry := decision.Action == "retry"
diagnostics.attemptFailed(retryParam.GetRetry()+1, channel, taskErr, willRetry)
if !willRetry {
break
@@ -646,6 +662,11 @@ func executeTaskSubmissionWith(
diagnostics.failed("settle", "billing_error", taskErr, true)
return nil, taskErr
}
if task.Status != model.TaskStatusFailure {
service.MarkRequestPolicySuccess(c, nil)
} else {
policy.AddEvent(service.PolicyEvent{Decision: service.PolicyDecision{Action: "stop", Reason: "task_failed", Source: "upstream"}})
}
service.LogTaskConsumption(c, relayInfo, task)
diagnostics.complete(task, result.Quota)
@@ -706,6 +727,7 @@ func presentTaskSubmission(c *gin.Context, outcome *taskSubmissionOutcome) {
}
func respondTaskSubmissionError(c *gin.Context, taskErr *taskdto.TaskError) {
service.RecordRequestPolicyTermination(c, taskSubmissionAPIError(taskErr))
newTaskPluginSubmitDiagnostics(c).presentError(taskErr)
if middleware.RespondTaskPluginError(c, taskErr) {
return
@@ -721,44 +743,53 @@ func respondTaskError(c *gin.Context, taskErr *taskdto.TaskError) {
c.JSON(taskErr.StatusCode, taskErr)
}
func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *taskdto.TaskError, retryTimes int) bool {
if taskErr == nil || taskErr.NoRetry {
return false
// taskSubmissionAPIError adapts a task error for the shared relay error paths.
// TaskError.Error is nil for many local rejections, so fall back to the message.
func taskSubmissionAPIError(taskErr *taskdto.TaskError) *types.NewAPIError {
err := taskErr.Error
if err == nil {
err = errors.New(taskErr.Message)
}
if service.ShouldSkipRetryAfterChannelAffinityFailure(c) {
return false
}
if retryTimes <= 0 {
return false
}
if service.GetChannelConstraints(c).SuppressesRetry() {
return false
}
if taskErr.StatusCode == http.StatusTooManyRequests {
return true
}
if taskErr.StatusCode == 307 {
return true
}
if taskErr.StatusCode/100 == 5 {
return types.NewOpenAIError(err, types.ErrorCodeBadResponseStatusCode, taskErr.StatusCode)
}
// decideTaskRetry is the single retry decision for task submissions. The
// reason is recorded in the request policy decision events of the log details.
func decideTaskRetry(c *gin.Context, taskErr *taskdto.TaskError, retryTimes int) service.PolicyDecision {
stop := service.PolicyDecision{Action: "stop", Source: "system"}
retry := service.PolicyDecision{Action: "retry", Reason: "retry_status_matched", Source: "system"}
switch {
case taskErr == nil:
stop.Reason = "request_completed"
case taskErr.NoRetry:
stop.Reason = "task_accepted"
case service.ShouldSkipRetryAfterChannelAffinityFailure(c):
stop.Reason, stop.Source = "strict_session", "session_rule"
if source := service.RequestPolicy(c).SessionModeSource; source != "" {
stop.Source = source
}
case retryTimes <= 0:
stop.Reason, stop.Source = "attempt_budget_exhausted", "global"
case service.GetChannelConstraints(c).SuppressesRetry():
stop.Reason, stop.Source = "pinned_channel", "channel_constraint"
case taskErr.StatusCode == http.StatusTooManyRequests, taskErr.StatusCode == 307:
return retry
case taskErr.StatusCode/100 == 5:
// 超时不重试
if operation_setting.IsAlwaysSkipRetryStatusCode(taskErr.StatusCode) {
return false
stop.Reason = "system_retry_exclusion"
break
}
return true
}
if taskErr.StatusCode == http.StatusBadRequest {
return false
}
if taskErr.StatusCode == 408 {
return retry
case taskErr.StatusCode == http.StatusBadRequest, taskErr.StatusCode == 408:
// azure处理超时不重试
return false
stop.Reason = "status_not_retryable"
case taskErr.LocalError:
stop.Reason = "local_rejection"
case taskErr.StatusCode/100 == 2:
stop.Reason = "system_retry_exclusion"
default:
return retry
}
if taskErr.LocalError {
return false
}
if taskErr.StatusCode/100 == 2 {
return false
}
return true
return stop
}
+18 -1
View File
@@ -539,7 +539,24 @@ export function buildQueryRequest(){throw new Error("completed submissions must
func TestAcceptedSubmitStreamNeverRetries(t *testing.T) {
c := taskSubmissionTestContext()
assert.False(t, shouldRetryTaskRelay(c, 1, &dto.TaskError{StatusCode: 502, LocalError: true, NoRetry: true}, 3))
assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "task_accepted", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: 502, LocalError: true, NoRetry: true}, 3))
}
// Local task rejections carry a message but no cause; the response and the
// decision record must still be produced.
func TestRespondTaskSubmissionErrorWithoutCause(t *testing.T) {
previousErrorLog := constant.ErrorLogEnabled
constant.ErrorLogEnabled = false
t.Cleanup(func() { constant.ErrorLogEnabled = previousErrorLog })
c := taskSubmissionTestContext()
taskErr := &dto.TaskError{Code: "get_channel_failed", Message: "no channel", StatusCode: http.StatusServiceUnavailable, LocalError: true}
require.NotPanics(t, func() { respondTaskSubmissionError(c, taskErr) })
assert.Equal(t, http.StatusServiceUnavailable, c.Writer.Status())
events := service.RequestPolicy(c).Events()
require.Len(t, events, 1)
assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "request_failed", Source: "system"}, events[0].Decision)
assert.Equal(t, http.StatusServiceUnavailable, events[0].Status)
assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "local_rejection", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusForbidden, LocalError: true, Message: "billing"}, 2), "local errors stop once the status rules do not force a retry")
}
func TestExecuteTaskSubmissionRefundsWhenFinalReserveFails(t *testing.T) {
+27
View File
@@ -0,0 +1,27 @@
package controller
import (
"net/http"
"github.com/QuantumNous/new-api/model"
"github.com/gin-gonic/gin"
)
func GetRequestPolicy(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"options": model.CurrentRequestPolicy().Options}})
}
func UpdateRequestPolicy(c *gin.Context) {
var request struct {
Options map[string]string `json:"options"`
}
if err := c.ShouldBindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": err.Error()})
return
}
if err := model.UpdateRequestPolicyOptions(request.Options); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": err.Error()})
return
}
GetRequestPolicy(c)
}
+10
View File
@@ -34,6 +34,12 @@ type ModelRequest struct {
func Distribute() func(c *gin.Context) {
return func(c *gin.Context) {
var channel *model.Channel
policy := service.RequestPolicy(c)
defer func() {
if c.Writer.Status() >= 400 {
service.RecordRequestPolicyTermination(c, types.NewErrorWithStatusCode(errors.New("request rejected"), types.ErrorCodeInvalidRequest, c.Writer.Status(), types.ErrOptionWithSkipRetry()))
}
}()
constraints := service.GetChannelConstraints(c)
constraints.AddFilter(taskdto.ChannelFilter{
Kind: taskdto.FilterRequestPath,
@@ -154,6 +160,10 @@ func Distribute() func(c *gin.Context) {
if !affinityUsable && !service.ShouldKeepChannelAffinityOnChannelDisabled() {
service.ClearCurrentChannelAffinityCache(c)
}
if !affinityUsable && policy.SessionMode == "strict" {
abortWithOpenAiMessage(c, http.StatusServiceUnavailable, "strict_session_binding_unavailable")
return
}
}
if channel == nil {
+33
View File
@@ -195,6 +195,13 @@ func InitOptionMap() {
}
func loadOptionsFromDatabase() {
requestPolicyOptionMutex.Lock()
defer requestPolicyOptionMutex.Unlock()
defer func() {
if err := refreshRequestPolicySnapshot(); err != nil {
common.SysError("invalid request policy: " + err.Error())
}
}()
passkeyOptionMutex.Lock()
defer passkeyOptionMutex.Unlock()
options, _ := AllOption()
@@ -234,6 +241,9 @@ func validateOptionValue(key string, value string) error {
}
func UpdateOption(key string, value string) error {
if IsRequestPolicyOption(key) {
return UpdateRequestPolicyOptions(map[string]string{key: value})
}
if IsPasskeyDomainOption(key) {
_, err := UpdatePasskeyDomainOptions(map[string]string{key: value}, false, "")
return err
@@ -279,6 +289,26 @@ func UpdateOptionsBulk(values map[string]string) error {
return err
}
}
var policySnapshot *RequestPolicySnapshot
for key := range values {
if IsRequestPolicyOption(key) {
requestPolicyOptionMutex.Lock()
defer requestPolicyOptionMutex.Unlock()
options := maps.Clone(CurrentRequestPolicy().Options)
for key, value := range values {
if IsRequestPolicyOption(key) {
options[key] = value
}
}
var err error
policySnapshot, err = BuildRequestPolicy(options)
if err != nil {
return err
}
break
}
}
err := DB.Transaction(func(tx *gorm.DB) error {
for k, v := range values {
option := Option{Key: k}
@@ -300,6 +330,9 @@ func UpdateOptionsBulk(values map[string]string) error {
return err
}
}
if policySnapshot != nil {
requestPolicySnapshot.Store(policySnapshot)
}
return nil
}
+258
View File
@@ -0,0 +1,258 @@
package model
import (
"encoding/json"
"fmt"
"maps"
"math"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/config"
"github.com/QuantumNous/new-api/setting/operation_setting"
"gorm.io/gorm"
)
// RequestPolicySnapshot is the validated read model behind the request policy
// settings API. It is rebuilt from the option map on every option write, so
// the runtime globals updated by the same write never disagree with it.
type RequestPolicySnapshot struct {
Affinity operation_setting.ChannelAffinitySetting
RetryTimes int
RetryCodes []operation_setting.StatusCodeRange
DisableCodes []operation_setting.StatusCodeRange
DisableKeywords []string
CheckText bool
TextKeywords []string
AutoDisable bool
Options map[string]string
}
var requestPolicySnapshot atomic.Pointer[RequestPolicySnapshot]
var requestPolicyOptionMutex sync.Mutex
var requestPolicyDefaults = requestPolicyDefaultOptions()
func requestPolicyDefaultOptions() map[string]string {
defaults := make(map[string]string)
for prefix, value := range map[string]any{
"channel_affinity_setting.": operation_setting.GetChannelAffinitySetting(),
"monitor_setting.": operation_setting.GetMonitorSetting(),
} {
fields, err := config.ConfigToMap(value)
if err != nil {
panic(err)
}
for field, value := range fields {
defaults[prefix+field] = value
}
}
defaults["RetryTimes"] = strconv.Itoa(common.RetryTimes)
defaults["AutomaticRetryStatusCodes"] = operation_setting.AutomaticRetryStatusCodesToString()
defaults["AutomaticDisableStatusCodes"] = operation_setting.AutomaticDisableStatusCodesToString()
defaults["AutomaticDisableKeywords"] = operation_setting.AutomaticDisableKeywordsToString()
defaults["AutomaticDisableChannelEnabled"] = strconv.FormatBool(common.AutomaticDisableChannelEnabled)
defaults["CheckSensitiveEnabled"] = strconv.FormatBool(setting.CheckSensitiveEnabled)
defaults["CheckSensitiveOnPromptEnabled"] = strconv.FormatBool(setting.CheckSensitiveOnPromptEnabled)
defaults["SensitiveWords"] = setting.SensitiveWordsToString()
defaults["AutomaticEnableChannelEnabled"] = strconv.FormatBool(common.AutomaticEnableChannelEnabled)
defaults["ChannelDisableThreshold"] = strconv.FormatFloat(common.ChannelDisableThreshold, 'f', -1, 64)
return defaults
}
func IsRequestPolicyOption(key string) bool {
if strings.HasPrefix(key, "channel_affinity_setting.") {
return true
}
switch key {
case "CheckSensitiveEnabled", "CheckSensitiveOnPromptEnabled", "SensitiveWords", "AutomaticEnableChannelEnabled", "ChannelDisableThreshold", "monitor_setting.auto_test_channel_enabled", "monitor_setting.auto_test_channel_minutes", "monitor_setting.channel_test_concurrency", "monitor_setting.channel_test_mode", "RetryTimes", "AutomaticRetryStatusCodes", "AutomaticDisableChannelEnabled", "AutomaticDisableStatusCodes", "AutomaticDisableKeywords":
return true
}
return false
}
func CurrentRequestPolicy() *RequestPolicySnapshot {
if snapshot := requestPolicySnapshot.Load(); snapshot != nil {
return snapshot
}
// Startup and test fixtures may not have loaded options yet.
snapshot, err := BuildRequestPolicy(nil)
if err != nil {
return &RequestPolicySnapshot{Options: map[string]string{}}
}
return snapshot
}
func BuildRequestPolicy(options map[string]string) (*RequestPolicySnapshot, error) {
defaults := requestPolicyDefaults
raw := make(map[string]string)
for key, value := range defaults {
if IsRequestPolicyOption(key) {
raw[key] = value
}
}
maps.Copy(raw, options)
snapshot := &RequestPolicySnapshot{Options: raw}
affinityFields := map[string]string{}
for key, value := range raw {
if field, ok := strings.CutPrefix(key, "channel_affinity_setting."); ok {
switch field {
case "enabled", "session_mode", "switch_on_success", "keep_on_channel_disabled", "max_entries", "default_ttl_seconds", "rules":
default:
return nil, fmt.Errorf("unknown affinity option: %s", key)
}
affinityFields[field] = value
}
}
// Decode through JSON so malformed scalar/array values cannot be silently ignored.
affinityJSON := map[string]json.RawMessage{}
for key, value := range affinityFields {
if key == "session_mode" {
encoded, _ := common.Marshal(value)
affinityJSON[key] = encoded
} else {
affinityJSON[key] = json.RawMessage(value)
}
}
encoded, err := common.Marshal(affinityJSON)
if err != nil {
return nil, err
}
if err := common.Unmarshal(encoded, &snapshot.Affinity); err != nil {
return nil, err
}
snapshot.RetryTimes, err = strconv.Atoi(raw["RetryTimes"])
if err != nil || snapshot.RetryTimes < 0 || snapshot.RetryTimes == math.MaxInt {
return nil, fmt.Errorf("retry times must be a non-negative integer with room for the initial attempt")
}
snapshot.AutoDisable, err = strconv.ParseBool(raw["AutomaticDisableChannelEnabled"])
if err != nil {
return nil, err
}
snapshot.RetryCodes, err = operation_setting.ParseHTTPStatusCodeRanges(raw["AutomaticRetryStatusCodes"])
if err != nil {
return nil, err
}
snapshot.DisableCodes, err = operation_setting.ParseHTTPStatusCodeRanges(raw["AutomaticDisableStatusCodes"])
if err != nil {
return nil, err
}
snapshot.DisableKeywords = strings.Split(raw["AutomaticDisableKeywords"], "\n")
for _, key := range []string{"CheckSensitiveEnabled", "CheckSensitiveOnPromptEnabled", "AutomaticEnableChannelEnabled", "monitor_setting.auto_test_channel_enabled"} {
if _, err := strconv.ParseBool(raw[key]); err != nil {
return nil, fmt.Errorf("invalid boolean: %s", key)
}
}
snapshot.CheckText = raw["CheckSensitiveEnabled"] == "true" && raw["CheckSensitiveOnPromptEnabled"] == "true"
for word := range strings.SplitSeq(raw["SensitiveWords"], "\n") {
if word = strings.TrimSpace(word); word != "" {
snapshot.TextKeywords = append(snapshot.TextKeywords, word)
}
}
if err := operation_setting.ValidateChannelTestConcurrency(raw["monitor_setting.channel_test_concurrency"]); err != nil {
return nil, err
}
for _, key := range []string{"ChannelDisableThreshold", "monitor_setting.auto_test_channel_minutes"} {
if raw[key] == "" && key == "ChannelDisableThreshold" {
continue
}
value, err := strconv.ParseFloat(raw[key], 64)
if err != nil || value < 0 || math.IsNaN(value) || math.IsInf(value, 0) {
return nil, fmt.Errorf("invalid numeric value: %s", key)
}
}
switch raw["monitor_setting.channel_test_mode"] {
case "scheduled_all", "auto_ban_only", "passive_recovery":
default:
return nil, fmt.Errorf("invalid channel test mode")
}
if snapshot.Affinity.MaxEntries < 0 || snapshot.Affinity.DefaultTTLSeconds < 0 {
return nil, fmt.Errorf("invalid affinity cache limits")
}
switch snapshot.Affinity.SessionMode {
case "", "off", "prefer", "strict":
default:
return nil, fmt.Errorf("invalid global session mode")
}
for _, rule := range snapshot.Affinity.Rules {
switch rule.SessionMode {
case "", "inherit", "off", "prefer", "strict":
default:
return nil, fmt.Errorf("invalid session mode for rule %q", rule.Name)
}
patterns := append(append([]string{}, rule.ModelRegex...), rule.PathRegex...)
if rule.ValueRegex != "" {
patterns = append(patterns, rule.ValueRegex)
}
for _, pattern := range patterns {
if _, err := regexp.Compile(pattern); err != nil {
return nil, fmt.Errorf("rule %q: %w", rule.Name, err)
}
}
if rule.TTLSeconds < 0 {
return nil, fmt.Errorf("negative affinity TTL")
}
}
return snapshot, nil
}
func refreshRequestPolicySnapshot() error {
common.OptionMapRWMutex.RLock()
options := make(map[string]string)
for key, value := range common.OptionMap {
if IsRequestPolicyOption(key) {
options[key] = value
}
}
common.OptionMapRWMutex.RUnlock()
snapshot, err := BuildRequestPolicy(options)
if err == nil {
requestPolicySnapshot.Store(snapshot)
}
return err
}
// UpdateRequestPolicyOptions validates the entire resulting policy before any
// write. Unknown JSON rule fields stay in the original option string.
func UpdateRequestPolicyOptions(values map[string]string) error {
requestPolicyOptionMutex.Lock()
defer requestPolicyOptionMutex.Unlock()
options := maps.Clone(CurrentRequestPolicy().Options)
for key, value := range values {
if !IsRequestPolicyOption(key) {
return fmt.Errorf("not a request policy option: %s", key)
}
options[key] = value
}
snapshot, err := BuildRequestPolicy(options)
if err != nil {
return err
}
if err := DB.Transaction(func(tx *gorm.DB) error {
for key, value := range values {
option := Option{Key: key}
if err := tx.FirstOrCreate(&option, Option{Key: key}).Error; err != nil {
return err
}
if err := tx.Model(&option).Update("value", value).Error; err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
for key, value := range values {
if err := updateOptionMap(key, value); err != nil {
return err
}
}
requestPolicySnapshot.Store(snapshot)
return nil
}
+122
View File
@@ -0,0 +1,122 @@
package model
import (
"errors"
"maps"
"math"
"os"
"strconv"
"testing"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/setting/operation_setting"
"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 TestRequestPolicyDatabaseMatrix(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 not configured")
}
driver = mysql.Open(dsn)
case "postgres":
dsn := os.Getenv("TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("TEST_POSTGRES_DSN not configured")
}
driver = postgres.Open(dsn)
}
db, err := gorm.Open(driver, &gorm.Config{NamingStrategy: schema.NamingStrategy{TablePrefix: "policy_test_"}})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
sqlDB.SetMaxOpenConns(1)
previousDB, previousType, previousSnapshot := DB, common.MainDatabaseType(), CurrentRequestPolicy()
common.OptionMapRWMutex.Lock()
previousOptions := maps.Clone(common.OptionMap)
common.OptionMap = maps.Clone(previousSnapshot.Options)
common.OptionMapRWMutex.Unlock()
DB = db
common.SetMainDatabaseType(common.DatabaseType(dialect))
initCol()
t.Cleanup(func() {
require.NoError(t, db.Migrator().DropTable(&Option{}))
for k, v := range previousSnapshot.Options {
require.NoError(t, updateOptionMap(k, v))
}
requestPolicySnapshot.Store(previousSnapshot)
common.OptionMapRWMutex.Lock()
common.OptionMap = previousOptions
common.OptionMapRWMutex.Unlock()
DB = previousDB
common.SetMainDatabaseType(previousType)
initCol()
require.NoError(t, sqlDB.Close())
})
require.NoError(t, db.AutoMigrate(&Option{}))
var version string
query := "SELECT version()"
if dialect == "sqlite" {
query = "SELECT sqlite_version()"
}
require.NoError(t, db.Raw(query).Scan(&version).Error)
t.Logf("database version: %s", version)
rules := `[{"name":"session","model_regex":[".*"],"key_sources":[{"type":"request_header","key":"X-Session"}],"ttl_seconds":0,"skip_retry_on_failure":false,"include_using_group":false,"param_override_template":{"temperature":0},"future_field":{"enabled":false}}]`
require.NoError(t, UpdateRequestPolicyOptions(map[string]string{"RetryTimes": "2", "channel_affinity_setting.rules": rules}))
assert.Equal(t, 2, CurrentRequestPolicy().RetryTimes)
assert.Equal(t, 2, common.RetryTimes, "the runtime global follows the same write")
require.NoError(t, UpdateOption("AutomaticRetryStatusCodes", "429,500-503"))
assert.Equal(t, "429,500-503", CurrentRequestPolicy().Options["AutomaticRetryStatusCodes"])
assert.Equal(t, "429,500-503", operation_setting.AutomaticRetryStatusCodesToString())
assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"request_policy_setting.mode": "off"}), "the removed mode switch is not a policy option")
assert.False(t, CurrentRequestPolicy().Affinity.Rules[0].SkipRetryOnFailure)
assert.Equal(t, rules, CurrentRequestPolicy().Options["channel_affinity_setting.rules"])
loadOptionsFromDatabase()
loadOptionsFromDatabase()
assert.Equal(t, rules, CurrentRequestPolicy().Options["channel_affinity_setting.rules"], "legacy rule JSON survives reloads without dropping extension fields")
require.NoError(t, UpdateRequestPolicyOptions(map[string]string{"channel_affinity_setting.session_mode": "strict"}))
loadOptionsFromDatabase()
loadOptionsFromDatabase()
assert.Equal(t, "strict", CurrentRequestPolicy().Affinity.SessionMode)
assert.Equal(t, rules, CurrentRequestPolicy().Options["channel_affinity_setting.rules"], "a global mode never rewrites rule fields")
snapshot := CurrentRequestPolicy()
assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"channel_affinity_setting.session_mode": "unknown"}))
assert.Same(t, snapshot, CurrentRequestPolicy())
for _, value := range []string{"-1", "1.5", "bad", strconv.Itoa(math.MaxInt)} {
assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"RetryTimes": value}))
assert.Same(t, snapshot, CurrentRequestPolicy())
}
assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"channel_affinity_setting.rules": "[", "RetryTimes": "8"}))
assert.Same(t, snapshot, CurrentRequestPolicy())
var option Option
require.NoError(t, db.Where(map[string]any{"key": "RetryTimes"}).First(&option).Error)
assert.Equal(t, "2", option.Value)
require.NoError(t, db.Callback().Update().Before("gorm:update").Register("policy_fail", func(tx *gorm.DB) {
if tx.Statement.Table == "policy_test_options" {
tx.AddError(errors.New("save rejected"))
}
}))
assert.Error(t, UpdateRequestPolicyOptions(map[string]string{"RetryTimes": "8", "channel_affinity_setting.session_mode": "off"}))
assert.Same(t, snapshot, CurrentRequestPolicy())
require.NoError(t, db.Callback().Update().Remove("policy_fail"))
option = Option{}
require.NoError(t, db.Where(map[string]any{"key": "RetryTimes"}).First(&option).Error)
assert.Equal(t, "2", option.Value)
loadOptionsFromDatabase()
assert.Equal(t, "strict", CurrentRequestPolicy().Affinity.SessionMode, "a failed save keeps the persisted global mode")
})
}
}
+22 -10
View File
@@ -2,7 +2,6 @@ package relay
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
@@ -125,7 +124,7 @@ func RelayMidjourneyNotify(c *gin.Context) *dto.MidjourneyResponse {
midjourneyTask.FinishTime = midjRequest.FinishTime
midjourneyTask.ImageUrl = midjRequest.ImageUrl
midjourneyTask.VideoUrl = midjRequest.VideoUrl
videoUrlsStr, _ := json.Marshal(midjRequest.VideoUrls)
videoUrlsStr, _ := common.Marshal(midjRequest.VideoUrls)
midjourneyTask.VideoUrls = string(videoUrlsStr)
midjourneyTask.Status = midjRequest.Status
midjourneyTask.FailReason = midjRequest.FailReason
@@ -167,21 +166,21 @@ func coverMidjourneyTaskDto(c *gin.Context, originTask *model.Midjourney) (midjo
midjourneyTask.Prompt = originTask.Prompt
if originTask.Buttons != "" {
var buttons []dto.ActionButton
err := json.Unmarshal([]byte(originTask.Buttons), &buttons)
err := common.Unmarshal([]byte(originTask.Buttons), &buttons)
if err == nil {
midjourneyTask.Buttons = buttons
}
}
if originTask.VideoUrls != "" {
var videoUrls []dto.ImgUrls
err := json.Unmarshal([]byte(originTask.VideoUrls), &videoUrls)
err := common.Unmarshal([]byte(originTask.VideoUrls), &videoUrls)
if err == nil {
midjourneyTask.VideoUrls = videoUrls
}
}
if originTask.Properties != "" {
var properties dto.Properties
err := json.Unmarshal([]byte(originTask.Properties), &properties)
err := common.Unmarshal([]byte(originTask.Properties), &properties)
if err == nil {
midjourneyTask.Properties = &properties
}
@@ -228,7 +227,9 @@ func RelaySwapFace(c *gin.Context, info *relaycommon.RelayInfo) *dto.MidjourneyR
requestURL := getMjRequestPath(c.Request.URL.String())
baseURL := c.GetString("base_url")
fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL)
service.RequestPolicy(c).BeginAttempt(&model.Channel{Id: c.GetInt("channel_id")}, info.UsingGroup)
mjResp, _, err := service.DoMidjourneyHttpRequest(c, time.Second*60, fullRequestURL)
accepted := service.RecordMidjourneyPolicyResponse(c, mjResp, err)
if err != nil {
return &mjResp.Response
}
@@ -268,11 +269,15 @@ func RelaySwapFace(c *gin.Context, info *relaycommon.RelayInfo) *dto.MidjourneyR
if billingErr != nil {
common.SysLog("error settling Midjourney quota: " + billingErr.Error())
}
if accepted {
service.MarkRequestPolicySuccess(c, nil)
}
if billingApplied {
billingChannelId := midjourneyTask.GetBillingChannelId()
tokenName := c.GetString("token_name")
logContent := fmt.Sprintf("模型固定价格 %.2f,分组倍率 %.2f,操作 %s", priceData.ModelPrice, priceData.GroupRatioInfo.GroupRatio, constant.MjActionSwapFace)
other := service.GenerateMjOtherInfo(info, priceData)
service.AppendRelayLogAdminInfo(c, info, other)
model.RecordConsumeLog(c, info.UserId, model.RecordConsumeLogParams{
ChannelId: billingChannelId,
ModelName: modelName,
@@ -287,7 +292,7 @@ func RelaySwapFace(c *gin.Context, info *relaycommon.RelayInfo) *dto.MidjourneyR
model.UpdateChannelUsedQuota(billingChannelId, midjourneyTask.Quota)
}
c.Writer.WriteHeader(mjResp.StatusCode)
respBody, err := json.Marshal(midjResponse)
respBody, err := common.Marshal(midjResponse)
if err != nil {
return service.MidjourneyErrorWrapper(constant.MjRequestError, "unmarshal_response_body_failed")
}
@@ -323,7 +328,7 @@ func RelayMidjourneyTaskImageSeed(c *gin.Context) *dto.MidjourneyResponse {
}
midjResponse := &midjResponseWithStatus.Response
c.Writer.WriteHeader(midjResponseWithStatus.StatusCode)
respBody, err := json.Marshal(midjResponse)
respBody, err := common.Marshal(midjResponse)
if err != nil {
return service.MidjourneyErrorWrapper(constant.MjRequestError, "unmarshal_response_body_failed")
}
@@ -346,7 +351,7 @@ func RelayMidjourneyTask(c *gin.Context, relayMode int) *dto.MidjourneyResponse
}
}
midjourneyTask := coverMidjourneyTaskDto(c, originTask)
respBody, err = json.Marshal(midjourneyTask)
respBody, err = common.Marshal(midjourneyTask)
if err != nil {
return &dto.MidjourneyResponse{
Code: 4,
@@ -375,7 +380,7 @@ func RelayMidjourneyTask(c *gin.Context, relayMode int) *dto.MidjourneyResponse
if tasks == nil {
tasks = make([]dto.MidjourneyDto, 0)
}
respBody, err = json.Marshal(tasks)
respBody, err = common.Marshal(tasks)
if err != nil {
return &dto.MidjourneyResponse{
Code: 4,
@@ -539,7 +544,9 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt
}
}
service.RequestPolicy(c).BeginAttempt(&model.Channel{Id: c.GetInt("channel_id")}, relayInfo.UsingGroup)
midjResponseWithStatus, responseBody, err := service.DoMidjourneyHttpRequest(c, time.Second*60, fullRequestURL)
accepted := service.RecordMidjourneyPolicyResponse(c, midjResponseWithStatus, err)
if err != nil {
return &midjResponseWithStatus.Response
}
@@ -576,9 +583,10 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt
if err != nil {
common.SysLog("get_channel_null: " + err.Error())
}
if channel.GetAutoBan() && common.AutomaticDisableChannelEnabled {
if channel != nil && channel.GetAutoBan() && common.AutomaticDisableChannelEnabled {
if model.UpdateChannelStatus(midjourneyTask.ChannelId, "", common.ChannelStatusManuallyDisabled, "No available account instance") {
service.CloseActiveWebSocketsForChannel(midjourneyTask.ChannelId, service.ChannelDisabledCloseReason)
service.RequestPolicy(c).AddEvent(service.PolicyEvent{ChannelID: midjourneyTask.ChannelId, Decision: service.PolicyDecision{Action: "stop", Reason: "task_failed", Source: "upstream"}, Health: "channel_disable_requested"})
}
}
}
@@ -635,11 +643,15 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt
if billingErr != nil {
common.SysLog("error settling Midjourney quota: " + billingErr.Error())
}
if accepted {
service.MarkRequestPolicySuccess(c, nil)
}
if billingApplied {
billingChannelId := midjourneyTask.GetBillingChannelId()
tokenName := c.GetString("token_name")
logContent := fmt.Sprintf("模型固定价格 %.2f,分组倍率 %.2f,操作 %s,ID %s", priceData.ModelPrice, priceData.GroupRatioInfo.GroupRatio, midjRequest.Action, midjResponse.Result)
other := service.GenerateMjOtherInfo(relayInfo, priceData)
service.AppendRelayLogAdminInfo(c, relayInfo, other)
model.RecordConsumeLog(c, relayInfo.UserId, model.RecordConsumeLogParams{
ChannelId: billingChannelId,
ModelName: modelName,
+1
View File
@@ -42,6 +42,7 @@ func PrepareRequestBilling(c *gin.Context, info *relaycommon.RelayInfo) *types.N
if needSensitiveCheck && meta != nil {
if contains, words := service.CheckSensitiveText(meta.CombineText); contains {
service.RequestPolicy(c).AddEvent(service.PolicyEvent{ErrorCode: string(types.ErrorCodeSensitiveWordsDetected), ErrorSource: "local", Decision: service.PolicyDecision{Action: "stop", Reason: "local_rejection", Source: "global"}, Health: "unchanged"})
message := fmt.Sprintf("user sensitive words detected: %s", strings.Join(words, ", "))
logger.LogWarn(c, message)
return types.NewError(errors.New(message), types.ErrorCodeSensitiveWordsDetected)
+2
View File
@@ -204,6 +204,8 @@ func SetApiRouter(router *gin.Engine) {
optionRoute.Use(middleware.RootAuth())
{
optionRoute.GET("/", controller.GetOptions)
optionRoute.GET("/request_policy", controller.GetRequestPolicy)
optionRoute.PATCH("/request_policy", controller.UpdateRequestPolicy)
optionRoute.PUT("/", controller.UpdateOption)
optionRoute.PUT("/passkey/domains", controller.UpdatePasskeyDomains)
optionRoute.GET("/model_pricing", controller.GetModelPricingConfig)
+18 -1
View File
@@ -549,6 +549,7 @@ func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[stri
func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool) {
setting := operation_setting.GetChannelAffinitySetting()
state := RequestPolicy(c)
if setting == nil || !setting.Enabled {
return 0, false
}
@@ -593,11 +594,13 @@ func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup
}
cacheKeySuffix := buildChannelAffinityCacheKeySuffix(rule, modelName, usingGroup, affinityValue)
cacheKeyFull := channelAffinityCacheNamespace + ":" + cacheKeySuffix
state.SessionMode, state.SessionModeSource = EffectiveSessionMode(setting, rule)
state.RuleName = rule.Name
setChannelAffinityContext(c, channelAffinityMeta{
CacheKey: cacheKeyFull,
TTLSeconds: ttlSeconds,
RuleName: rule.Name,
SkipRetry: rule.SkipRetryOnFailure,
SkipRetry: state.SessionMode == "strict",
ParamTemplate: cloneStringAnyMap(rule.ParamOverrideTemplate),
KeySourceType: strings.TrimSpace(usedSource.Type),
KeySourceKey: strings.TrimSpace(usedSource.Key),
@@ -609,6 +612,10 @@ func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup
RequestPath: path,
})
state.AddEvent(PolicyEvent{Decision: PolicyDecision{Action: "match", Reason: "session_rule_matched", Source: "session_rule"}})
if state.SessionMode == "off" {
return 0, false
}
cache := getChannelAffinityCache()
channelID, found, err := cache.Get(cacheKeySuffix)
if err != nil {
@@ -707,6 +714,13 @@ func AppendChannelAffinityAdminInfo(c *gin.Context, other *model.LogOther) {
if !ok || anyInfo == nil {
return
}
// The hint can be the whole session value for short keys; logs keep only
// the fingerprint.
if info, ok := anyInfo.(map[string]any); ok {
sanitized := cloneStringAnyMap(info)
delete(sanitized, "key_hint")
anyInfo = sanitized
}
other.SetAdmin("channel_affinity", anyInfo)
}
@@ -715,6 +729,9 @@ func RecordChannelAffinity(c *gin.Context, channelID int) {
return
}
setting := operation_setting.GetChannelAffinitySetting()
if RequestPolicy(c).SessionMode == "off" {
return
}
if setting == nil || !setting.Enabled {
return
}
+133
View File
@@ -1,6 +1,7 @@
package service
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -8,9 +9,14 @@ import (
"testing"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -332,3 +338,130 @@ func TestChannelAffinityHitCodexTemplatePassHeadersEffective(t *testing.T) {
_, exists = info.RuntimeHeadersOverride["x-codex-turn-metadata"]
require.False(t, exists)
}
func TestMidjourneyPolicyAcceptance(t *testing.T) {
for _, tc := range []struct {
name string
status int
code int
properties map[string]any
requestErr error
accepted bool
reason string
}{
{name: "submitted", status: 200, code: 1, accepted: true},
{name: "existing task", status: 200, code: 21, accepted: true},
{name: "queued", status: 200, code: 22, accepted: true},
{name: "HTTP 200 with rejected prompt", status: 200, code: 24, reason: "non_retryable_error"},
{name: "failed existing task", status: 200, code: 21, properties: map[string]any{"status": "FAILURE"}, reason: "task_accepted"},
{name: "HTTP failure", status: 502, code: 1, reason: "non_retryable_error"},
{name: "ambiguous transport failure", status: 502, requestErr: errors.New("connection reset"), reason: "non_retryable_error"},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
ctx.Request = httptest.NewRequest(http.MethodPost, "/mj/submit/imagine", strings.NewReader(`{}`))
ctx.Set("channel_id", 7)
state := RequestPolicy(ctx)
state.BeginAttempt(&model.Channel{Id: 7}, "default")
response := &dto.MidjourneyResponseWithStatusCode{StatusCode: tc.status, Response: dto.MidjourneyResponse{Code: tc.code, Properties: tc.properties}}
accepted := RecordMidjourneyPolicyResponse(ctx, response, tc.requestErr)
assert.Equal(t, tc.accepted, accepted)
assert.False(t, state.Successful, "acceptance alone must not bind before local processing finishes")
if accepted {
MarkRequestPolicySuccess(ctx, nil)
assert.True(t, state.Successful)
return
}
events := state.Events()
require.Len(t, events, 3)
assert.Equal(t, PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: "upstream"}, events[1].Decision)
assert.Equal(t, tc.status, events[1].Status)
assert.Equal(t, PolicyDecision{Action: "stop", Reason: tc.reason, Source: "system"}, events[2].Decision, "submissions are never replayed")
})
}
}
func TestSessionRulesInheritOrOverrideGlobalDefault(t *testing.T) {
setting := operation_setting.GetChannelAffinitySetting()
previous := *setting
t.Cleanup(func() { *setting = previous })
for _, globalMode := range []string{"", "off", "prefer", "strict"} {
for _, tc := range []struct {
name, mode, expected string
skipRetry bool
}{
{name: "inherit", mode: "inherit", expected: globalMode},
{name: "override-strict", mode: "strict", expected: "strict"},
{name: "override-prefer", mode: "prefer", expected: "prefer", skipRetry: true},
{name: "override-off", mode: "off", expected: "off", skipRetry: true},
{name: "legacy-strict", expected: "strict", skipRetry: true},
{name: "legacy-prefer", expected: "prefer"},
} {
t.Run(globalMode+"/"+tc.name, func(t *testing.T) {
expected := tc.expected
if expected == "" {
expected = "prefer"
}
source := "session_rule"
if tc.mode == "inherit" {
source = "global"
}
rule := operation_setting.ChannelAffinityRule{
Name: tc.name, ModelRegex: []string{"^test-model$"},
KeySources: []operation_setting.ChannelAffinityKeySource{{Type: "request_header", Key: "X-Session"}},
SessionMode: tc.mode, SkipRetryOnFailure: tc.skipRetry,
ParamOverrideTemplate: map[string]any{"temperature": 0}, IncludeRuleName: true,
}
encoded, err := common.Marshal([]operation_setting.ChannelAffinityRule{rule})
require.NoError(t, err)
snapshot, err := model.BuildRequestPolicy(map[string]string{"RetryTimes": "2", "channel_affinity_setting.enabled": "true", "channel_affinity_setting.session_mode": globalMode, "channel_affinity_setting.rules": string(encoded)})
require.NoError(t, err)
*setting = snapshot.Affinity
key := t.Name()
cacheKey := buildChannelAffinityCacheKeySuffix(rule, "test-model", "default", key)
cache := getChannelAffinityCache()
require.NoError(t, cache.SetWithTTL(cacheKey, 1, time.Minute))
t.Cleanup(func() { _, err := cache.DeleteMany([]string{cacheKey}); assert.NoError(t, err) })
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
ctx.Request.Header.Set("X-Session", key)
state := RequestPolicy(ctx)
channelID, found := GetPreferredChannelByAffinity(ctx, "test-model", "default")
assert.Equal(t, expected != "off", found)
if found {
assert.Equal(t, 1, channelID)
}
assert.Equal(t, expected, state.SessionMode)
assert.Equal(t, source, state.SessionModeSource)
assert.Equal(t, expected == "strict", ShouldSkipRetryAfterChannelAffinityFailure(ctx))
decision := DecideRelayRetry(ctx, types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, http.StatusTooManyRequests), 2)
if expected == "strict" {
assert.Equal(t, PolicyDecision{Action: "stop", Reason: "strict_session", Source: source}, decision)
} else {
assert.Equal(t, "retry", decision.Action)
}
events := state.Events()
require.Len(t, events, 1)
assert.Equal(t, PolicyDecision{Action: "match", Reason: "session_rule_matched", Source: "session_rule"}, events[0].Decision)
assert.Equal(t, tc.name, events[0].Rule)
transformed, applied := ApplyChannelAffinityOverrideTemplate(ctx, nil)
assert.True(t, applied, "session behavior does not disable request transforms")
assert.EqualValues(t, 0, transformed["temperature"])
if expected == "off" {
ctx.Set("channel_id", 9)
RecordChannelAffinity(ctx, 9)
cached, found, err := cache.Get(cacheKey)
require.NoError(t, err)
assert.True(t, found)
assert.Equal(t, 1, cached, "off does not refresh session bindings")
_, err = cache.DeleteMany([]string{cacheKey})
require.NoError(t, err)
RecordChannelAffinity(ctx, 9)
_, found, err = cache.Get(cacheKey)
require.NoError(t, err)
assert.False(t, found, "off does not establish session bindings")
}
})
}
}
}
+4
View File
@@ -92,10 +92,14 @@ func AppendRelayLogAdminInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo,
}
AppendChannelAffinityAdminInfo(ctx, other)
if events := RequestPolicy(ctx).Events(); len(events) > 0 {
other.SetAdmin("request_policy", events)
}
}
func GenerateTextOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelRatio, groupRatio, completionRatio float64,
cacheTokens int, cacheRatio float64, modelPrice float64, userGroupRatio float64) *model.LogOther {
MarkRequestPolicySuccess(ctx, relayInfo.StreamStatus)
other := model.NewLogOther()
other.SetPublic("model_ratio", modelRatio)
other.SetPublic("group_ratio", groupRatio)
+29 -5
View File
@@ -2,7 +2,6 @@ package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -273,6 +272,31 @@ func ConvertSimpleChangeParams(content string) *dto.MidjourneyRequest {
return changeParams
}
// RecordMidjourneyPolicyResponse distinguishes accepted tasks from errors inside
// HTTP 200 responses. Submissions are single-attempt: an ambiguous transport
// failure must never create a duplicate task on another channel.
func RecordMidjourneyPolicyResponse(c *gin.Context, response *dto.MidjourneyResponseWithStatusCode, requestErr error) bool {
if response == nil {
response = MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "empty_response", http.StatusBadGateway)
}
accepted := requestErr == nil && response.StatusCode == http.StatusOK && (response.Response.Code == 1 || response.Response.Code == 21 || response.Response.Code == 22)
if accepted {
properties, _ := response.Response.Properties.(map[string]any)
if properties["status"] != "FAILURE" {
return true
}
}
state := RequestPolicy(c)
event := PolicyEvent{ChannelID: c.GetInt("channel_id"), Status: response.StatusCode, ErrorCode: strconv.Itoa(response.Response.Code), ErrorSource: "upstream", Decision: PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: "upstream"}}
state.AddEvent(event)
event.Decision, event.Health = PolicyDecision{Action: "stop", Reason: "non_retryable_error", Source: "system"}, "unchanged"
if accepted {
event.Decision.Reason = "task_accepted"
}
state.AddEvent(event)
return false
}
func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestURL string) (*dto.MidjourneyResponseWithStatusCode, []byte, error) {
var nullBytes []byte
//var requestBody io.Reader
@@ -281,7 +305,7 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU
var mapResult map[string]any
// if get request, no need to read request body
if c.Request.Method != "GET" {
err := json.NewDecoder(c.Request.Body).Decode(&mapResult)
err := common.DecodeJson(c.Request.Body, &mapResult)
if err != nil {
return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "read_request_body_failed", http.StatusInternalServerError), nullBytes, err
}
@@ -303,7 +327,7 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU
mapResult["prompt"] = prompt
}
}
reqBody, err := json.Marshal(mapResult)
reqBody, err := common.Marshal(mapResult)
if err != nil {
return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "marshal_request_body_failed", http.StatusInternalServerError), nullBytes, err
}
@@ -350,9 +374,9 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU
if len(responseBody) == 0 {
return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "empty_response_body", statusCode), responseBody, nil
} else {
err = json.Unmarshal(responseBody, &midjResponse)
err = common.Unmarshal(responseBody, &midjResponse)
if err != nil {
err2 := json.Unmarshal(responseBody, &midjourneyUploadsResponse)
err2 := common.Unmarshal(responseBody, &midjourneyUploadsResponse)
if err2 != nil {
return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "unmarshal_response_body_failed", statusCode), responseBody, err
}
+29 -16
View File
@@ -16,36 +16,49 @@ import (
"github.com/gin-gonic/gin"
)
func ShouldRetryRelayError(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
if openaiErr == nil {
return false
// DecideRelayRetry is the single retry decision for relay attempts. The reason
// is recorded in the request policy decision events of the log details.
func DecideRelayRetry(c *gin.Context, err *types.NewAPIError, retryTimes int) PolicyDecision {
if err == nil {
return PolicyDecision{Action: "stop", Reason: "request_completed", Source: "system"}
}
if ShouldSkipRetryAfterChannelAffinityFailure(c) {
return false
source := RequestPolicy(c).SessionModeSource
if source == "" {
source = "session_rule"
}
return PolicyDecision{Action: "stop", Reason: "strict_session", Source: source}
}
if GetChannelConstraints(c).SuppressesRetry() {
return false
return PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"}
}
if types.IsChannelError(openaiErr) {
return true
if types.IsChannelError(err) {
return PolicyDecision{Action: "retry", Reason: "channel_error", Source: "system"}
}
if types.IsSkipRetryError(openaiErr) {
return false
if types.IsSkipRetryError(err) {
return PolicyDecision{Action: "stop", Reason: "non_retryable_error", Source: "system"}
}
if retryTimes <= 0 {
return false
return PolicyDecision{Action: "stop", Reason: "attempt_budget_exhausted", Source: "global"}
}
code := openaiErr.StatusCode
code := err.StatusCode
if code >= 200 && code < 300 {
return false
return PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"}
}
if code < 100 || code > 599 {
return true
return PolicyDecision{Action: "retry", Reason: "unrecognized_status", Source: "system"}
}
if operation_setting.IsAlwaysSkipRetryCode(openaiErr.GetErrorCode()) {
return false
if operation_setting.IsAlwaysSkipRetryCode(err.GetErrorCode()) || operation_setting.IsAlwaysSkipRetryStatusCode(code) {
return PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"}
}
return operation_setting.ShouldRetryByStatusCode(code)
if operation_setting.ShouldRetryByStatusCode(code) {
return PolicyDecision{Action: "retry", Reason: "retry_status_matched", Source: "global"}
}
return PolicyDecision{Action: "stop", Reason: "status_not_retryable", Source: "global"}
}
func ShouldRetryRelayError(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
return DecideRelayRetry(c, openaiErr, retryTimes).Action == "retry"
}
func ProcessChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError, relayInfo *relaycommon.RelayInfo) {
+87
View File
@@ -124,3 +124,90 @@ func TestProcessChannelErrorMasksDisableReasonAndNotification(t *testing.T) {
assert.NotContains(t, notification.Content, "review-secret")
assert.Equal(t, http.StatusUnauthorized, apiErr.StatusCode)
}
func TestDecideRelayRetryReasons(t *testing.T) {
upstream := func(status int) *types.NewAPIError {
return types.NewOpenAIError(errors.New("upstream"), types.ErrorCodeBadResponseStatusCode, status)
}
for _, tc := range []struct {
name string
err *types.NewAPIError
retries int
setup func(*gin.Context)
want PolicyDecision
}{
{name: "retry status matched", err: upstream(http.StatusTooManyRequests), retries: 1, want: PolicyDecision{Action: "retry", Reason: "retry_status_matched", Source: "global"}},
{name: "status outside retry rules", err: upstream(http.StatusBadRequest), retries: 1, want: PolicyDecision{Action: "stop", Reason: "status_not_retryable", Source: "global"}},
{name: "attempt budget exhausted", err: upstream(http.StatusTooManyRequests), retries: 0, want: PolicyDecision{Action: "stop", Reason: "attempt_budget_exhausted", Source: "global"}},
{name: "always skipped status", err: upstream(http.StatusGatewayTimeout), retries: 1, want: PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"}},
{name: "success status never retries", err: upstream(http.StatusOK), retries: 1, want: PolicyDecision{Action: "stop", Reason: "system_retry_exclusion", Source: "system"}},
{name: "skip retry error", err: types.NewErrorWithStatusCode(errors.New("local"), types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry()), retries: 1, want: PolicyDecision{Action: "stop", Reason: "non_retryable_error", Source: "system"}},
{name: "channel error retries without budget", err: types.NewError(errors.New("no key"), types.ErrorCodeChannelNoAvailableKey), retries: 0, want: PolicyDecision{Action: "retry", Reason: "channel_error", Source: "system"}},
{name: "single attempt pin", err: upstream(http.StatusTooManyRequests), retries: 1, setup: func(c *gin.Context) {
GetChannelConstraints(c).AddPin(dto.ChannelPin{ChannelId: 1, Source: dto.PinSourceToken, Rank: dto.PinRankToken, RetryMode: dto.PinRetrySingleAttempt})
}, want: PolicyDecision{Action: "stop", Reason: "pinned_channel", Source: "channel_constraint"}},
{name: "strict session", err: upstream(http.StatusTooManyRequests), retries: 1, setup: func(c *gin.Context) {
c.Set(ginKeyChannelAffinitySkipRetry, true)
RequestPolicy(c).SessionModeSource = "global"
}, want: PolicyDecision{Action: "stop", Reason: "strict_session", Source: "global"}},
{name: "nil error", retries: 1, want: PolicyDecision{Action: "stop", Reason: "request_completed", Source: "system"}},
} {
t.Run(tc.name, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
if tc.setup != nil {
tc.setup(c)
}
decision := DecideRelayRetry(c, tc.err, tc.retries)
assert.Equal(t, tc.want, decision)
assert.Equal(t, tc.want.Action == "retry", ShouldRetryRelayError(c, tc.err, tc.retries))
})
}
}
func TestRequestPolicyEventsReachLogAdminInfo(t *testing.T) {
previousAutoDisable := common.AutomaticDisableChannelEnabled
common.AutomaticDisableChannelEnabled = true
t.Cleanup(func() { common.AutomaticDisableChannelEnabled = previousAutoDisable })
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
c.Set("auto_ban", true)
c.Set("channel_id", 7)
state := RequestPolicy(c)
state.BeginAttempt(&model.Channel{Id: 7}, "default")
apiErr := types.NewOpenAIError(errors.New("invalid credential"), types.ErrorCodeBadResponseStatusCode, http.StatusUnauthorized)
RecordPolicyFailure(c, 7, apiErr, DecideRelayRetry(c, apiErr, 0))
failed := model.NewLogOther()
AppendRelayLogAdminInfo(c, nil, failed)
events, ok := failed.Snapshot()["admin_info"].(map[string]any)["request_policy"].([]PolicyEvent)
require.True(t, ok, "a failed relay exposes its decision events to administrators")
require.Len(t, events, 3)
assert.Equal(t, PolicyDecision{Action: "attempt", Reason: "channel_selected", Source: "routing"}, events[0].Decision)
assert.Equal(t, "default", events[0].Group)
assert.Equal(t, PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: "upstream"}, events[1].Decision)
assert.Equal(t, http.StatusUnauthorized, events[1].Status)
assert.Equal(t, PolicyDecision{Action: "stop", Reason: "attempt_budget_exhausted", Source: "global"}, events[2].Decision)
assert.Equal(t, "channel_disable_requested", events[2].Health, "the health entry follows the automatic disable rules")
common.SetContextKey(c, constant.ContextKeyChannelIsMultiKey, true)
RecordPolicyFailure(c, 7, apiErr, DecideRelayRetry(c, apiErr, 0))
assert.Equal(t, "key_disable_requested", state.Events()[4].Health)
state.BeginAttempt(&model.Channel{Id: 8}, "default")
c.Set("channel_id", 8)
MarkRequestPolicySuccess(c, nil)
MarkRequestPolicySuccess(c, nil)
succeeded := model.NewLogOther()
AppendRelayLogAdminInfo(c, nil, succeeded)
events, ok = succeeded.Snapshot()["admin_info"].(map[string]any)["request_policy"].([]PolicyEvent)
require.True(t, ok, "a successful relay exposes its decision events to administrators")
require.Len(t, events, 7, "the outcome is recorded once")
assert.Equal(t, PolicyDecision{Action: "success", Reason: "request_completed", Source: "upstream"}, events[6].Decision)
assert.Equal(t, 8, events[6].ChannelID)
assert.Equal(t, 2, events[6].Attempt)
assert.True(t, state.Successful)
untouched, _ := gin.CreateTestContext(httptest.NewRecorder())
other := model.NewLogOther()
AppendRelayLogAdminInfo(untouched, nil, other)
assert.NotContains(t, other.Snapshot()["admin_info"], "request_policy", "requests without decisions do not carry an empty record")
}
+182
View File
@@ -0,0 +1,182 @@
package service
import (
"slices"
"sync"
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/setting/operation_setting"
"github.com/gin-gonic/gin"
)
const requestPolicyContextKey = "request_policy_state"
type PolicyDecision struct {
Action string `json:"action"`
Reason string `json:"reason"`
Source string `json:"source"`
}
type PolicyEvent struct {
Attempt int `json:"attempt"`
ChannelID int `json:"channel_id,omitempty"`
Group string `json:"group,omitempty"`
Rule string `json:"rule,omitempty"`
Status int `json:"status,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
ErrorSource string `json:"error_source,omitempty"`
ElapsedMS int64 `json:"elapsed_ms"`
Decision PolicyDecision `json:"decision"`
Health string `json:"health,omitempty"`
}
// RequestPolicyState records how one request was routed so administrators can
// read the decision flow in the log details. Channel selection and the retry
// decision stay in the relay flows; this state only records them.
type RequestPolicyState struct {
FinalLogged bool
StartedAt time.Time
Attempts int
SelectedGroup string
SessionMode string
SessionModeSource string
RuleName string
Successful bool
OutcomeRecorded bool
mu sync.Mutex
events []PolicyEvent
}
func RequestPolicy(c *gin.Context) *RequestPolicyState {
if c != nil {
if value, ok := c.Get(requestPolicyContextKey); ok {
return value.(*RequestPolicyState)
}
}
state := &RequestPolicyState{StartedAt: time.Now()}
if c != nil {
c.Set(requestPolicyContextKey, state)
}
return state
}
func (s *RequestPolicyState) AddEvent(event PolicyEvent) {
event.Attempt, event.ElapsedMS = s.Attempts, time.Since(s.StartedAt).Milliseconds()
if event.Group == "" {
event.Group = s.SelectedGroup
}
if event.Rule == "" {
event.Rule = s.RuleName
}
s.mu.Lock()
defer s.mu.Unlock()
if len(s.events) < 512 {
s.events = append(s.events, event)
}
}
func (s *RequestPolicyState) Events() []PolicyEvent {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Clone(s.events)
}
func (s *RequestPolicyState) BeginAttempt(channel *model.Channel, group string) {
s.Attempts++
s.Successful = false
s.OutcomeRecorded = false
s.SelectedGroup = group
s.AddEvent(PolicyEvent{ChannelID: channel.Id, Decision: PolicyDecision{Action: "attempt", Reason: "channel_selected", Source: "routing"}})
}
// RecordPolicyFailure appends the failed attempt and the retry decision made
// for it. The health entry mirrors the check in ProcessChannelError, which
// performs the actual disable.
func RecordPolicyFailure(c *gin.Context, channelID int, err *types.NewAPIError, decision PolicyDecision) {
if c == nil || err == nil {
return
}
source := "upstream"
switch {
case types.IsChannelError(err):
source = "channel"
case err.GetErrorCode() == types.ErrorCodeDoRequestFailed:
source = "transport"
case err.GetErrorType() == types.ErrorTypeNewAPIError:
source = "local"
}
state := RequestPolicy(c)
event := PolicyEvent{ChannelID: channelID, Status: err.StatusCode, ErrorCode: string(err.GetErrorCode()), ErrorSource: source, Decision: PolicyDecision{Action: "failure", Reason: "upstream_failure", Source: source}}
if source == "local" {
event.Decision.Reason = "local_rejection"
}
state.AddEvent(event)
event.Decision, event.Health = decision, "unchanged"
if source != "local" && c.GetBool("auto_ban") && ShouldDisableChannel(err) {
event.Health = "channel_disable_requested"
if common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey) {
event.Health = "key_disable_requested"
}
}
state.AddEvent(event)
}
func MarkRequestPolicySuccess(c *gin.Context, stream *relaycommon.StreamStatus) {
state := RequestPolicy(c)
if state.OutcomeRecorded {
return
}
state.OutcomeRecorded = true
state.Successful = stream == nil || stream.IsNormalEnd() && !stream.HasErrors() && (stream.ResponseOutcome() == "" || stream.ResponseOutcome() == "completed")
decision := PolicyDecision{Action: "success", Reason: "request_completed", Source: "upstream"}
if !state.Successful {
decision = PolicyDecision{Action: "stop", Reason: "stream_not_successful", Source: "system"}
}
channelID := 0
if c != nil {
channelID = c.GetInt("channel_id")
}
state.AddEvent(PolicyEvent{ChannelID: channelID, Decision: decision})
}
// Rules explicitly inherit the global default or override it. Rules without a
// mode retain their legacy retry behavior until an administrator changes them.
func EffectiveSessionMode(setting *operation_setting.ChannelAffinitySetting, rule operation_setting.ChannelAffinityRule) (mode, source string) {
if rule.SessionMode == "inherit" {
if setting.SessionMode != "" {
return setting.SessionMode, "global"
}
return "prefer", "global"
}
if rule.SessionMode != "" {
return rule.SessionMode, "session_rule"
}
if rule.SkipRetryOnFailure {
return "strict", "session_rule"
}
return "prefer", "session_rule"
}
// RecordRequestPolicyTermination appends the final decision after routing has
// stopped. It never writes a log row itself: the per-channel error log written
// by ProcessChannelError already carries the decision record, so a second row
// here would duplicate it.
func RecordRequestPolicyTermination(c *gin.Context, apiErr *types.NewAPIError) {
if c == nil || apiErr == nil {
return
}
state := RequestPolicy(c)
if state.FinalLogged {
return
}
state.FinalLogged = true
events := state.Events()
if len(events) == 0 || events[len(events)-1].Decision.Action != "stop" {
state.AddEvent(PolicyEvent{ChannelID: c.GetInt("channel_id"), Status: apiErr.StatusCode, ErrorCode: string(apiErr.GetErrorCode()), Decision: PolicyDecision{Action: "stop", Reason: "request_failed", Source: "system"}, Health: "unchanged"})
}
}
@@ -21,6 +21,9 @@ type ChannelAffinityRule struct {
ParamOverrideTemplate map[string]any `json:"param_override_template,omitempty"`
SkipRetryOnFailure bool `json:"skip_retry_on_failure"`
// "inherit" uses the global default; off/prefer/strict override it.
// Empty preserves the legacy SkipRetryOnFailure behavior.
SessionMode string `json:"session_mode,omitempty"`
IncludeUsingGroup bool `json:"include_using_group"`
IncludeModelName bool `json:"include_model_name"`
@@ -28,7 +31,9 @@ type ChannelAffinityRule struct {
}
type ChannelAffinitySetting struct {
Enabled bool `json:"enabled"`
Enabled bool `json:"enabled"`
// Default for rules with SessionMode "inherit". Empty defaults to "prefer".
SessionMode string `json:"session_mode"`
SwitchOnSuccess bool `json:"switch_on_success"`
KeepOnChannelDisabled bool `json:"keep_on_channel_disabled"`
MaxEntries int `json:"max_entries"`
+3
View File
@@ -120,6 +120,9 @@
"getOperationsSectionNavItems",
"getOperationsSectionContent",
"getOperationsSectionMeta",
"getPolicySectionNavItems",
"getPolicySectionContent",
"getPolicySectionMeta",
"getSecuritySectionNavItems",
"getSecuritySectionContent",
"getSecuritySectionMeta",
@@ -16,9 +16,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { type TFunction } from 'i18next'
import type { TFunction } from 'i18next'
import {
Box,
Route,
CreditCard,
Layout,
Settings,
@@ -32,6 +33,7 @@ import { getBillingSectionNavItems } from '@/features/system-settings/billing/se
import { getContentSectionNavItems } from '@/features/system-settings/content/section-registry.tsx'
import { getModelsSectionNavItems } from '@/features/system-settings/models/section-registry.tsx'
import { getOperationsSectionNavItems } from '@/features/system-settings/operations/section-registry.tsx'
import { getPolicySectionNavItems } from '@/features/system-settings/request-policies/section-registry'
import { getSecuritySectionNavItems } from '@/features/system-settings/security/section-registry.tsx'
import { getSiteSectionNavItems } from '@/features/system-settings/site/section-registry.tsx'
@@ -66,10 +68,15 @@ function getSystemSettingsNavGroups(t: TFunction): NavGroup[] {
items: getBillingSectionNavItems(t),
},
{
title: t('Models & Routing'),
title: t('Models'),
icon: Box,
items: getModelsSectionNavItems(t),
},
{
title: t('Request policies'),
icon: Route,
items: getPolicySectionNavItems(t),
},
{
title: t('Security & Limits'),
icon: ShieldAlert,
+7 -2
View File
@@ -143,8 +143,13 @@ export async function getChannel(id: number): Promise<GetChannelResponse> {
/**
* Get channel operations summary for administrators
*/
export async function getChannelOps(): Promise<ChannelOpsResponse> {
const res = await api.get('/api/channel/ops', channelActionConfig())
export async function getChannelOps(
autoBan?: boolean
): Promise<ChannelOpsResponse> {
const res = await api.get('/api/channel/ops', {
...channelActionConfig(),
params: autoBan === undefined ? undefined : { auto_ban: autoBan },
})
return res.data
}
@@ -17,6 +17,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
createRouter,
createRootRoute,
createMemoryHistory,
RouterContextProvider,
} from '@tanstack/react-router'
import {
act,
cleanup,
@@ -95,18 +101,28 @@ function ConfigurationHarness(props: {
clearRowOnClose?: boolean
}) {
const [open, setOpen] = useState(props.initialOpen ?? true)
const [router] = useState(() =>
createRouter({
routeTree: createRootRoute(),
history: createMemoryHistory({ initialEntries: ['/'] }),
})
)
return (
<QueryClientProvider client={client}>
<ChannelsProvider>
<button type='button' onClick={() => setOpen(true)}>
Open channel
</button>
<ChannelMutateDrawer
open={open}
onOpenChange={setOpen}
currentRow={open || !props.clearRowOnClose ? props.currentRow : null}
/>
</ChannelsProvider>
<RouterContextProvider router={router}>
<ChannelsProvider>
<button type='button' onClick={() => setOpen(true)}>
Open channel
</button>
<ChannelMutateDrawer
open={open}
onOpenChange={setOpen}
currentRow={
open || !props.clearRowOnClose ? props.currentRow : null
}
/>
</ChannelsProvider>
</RouterContextProvider>
</QueryClientProvider>
)
}
@@ -17,6 +17,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
createRouter,
createRootRoute,
createMemoryHistory,
RouterContextProvider,
} from '@tanstack/react-router'
import {
act,
cleanup,
@@ -485,15 +491,21 @@ it.each([
vi.spyOn(api, 'get').mockImplementation(async (url) => ({
data: { success: true, data: url === '/api/channel/42' ? channel : [] },
}))
const router = createRouter({
routeTree: createRootRoute(),
history: createMemoryHistory({ initialEntries: ['/'] }),
})
render(
<QueryClientProvider client={client}>
<ChannelsProvider>
<ChannelMutateDrawer
open
onOpenChange={vi.fn()}
currentRow={channel}
/>
</ChannelsProvider>
<RouterContextProvider router={router}>
<ChannelsProvider>
<ChannelMutateDrawer
open
onOpenChange={vi.fn()}
currentRow={channel}
/>
</ChannelsProvider>
</RouterContextProvider>
</QueryClientProvider>
)
expect(await screen.findByDisplayValue('Inference')).toBeInTheDocument()
@@ -24,6 +24,7 @@ import { FieldGroup } from '@/components/ui/field'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { SettingsSwitchField } from '@/features/system-settings/components/settings-form-layout'
import { ChannelHealthSource } from '@/features/system-settings/request-policies/related-policy-link'
import { cn } from '@/lib/utils'
import { CHANNEL_TYPE_TASK_PLUGIN, MODEL_FETCHABLE_TYPES } from '../constants'
@@ -89,7 +90,7 @@ export function ChannelQuickOptions(props: ChannelQuickOptionsProps) {
options.push({
key: 'auto-ban',
label: t('Auto-disable channel'),
description: t('Disable channels on repeated failures'),
description: <ChannelHealthSource autoBan={(autoBan ?? 1) === 1} />,
checked: (autoBan ?? 1) === 1,
onCheckedChange: (value) =>
form.setValue('auto_ban', value ? 1 : 0, {
+2 -2
View File
@@ -64,8 +64,8 @@ export function Channels() {
aria-label={t('Retry Settings')}
render={
<Link
to='/system-settings/models/$section'
params={{ section: 'routing-reliability' }}
to='/system-settings/request-policies/$section'
params={{ section: 'routing' }}
/>
}
/>
+4
View File
@@ -182,6 +182,10 @@ export interface ChannelOpsResponse {
message?: string
data?: {
retry_times: number
request_policy?: {
automatic_disable: boolean
source: string
}
}
}
@@ -62,6 +62,7 @@ import {
} from '@/components/ui/sheet'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { RelatedPolicyLink } from '@/features/system-settings/request-policies/related-policy-link'
import { useStatus } from '@/hooks/use-status'
import { getUserModels, getUserGroups } from '@/lib/api'
import { getCurrencyDisplay, getCurrencyLabel } from '@/lib/currency'
@@ -500,6 +501,7 @@ export function ApiKeysMutateDrawer({
{t(
'When enabled, if channels in the current group fail, it will try channels in the next group in order.'
)}
<RelatedPolicyLink section='routing' />
</FormDescription>
</div>
<FormControl>
@@ -28,6 +28,7 @@ type SettingsAccordionProps = {
title: string
children: React.ReactNode
className?: string
keepMounted?: boolean
}
export function SettingsAccordion({
@@ -35,6 +36,7 @@ export function SettingsAccordion({
title,
children,
className,
keepMounted,
}: SettingsAccordionProps) {
return (
<AccordionItem value={value} className={cn(className)}>
@@ -43,7 +45,9 @@ export function SettingsAccordion({
<div className='text-base font-semibold'>{title}</div>
</div>
</AccordionTrigger>
<AccordionContent className='pt-4'>{children}</AccordionContent>
<AccordionContent className='pt-4' keepMounted={keepMounted}>
{children}
</AccordionContent>
</AccordionItem>
)
}
@@ -20,6 +20,7 @@ import { useParams } from '@tanstack/react-router'
import { useMemo, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { ErrorState } from '@/components/error-state'
import { SectionPageLayout } from '@/components/layout'
import { useSystemOptions, getOptionValue } from '../hooks/use-system-options'
@@ -111,7 +112,7 @@ export function SettingsPage<
resolveSettings,
}: SettingsPageProps<TSettings, TSectionId, TExtraArgs>) {
const { t } = useTranslation()
const { data, isLoading } = useSystemOptions()
const { data, isLoading, isError, refetch } = useSystemOptions()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const params = useParams({ from: routePath as any })
const activeSection = (params?.section ?? defaultSection) as TSectionId
@@ -137,6 +138,17 @@ export function SettingsPage<
)
}
if (isError && !data) {
return (
<SettingsPageFrame title={t(sectionMeta.titleKey)}>
<ErrorState
title={t('Failed to load settings')}
onRetry={() => void refetch()}
/>
</SettingsPageFrame>
)
}
const sectionContent = getSectionContent(
activeSection,
settings,
@@ -16,36 +16,43 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Edit, FileText, Plus, RefreshCw, Trash2, X } from 'lucide-react'
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import {
Braces,
Database,
FileText,
ListFilter,
Plus,
RefreshCw,
Trash2,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { StaticDataTable } from '@/components/data-table'
import { Dialog } from '@/components/dialog'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { JsonCodeEditor } from '@/components/json-code-editor'
import { StatusBadge, StatusBadgeList } from '@/components/status-badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { toIntlLocale } from '@/i18n/languages'
import { formatNumber } from '@/lib/format'
import { handleServerError } from '@/lib/handle-server-error'
import { cn } from '@/lib/utils'
import { SettingsSwitchField } from '../../components/settings-form-layout'
import { SettingsPageActionsPortal } from '../../components/settings-page-context'
import { SettingsSection } from '../../components/settings-section'
import { useUpdateOption } from '../../hooks/use-update-option'
import { getCacheStats, clearAllCache, clearRuleCache } from './api'
import { RULE_TEMPLATES, cloneTemplate, makeUniqueName } from './constants'
import { RuleEditorDialog } from './rule-editor-dialog'
import type { AffinityRule, CacheStats, ChannelAffinitySettings } from './types'
import { SessionRulesTable } from './session-rules-table'
import type { AffinityRule, CacheStats, SessionMode } from './types'
function parseRules(jsonStr: string): AffinityRule[] {
try {
@@ -60,138 +67,33 @@ function parseRules(jsonStr: string): AffinityRule[] {
}
}
function RuleBadgeList(props: { items: string[] }) {
return (
<StatusBadgeList
items={props.items}
max={2}
getKey={(item) => item}
renderItem={(item) => (
<StatusBadge
label={item}
variant='neutral'
size='sm'
copyable={false}
/>
)}
/>
)
}
function ChannelAffinityConfirmDialog(props: {
open: boolean
onOpenChange: (open: boolean) => void
title: ReactNode
desc: ReactNode
handleConfirm: () => void
destructive?: boolean
}) {
const { t } = useTranslation()
return (
<Dialog
open={props.open}
onOpenChange={props.onOpenChange}
title={props.title}
contentClassName='sm:max-w-md'
contentHeight='auto'
bodyClassName='flex items-start'
footer={
<>
<Button variant='outline' onClick={() => props.onOpenChange(false)}>
{t('Cancel')}
</Button>
<Button
variant={props.destructive ? 'destructive' : 'default'}
onClick={props.handleConfirm}
>
{t('Continue')}
</Button>
</>
}
>
<div className='text-muted-foreground text-sm'>{props.desc}</div>
</Dialog>
)
}
function serializeRules(rules: AffinityRule[]): string {
return JSON.stringify(rules.map(({ id: _, ...rest }) => rest))
}
interface Props {
defaultValues: ChannelAffinitySettings
rulesJson: string
onRulesChange: (rules: string) => void
enabled?: boolean
globalSessionMode?: SessionMode | ''
}
export function ChannelAffinitySection(props: Props) {
const { t } = useTranslation()
const updateOption = useUpdateOption()
const [enabled, setEnabled] = useState(
props.defaultValues['channel_affinity_setting.enabled']
)
const [switchOnSuccess, setSwitchOnSuccess] = useState(
props.defaultValues['channel_affinity_setting.switch_on_success']
)
const [keepOnChannelDisabled, setKeepOnChannelDisabled] = useState(
props.defaultValues['channel_affinity_setting.keep_on_channel_disabled']
)
const [maxEntries, setMaxEntries] = useState(
props.defaultValues['channel_affinity_setting.max_entries']
)
const [defaultTtl, setDefaultTtl] = useState(
props.defaultValues['channel_affinity_setting.default_ttl_seconds']
)
const [rules, setRules] = useState<AffinityRule[]>(() =>
parseRules(props.defaultValues['channel_affinity_setting.rules'])
)
const { t, i18n } = useTranslation()
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
const rules = useMemo(() => parseRules(props.rulesJson), [props.rulesJson])
const [editMode, setEditMode] = useState<'visual' | 'json'>('visual')
const [jsonText, setJsonText] = useState(() =>
JSON.stringify(
parseRules(props.defaultValues['channel_affinity_setting.rules']).map(
({ id: _, ...r }) => r
),
null,
2
)
)
const [cacheStats, setCacheStats] = useState<CacheStats | null>(null)
const [cacheLoading, setCacheLoading] = useState(false)
const [saving, setSaving] = useState(false)
const [ruleEditorOpen, setRuleEditorOpen] = useState(false)
const [editingRule, setEditingRule] = useState<AffinityRule | null>(null)
const [ruleTemplateKey, setRuleTemplateKey] = useState<string | null>(null)
const [deletingRule, setDeletingRule] = useState<AffinityRule | null>(null)
const [clearAllDialogOpen, setClearAllDialogOpen] = useState(false)
const [clearRuleName, setClearRuleName] = useState<string | null>(null)
const [fillTemplateDialogOpen, setFillTemplateDialogOpen] = useState(false)
useEffect(() => {
setEnabled(props.defaultValues['channel_affinity_setting.enabled'])
setSwitchOnSuccess(
props.defaultValues['channel_affinity_setting.switch_on_success']
)
setKeepOnChannelDisabled(
props.defaultValues['channel_affinity_setting.keep_on_channel_disabled']
)
setMaxEntries(props.defaultValues['channel_affinity_setting.max_entries'])
setDefaultTtl(
props.defaultValues['channel_affinity_setting.default_ttl_seconds']
)
const parsed = parseRules(
props.defaultValues['channel_affinity_setting.rules']
)
setRules(parsed)
setJsonText(
JSON.stringify(
parsed.map(({ id: _, ...r }) => r),
null,
2
)
)
}, [props.defaultValues])
const refreshCache = useCallback(async () => {
setCacheLoading(true)
try {
@@ -209,7 +111,7 @@ export function ChannelAffinitySection(props: Props) {
}, [t])
useEffect(() => {
refreshCache()
void refreshCache()
}, [refreshCache])
const appendCliTemplates = () => {
@@ -224,9 +126,7 @@ export function ChannelAffinitySection(props: Props) {
return { ...base, name }
})
setRules((prev) =>
[...prev, ...templates].map((r, idx) => ({ ...r, id: idx }))
)
props.onRulesChange(serializeRules([...rules, ...templates]))
toast.success(t('Templates appended'))
setFillTemplateDialogOpen(false)
}
@@ -239,124 +139,15 @@ export function ChannelAffinitySection(props: Props) {
}
}
const handleSave = async () => {
let rulesJson: string
if (editMode === 'json') {
try {
const parsed = JSON.parse(jsonText)
if (!Array.isArray(parsed)) {
toast.error(t('Rules JSON must be an array'))
return
}
rulesJson = JSON.stringify(parsed)
} catch {
toast.error(t('Invalid rules JSON format'))
return
}
} else {
rulesJson = serializeRules(rules)
}
setSaving(true)
try {
const updates: { key: string; value: string }[] = []
if (enabled !== props.defaultValues['channel_affinity_setting.enabled']) {
updates.push({
key: 'channel_affinity_setting.enabled',
value: String(enabled),
})
}
if (
switchOnSuccess !==
props.defaultValues['channel_affinity_setting.switch_on_success']
) {
updates.push({
key: 'channel_affinity_setting.switch_on_success',
value: String(switchOnSuccess),
})
}
if (
keepOnChannelDisabled !==
props.defaultValues['channel_affinity_setting.keep_on_channel_disabled']
) {
updates.push({
key: 'channel_affinity_setting.keep_on_channel_disabled',
value: String(keepOnChannelDisabled),
})
}
if (
maxEntries !==
props.defaultValues['channel_affinity_setting.max_entries']
) {
updates.push({
key: 'channel_affinity_setting.max_entries',
value: String(maxEntries),
})
}
if (
defaultTtl !==
props.defaultValues['channel_affinity_setting.default_ttl_seconds']
) {
updates.push({
key: 'channel_affinity_setting.default_ttl_seconds',
value: String(defaultTtl),
})
}
const origRules = props.defaultValues['channel_affinity_setting.rules']
const origSerialized = (() => {
try {
return JSON.stringify(JSON.parse(origRules || '[]'))
} catch {
return '[]'
}
})()
if (rulesJson !== origSerialized) {
updates.push({
key: 'channel_affinity_setting.rules',
value: rulesJson,
})
}
if (updates.length === 0) {
toast.info(t('No changes'))
return
}
for (const u of updates) {
await updateOption.mutateAsync(u)
}
toast.success(t('Saved successfully'))
} catch (error) {
handleServerError(error, t('Failed to save'))
} finally {
setSaving(false)
}
}
const handleRuleSave = (rule: AffinityRule) => {
setRules((prev) => {
const existIdx = prev.findIndex(
(r) => r.id === rule.id || (rule.name && r.name === editingRule?.name)
)
if (existIdx >= 0) {
const next = [...prev]
next[existIdx] = { ...rule, id: existIdx }
return next
}
return [...prev, { ...rule, id: prev.length }]
})
const index = rules.findIndex((item) => item.id === editingRule?.id)
const next = [...rules]
if (index >= 0) next[index] = rule
else next.push(rule)
props.onRulesChange(serializeRules(next))
setEditingRule(null)
}
const handleDeleteRule = (idx: number) => {
setRules((prev) =>
prev.filter((_, i) => i !== idx).map((r, i) => ({ ...r, id: i }))
)
toast.success(t('Deleted successfully'))
}
const handleClearAll = async () => {
try {
const res = await clearAllCache()
@@ -389,7 +180,7 @@ export function ChannelAffinitySection(props: Props) {
}
const switchToJsonMode = () => {
setJsonText(
props.onRulesChange(
JSON.stringify(
rules.map(({ id: _, ...r }) => r),
null,
@@ -401,17 +192,11 @@ export function ChannelAffinitySection(props: Props) {
const switchToVisualMode = () => {
try {
const parsed = JSON.parse(jsonText)
const parsed: unknown = JSON.parse(props.rulesJson)
if (!Array.isArray(parsed)) {
toast.error(t('Rules JSON must be an array'))
return
}
setRules(
parsed.map(
(r: Record<string, unknown>, i: number) =>
({ id: i, ...r }) as AffinityRule
)
)
setEditMode('visual')
} catch {
toast.error(t('Invalid rules JSON format'))
@@ -420,276 +205,197 @@ export function ChannelAffinitySection(props: Props) {
return (
<>
<SettingsSection title={t('Channel Affinity')}>
<Alert>
<AlertDescription className='text-xs'>
{t(
'Channel affinity reuses the last successful channel based on keys extracted from the request context or JSON body.'
)}
</AlertDescription>
</Alert>
{/* Basic Settings */}
<div className='grid grid-cols-1 gap-4 md:grid-cols-3'>
<SettingsSwitchField
checked={enabled}
onCheckedChange={setEnabled}
label={t('Enable')}
className='py-0'
/>
<div className='grid gap-1.5'>
<Label>{t('Max Entries')}</Label>
<Input
type='number'
min={0}
value={maxEntries}
onChange={(e) => setMaxEntries(Number(e.target.value))}
/>
</div>
<div className='grid gap-1.5'>
<Label>{t('Default TTL (seconds)')}</Label>
<Input
type='number'
min={0}
value={defaultTtl}
onChange={(e) => setDefaultTtl(Number(e.target.value))}
/>
<section
aria-label={t('Session rules')}
className='bg-card min-w-0 overflow-hidden rounded-xl border'
>
<div className='flex flex-col gap-1.5 px-4 pt-5 sm:px-5'>
<div className='flex items-center gap-2'>
<h3 className='text-base font-semibold'>{t('Session rules')}</h3>
<Badge variant='secondary' className='tabular-nums'>
{rules.length}
</Badge>
</div>
<p className='text-muted-foreground text-sm'>
{t('How a session is identified and which channel it keeps.')}
</p>
</div>
<SettingsSwitchField
checked={switchOnSuccess}
onCheckedChange={setSwitchOnSuccess}
label={t('Switch affinity on success')}
description={t(
'If the affinity channel fails and retry succeeds on another channel, update affinity to the successful channel.'
)}
/>
<SettingsSwitchField
checked={keepOnChannelDisabled}
onCheckedChange={setKeepOnChannelDisabled}
label={t('Keep affinity when channel is disabled')}
description={t(
'When enabled, keep the affinity entry even if the affinity channel is disabled or no longer usable for the current group/model. Leave it off to delete the entry and select another channel.'
)}
/>
<Separator />
<SettingsPageActionsPortal>
<Button
variant={editMode === 'visual' ? 'default' : 'outline'}
size='sm'
onClick={editMode === 'json' ? switchToVisualMode : undefined}
>
{t('Visual')}
</Button>
<Button
variant={editMode === 'json' ? 'default' : 'outline'}
size='sm'
onClick={editMode === 'visual' ? switchToJsonMode : undefined}
>
JSON
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant='outline' size='sm' />}
>
<Plus className='mr-1 h-3 w-3' />
{t('Add Rule')}
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
onClick={() => {
setEditingRule(null)
setRuleTemplateKey(null)
setRuleEditorOpen(true)
}}
<Tabs
value={editMode}
onValueChange={(value) => {
if (value === 'json') switchToJsonMode()
else switchToVisualMode()
}}
className='gap-0'
>
<div className='flex flex-wrap items-center justify-between gap-3 px-4 py-4 sm:px-5'>
<TabsList aria-label={t('Rule editor mode')}>
<TabsTrigger value='visual' className='px-3'>
<ListFilter aria-hidden='true' />
{t('Visual')}
</TabsTrigger>
<TabsTrigger value='json' className='px-3'>
<Braces aria-hidden='true' />
JSON
</TabsTrigger>
</TabsList>
<div className='flex flex-wrap items-center gap-2'>
<Button
variant='outline'
onClick={handleFillTemplates}
disabled={editMode === 'json'}
>
{t('Blank Rule')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setEditingRule(null)
setRuleTemplateKey('codexCli')
setRuleEditorOpen(true)
}}
>
Codex CLI
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setEditingRule(null)
setRuleTemplateKey('claudeCli')
setRuleEditorOpen(true)
}}
>
Claude CLI
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button variant='outline' size='sm' onClick={handleFillTemplates}>
<FileText className='mr-1 h-3 w-3' />
{t('Fill Templates')}
</Button>
<Button size='sm' onClick={handleSave} disabled={saving}>
{saving ? t('Saving...') : t('Save')}
</Button>
<Button
variant='outline'
size='sm'
onClick={refreshCache}
disabled={cacheLoading}
>
<RefreshCw
className={`mr-1 h-3 w-3 ${cacheLoading ? 'animate-spin' : ''}`}
/>
{t('Refresh Cache')}
</Button>
<Button
variant='destructive'
size='sm'
onClick={() => setClearAllDialogOpen(true)}
>
{t('Clear All Cache')}
</Button>
{cacheStats && (
<span className='text-muted-foreground text-xs'>
{t('Cache Entries')}: {cacheStats.total} /{' '}
{cacheStats.cache_capacity}
</span>
)}
</SettingsPageActionsPortal>
{/* Rules Table or JSON Editor */}
{editMode === 'visual' ? (
<StaticDataTable
tableClassName='min-w-max'
data={rules}
emptyClassName='text-muted-foreground py-8'
emptyContent={t('No rules yet')}
columns={[
{
id: 'name',
header: t('Name'),
cellClassName: 'font-medium',
cell: (rule) => rule.name || '-',
},
{
id: 'model-regex',
header: t('Model Regex'),
cell: (rule) => (
<RuleBadgeList items={rule.model_regex || []} />
),
},
{
id: 'key-sources',
header: t('Key Sources'),
cell: (rule) => (
<RuleBadgeList
items={(rule.key_sources || []).map(
(src) =>
`${src.type}:${src.type === 'gjson' ? src.path : src.key}`
)}
/>
),
},
{
id: 'ttl',
header: t('TTL'),
cell: (rule) => rule.ttl_seconds || '-',
},
{
id: 'retry',
header: t('Retry'),
cell: (rule) => (
<StatusBadge
label={
rule.skip_retry_on_failure ? t('No Retry') : t('Retry')
}
variant={rule.skip_retry_on_failure ? 'danger' : 'neutral'}
copyable={false}
/>
),
},
{
id: 'scope',
header: t('Scope'),
cell: (rule) => {
const scopeItems = [
rule.include_using_group && t('Group'),
rule.include_model_name && t('Model'),
rule.include_rule_name && t('Rule'),
].filter(Boolean) as string[]
if (scopeItems.length === 0) return '-'
return <RuleBadgeList items={scopeItems} />
},
},
{
id: 'cache',
header: t('Cache'),
cell: (rule) =>
rule.include_rule_name && cacheStats?.by_rule_name
? cacheStats.by_rule_name[rule.name] || 0
: 'N/A',
},
{
id: 'actions',
header: t('Actions'),
className: 'text-right',
cellClassName: 'text-right',
cell: (rule, idx) => (
<div className='flex justify-end gap-1'>
{rule.include_rule_name && (
<Button
variant='ghost'
size='icon'
className='h-7 w-7'
onClick={() => setClearRuleName(rule.name)}
title={t('Clear cache for this rule')}
>
<X className='h-3 w-3' />
</Button>
)}
<Button
variant='ghost'
size='icon'
className='h-7 w-7'
<FileText aria-hidden='true' data-icon='inline-start' />
{t('Fill Templates')}
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button disabled={editMode === 'json'} />}
>
<Plus aria-hidden='true' data-icon='inline-start' />
{t('Add Rule')}
</DropdownMenuTrigger>
<DropdownMenuContent align='end'>
<DropdownMenuGroup>
<DropdownMenuItem
onClick={() => {
setEditingRule(rule)
setEditingRule(null)
setRuleTemplateKey(null)
setRuleEditorOpen(true)
}}
>
<Edit className='h-3 w-3' />
</Button>
<Button
variant='ghost'
size='icon'
className='h-7 w-7'
onClick={() => handleDeleteRule(idx)}
{t('Blank Rule')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setEditingRule(null)
setRuleTemplateKey('codexCli')
setRuleEditorOpen(true)
}}
>
<Trash2 className='h-3 w-3' />
</Button>
</div>
),
},
]}
/>
) : (
<div className='grid gap-1.5'>
<Label htmlFor='channel-affinity-rules-json'>
{t('Rules JSON')}
</Label>
<JsonCodeEditor
id='channel-affinity-rules-json'
value={jsonText}
onChange={setJsonText}
heightClassName='h-[300px] min-h-[300px] max-h-[300px]'
/>
Codex CLI
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setEditingRule(null)
setRuleTemplateKey('claudeCli')
setRuleEditorOpen(true)
}}
>
Claude CLI
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
)}
</SettingsSection>
<Separator />
<TabsContent value='visual' className='min-w-0'>
<SessionRulesTable
rules={rules}
cacheStats={cacheStats}
enabled={props.enabled}
globalSessionMode={props.globalSessionMode}
onEdit={(rule) => {
setEditingRule(rule)
setRuleTemplateKey(null)
setRuleEditorOpen(true)
}}
onDelete={setDeletingRule}
onClearCache={setClearRuleName}
onFillTemplates={handleFillTemplates}
/>
</TabsContent>
<TabsContent value='json' className='min-w-0'>
<div className='grid gap-2 p-4 sm:p-5'>
<Label htmlFor='channel-affinity-rules-json'>
{t('Rules JSON')}
</Label>
<p className='text-muted-foreground text-xs'>
{t('Switch to visual mode to add rules or apply templates.')}
</p>
<JsonCodeEditor
id='channel-affinity-rules-json'
value={props.rulesJson}
onChange={props.onRulesChange}
heightClassName='h-[300px] min-h-[300px] max-h-[300px]'
/>
</div>
</TabsContent>
</Tabs>
<Separator />
<div className='bg-muted/25 flex flex-wrap items-center justify-between gap-3 px-4 py-3 sm:px-5'>
<div
role='status'
className='flex min-w-0 items-center gap-2 text-sm'
>
<Database
aria-hidden='true'
className='text-muted-foreground size-4 shrink-0'
/>
<span className='text-muted-foreground'>{t('Cache Entries')}</span>
{cacheStats ? (
<span className='flex flex-wrap items-baseline gap-1 font-medium tabular-nums'>
{formatNumber(cacheStats.total, locale)}
<span className='text-muted-foreground font-normal'>
/ {formatNumber(cacheStats.cache_capacity, locale)}
</span>
</span>
) : (
<span className='text-muted-foreground'>
{cacheLoading ? t('Loading...') : t('Unavailable')}
</span>
)}
</div>
<div className='flex flex-wrap items-center gap-1'>
<Button
variant='ghost'
size='sm'
onClick={refreshCache}
disabled={cacheLoading}
aria-busy={cacheLoading}
>
<RefreshCw
aria-hidden='true'
className={cn(
cacheLoading && 'animate-spin motion-reduce:animate-none'
)}
/>
{t('Refresh Cache')}
</Button>
<Button
variant='ghost'
size='sm'
onClick={() => setClearAllDialogOpen(true)}
>
<Trash2 aria-hidden='true' />
{t('Clear All Cache')}
</Button>
</div>
</div>
</section>
{deletingRule !== null && (
<ConfirmDialog
open
onOpenChange={(open) => !open && setDeletingRule(null)}
title={t('Delete Rule')}
desc={t(
'Delete session rule “{{name}}”? Save your changes to apply the removal.',
{ name: deletingRule.name }
)}
confirmText={t('Delete Rule')}
handleConfirm={() => {
props.onRulesChange(
serializeRules(
rules.filter((rule) => rule.id !== deletingRule.id)
)
)
setDeletingRule(null)
}}
destructive
/>
)}
<RuleEditorDialog
open={ruleEditorOpen}
@@ -697,9 +403,10 @@ export function ChannelAffinitySection(props: Props) {
rule={editingRule}
onSave={handleRuleSave}
templateKey={ruleTemplateKey}
globalSessionMode={props.globalSessionMode}
/>
<ChannelAffinityConfirmDialog
<ConfirmDialog
open={clearAllDialogOpen}
onOpenChange={setClearAllDialogOpen}
title={t('Confirm clearing all channel affinity cache')}
@@ -711,7 +418,7 @@ export function ChannelAffinitySection(props: Props) {
/>
{clearRuleName !== null && (
<ChannelAffinityConfirmDialog
<ConfirmDialog
open
onOpenChange={(v) => !v && setClearRuleName(null)}
title={t('Confirm clearing cache for this rule')}
@@ -721,7 +428,7 @@ export function ChannelAffinitySection(props: Props) {
/>
)}
<ChannelAffinityConfirmDialog
<ConfirmDialog
open={fillTemplateDialogOpen}
onOpenChange={setFillTemplateDialogOpen}
title={t('Fill Codex CLI / Claude CLI Templates')}
@@ -32,6 +32,7 @@ import {
} from '@/components/ui/collapsible'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import {
Select,
SelectContent,
@@ -44,8 +45,9 @@ import { Separator } from '@/components/ui/separator'
import { Textarea } from '@/components/ui/textarea'
import { SettingsSwitchField } from '../../components/settings-form-layout'
import { policyLabel } from '../../request-policies/policy-label'
import { RULE_TEMPLATES } from './constants'
import type { AffinityRule, KeySource } from './types'
import type { AffinityRule, KeySource, SessionMode } from './types'
type KeySourceRow = KeySource & {
rowId: string
@@ -73,6 +75,7 @@ const CONTEXT_KEY_PRESETS = [
const RULE_FORM_ID = 'channel-affinity-rule-form'
interface RuleFormValues {
session_mode?: AffinityRule['session_mode']
name: string
model_regex_text: string
path_regex_text: string
@@ -95,8 +98,8 @@ function normalizeStringList(text: string): string[] {
function normalizeKeySource(src: Partial<KeySource>): KeySource {
const type = (src?.type || 'gjson') as KeySource['type']
if (type === 'gjson') return { type, key: '', path: src?.path || '' }
return { type, key: src?.key || '', path: '' }
if (type === 'gjson') return { ...src, type, key: '', path: src?.path || '' }
return { ...src, type, key: src?.key || '', path: '' }
}
interface Props {
@@ -105,6 +108,7 @@ interface Props {
rule: AffinityRule | null
onSave: (rule: AffinityRule) => void
templateKey?: string | null
globalSessionMode?: SessionMode | ''
}
export function RuleEditorDialog(props: Props) {
@@ -122,6 +126,7 @@ export function RuleEditorDialog(props: Props) {
const form = useForm<RuleFormValues>({
defaultValues: {
session_mode: 'inherit',
name: '',
model_regex_text: '',
path_regex_text: '',
@@ -141,6 +146,8 @@ export function RuleEditorDialog(props: Props) {
const resetFromRule = (r: Partial<AffinityRule>) => {
form.reset({
session_mode:
r.session_mode || (r.skip_retry_on_failure ? 'strict' : 'prefer'),
name: r.name || '',
model_regex_text: (r.model_regex || []).join('\n'),
path_regex_text: (r.path_regex || []).join('\n'),
@@ -173,6 +180,7 @@ export function RuleEditorDialog(props: Props) {
resetFromRule(RULE_TEMPLATES[props.templateKey])
} else {
form.reset({
session_mode: 'inherit',
name: '',
model_regex_text: '',
path_regex_text: '',
@@ -198,7 +206,7 @@ export function RuleEditorDialog(props: Props) {
}
const validKeySources = keySources
.map(normalizeKeySource)
.map(({ rowId: _, ...source }) => normalizeKeySource(source))
.filter((s) => s.type && (s.type === 'gjson' ? s.path : s.key))
if (validKeySources.length === 0) {
toast.error(t('At least one valid key source is required'))
@@ -225,6 +233,8 @@ export function RuleEditorDialog(props: Props) {
}
const rule: AffinityRule = {
...props.rule,
session_mode: values.session_mode || 'inherit',
id: props.rule?.id,
name: values.name.trim(),
model_regex: modelRegex,
@@ -249,7 +259,7 @@ export function RuleEditorDialog(props: Props) {
open={props.open}
onOpenChange={props.onOpenChange}
title={isEdit ? t('Edit Rule') : t('Add Rule')}
contentClassName='max-w-2xl'
contentClassName='sm:max-w-5xl'
contentHeight='auto'
bodyClassName='pr-2'
footer={
@@ -273,8 +283,11 @@ export function RuleEditorDialog(props: Props) {
className='min-w-0 space-y-4 overflow-x-clip'
>
<div className='grid gap-1.5'>
<Label required>{t('Name')}</Label>
<Label required htmlFor='affinity-rule-name'>
{t('Name')}
</Label>
<Input
id='affinity-rule-name'
placeholder='prefer-by-conversation-id'
{...form.register('name', { required: true })}
/>
@@ -299,11 +312,36 @@ export function RuleEditorDialog(props: Props) {
</div>
</div>
<SettingsSwitchField
checked={form.watch('skip_retry_on_failure')}
onCheckedChange={(v) => form.setValue('skip_retry_on_failure', v)}
label={t('Skip retry on failure')}
/>
<div className='space-y-1.5'>
<Label htmlFor='rule-session-mode'>{t('Session behavior')}</Label>
<NativeSelect
id='rule-session-mode'
className='w-full'
aria-describedby='rule-session-mode-description'
{...form.register('session_mode')}
>
<NativeSelectOption value='inherit'>
{t('Inherit global default')}
</NativeSelectOption>
<NativeSelectOption value='off'>
{t('Do not keep sessions')}
</NativeSelectOption>
<NativeSelectOption value='prefer'>
{t('Prefer the original channel, allow switching')}
</NativeSelectOption>
<NativeSelectOption value='strict'>
{t('Require the original channel')}
</NativeSelectOption>
</NativeSelect>
<p
id='rule-session-mode-description'
className='text-muted-foreground text-xs'
>
{t('Global default: {{mode}}', {
mode: policyLabel(t, props.globalSessionMode || 'prefer'),
})}
</p>
</div>
<Separator />
@@ -0,0 +1,298 @@
/*
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 {
ArrowLeftRight,
Edit,
FileText,
Link2Off,
ListFilter,
LockKeyhole,
Trash2,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import {
DataTableRowActionMenu,
StaticDataTable,
TruncatedCell,
} from '@/components/data-table'
import { EmptyState } from '@/components/empty-state'
import { StatusBadge, StatusBadgeList } from '@/components/status-badge'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { toIntlLocale } from '@/i18n/languages'
import { formatNumber } from '@/lib/format'
import { policyLabel } from '../../request-policies/policy-label'
import type { AffinityRule, CacheStats, SessionMode } from './types'
interface SessionRulesTableProps {
rules: AffinityRule[]
cacheStats: CacheStats | null
enabled?: boolean
globalSessionMode?: SessionMode | ''
onEdit: (rule: AffinityRule) => void
onDelete: (rule: AffinityRule) => void
onClearCache: (name: string) => void
onFillTemplates: () => void
}
export function SessionRulesTable(props: SessionRulesTableProps) {
const { t, i18n } = useTranslation()
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
if (props.rules.length === 0) {
return (
<EmptyState
icon={ListFilter}
title={t('No rules yet')}
description={t('Fill a CLI template or add a blank rule.')}
className='min-h-56'
action={
<Button variant='outline' onClick={props.onFillTemplates}>
<FileText aria-hidden='true' />
{t('Fill Templates')}
</Button>
}
/>
)
}
return (
<StaticDataTable
className='focus-visible:outline-ring overflow-x-auto rounded-none border-0 focus-visible:-outline-offset-2'
containerProps={{
role: 'region',
'aria-label': t('Session rules table'),
tabIndex: 0,
}}
tableProps={{ withContainer: false }}
tableClassName='min-w-[960px] table-fixed [&_th]:px-4 [&_th]:text-muted-foreground [&_td]:px-4 [&_td]:py-4 [&_code]:font-mono!'
headerRowClassName='bg-muted/35 hover:bg-muted/35'
data={props.rules}
getRowKey={(rule) => rule.id ?? rule.name}
columns={[
{
id: 'name',
header: t('Name'),
className: 'w-[20%]',
cell: (rule) => (
<div className='flex min-w-0 flex-col gap-1.5'>
<TruncatedCell tabIndex={0}>{rule.name || '—'}</TruncatedCell>
<div
className='text-muted-foreground min-w-0'
data-table-text='secondary'
aria-label={t('Model Regex')}
>
<TruncatedCell
tabIndex={0}
tooltipContent={
(rule.model_regex || []).join('\n') || t('All models')
}
>
<code>
{(rule.model_regex || []).join(' · ') || t('All models')}
</code>
</TruncatedCell>
</div>
</div>
),
},
{
id: 'key-sources',
header: t('Key Sources'),
className: 'w-[22%]',
cell: (rule) => (
<div className='flex min-w-0 flex-col gap-1.5'>
{(rule.key_sources || []).map((source) => (
<div
key={`${source.type}:${source.path || source.key}`}
className='flex min-w-0 items-center gap-2'
>
<Badge variant='secondary' className='shrink-0'>
{source.type}
</Badge>
<TruncatedCell
tabIndex={0}
tooltipContent={
source.type === 'gjson' ? source.path : source.key
}
>
<code>
{source.type === 'gjson' ? source.path : source.key}
</code>
</TruncatedCell>
</div>
))}
{!rule.key_sources?.length ? (
<span className='text-muted-foreground'>—</span>
) : null}
</div>
),
},
{
id: 'session',
header: t('Session behavior'),
cell: (rule) => {
let mode =
rule.session_mode ||
(rule.skip_retry_on_failure ? 'strict' : 'prefer')
let source = t('Rule override')
if (mode === 'inherit') {
mode = props.globalSessionMode || 'prefer'
source = t('Inherit global default')
}
if (props.enabled === false) {
mode = 'off'
source = t('Disabled globally')
}
let icon = ArrowLeftRight
if (mode === 'strict') icon = LockKeyhole
if (mode === 'off') icon = Link2Off
return (
<div className='flex min-w-0 flex-col gap-1.5'>
<StatusBadge
label={policyLabel(t, mode)}
icon={icon}
variant='neutral'
type='text'
copyable={false}
className='h-auto whitespace-normal [&>span]:overflow-visible [&>span]:whitespace-normal'
/>
<span
data-table-text='secondary'
className='text-muted-foreground whitespace-normal'
>
{source}
</span>
</div>
)
},
},
{
id: 'ttl',
header: t('TTL'),
className: 'w-24',
cellClassName: 'text-muted-foreground',
cell: (rule) => (
<TruncatedCell tabIndex={0}>
{rule.ttl_seconds > 0
? `${formatNumber(rule.ttl_seconds, locale)} ${t('seconds')}`
: t('Global default')}
</TruncatedCell>
),
},
{
id: 'scope',
header: t('Scope'),
className: 'w-32',
cell: (rule) => {
const items = [
rule.include_using_group && t('Group'),
rule.include_model_name && t('Model'),
rule.include_rule_name && t('Rule'),
].filter(Boolean) as string[]
return (
<StatusBadgeList
items={items}
max={3}
className='flex-wrap gap-1.5'
renderItem={(item) => <Badge variant='outline'>{item}</Badge>}
/>
)
},
},
{
id: 'cache',
header: t('Cache'),
className: 'w-16 text-right',
cellClassName: 'text-right tabular-nums',
cell: (rule) => {
if (!rule.include_rule_name) return t('N/A')
if (!props.cacheStats) return '—'
return formatNumber(
props.cacheStats.by_rule_name?.[rule.name] || 0,
locale
)
},
},
{
id: 'actions',
header: t('Actions'),
className: 'w-24 text-right',
cell: (rule) => (
<div
role='group'
aria-label={t('Actions for {{name}}', { name: rule.name })}
className='flex items-center justify-end gap-0.5'
>
<Tooltip>
<TooltipTrigger
render={
<Button
variant='ghost'
size='icon'
aria-label={t('Edit Rule')}
onClick={() => props.onEdit(rule)}
>
<Edit aria-hidden='true' />
</Button>
}
/>
<TooltipContent>{t('Edit Rule')}</TooltipContent>
</Tooltip>
<DataTableRowActionMenu ariaLabel={t('More actions')}>
<DropdownMenuGroup>
{rule.include_rule_name ? (
<>
<DropdownMenuItem
onClick={() => props.onClearCache(rule.name)}
>
<Trash2 aria-hidden='true' />
{t('Clear cache for this rule')}
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
) : null}
<DropdownMenuItem
variant='destructive'
onClick={() => props.onDelete(rule)}
>
<Trash2 aria-hidden='true' />
{t('Delete Rule')}
</DropdownMenuItem>
</DropdownMenuGroup>
</DataTableRowActionMenu>
</div>
),
},
]}
/>
)
}
@@ -22,7 +22,10 @@ export interface KeySource {
path?: string
}
export type SessionMode = 'off' | 'prefer' | 'strict'
export interface AffinityRule {
session_mode?: SessionMode | 'inherit'
id?: number
name: string
model_regex: string[]
@@ -49,6 +52,7 @@ export interface CacheStats {
export interface ChannelAffinitySettings {
'channel_affinity_setting.enabled': boolean
'channel_affinity_setting.session_mode'?: '' | SessionMode
'channel_affinity_setting.switch_on_success': boolean
'channel_affinity_setting.keep_on_channel_disabled': boolean
'channel_affinity_setting.max_entries': number
@@ -64,24 +64,6 @@ const defaultModelSettings: ModelSettings = {
MaxTokenAutoGroups: 5,
DefaultUseAutoGroup: false,
'group_ratio_setting.group_special_usable_group': '{}',
RetryTimes: 0,
ChannelDisableThreshold: '',
AutomaticDisableChannelEnabled: false,
AutomaticEnableChannelEnabled: false,
AutomaticDisableKeywords: '',
AutomaticDisableStatusCodes: '401',
AutomaticRetryStatusCodes:
'100-199,300-399,401-407,409-499,500-503,505-523,525-599',
'monitor_setting.auto_test_channel_enabled': false,
'monitor_setting.auto_test_channel_minutes': 10,
'monitor_setting.channel_test_concurrency': 1,
'monitor_setting.channel_test_mode': 'scheduled_all',
'channel_affinity_setting.enabled': false,
'channel_affinity_setting.switch_on_success': true,
'channel_affinity_setting.keep_on_channel_disabled': false,
'channel_affinity_setting.max_entries': 100000,
'channel_affinity_setting.default_ttl_seconds': 3600,
'channel_affinity_setting.rules': '[]',
'model_deployment.ionet.api_key': '',
'model_deployment.ionet.enabled': false,
}
@@ -16,7 +16,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { ChannelAffinitySection } from '../general/channel-affinity'
import { IoNetDeploymentSettingsSection } from '../integrations/ionet-deployment-settings-section'
import type { ModelSettings } from '../types'
import { createSectionRegistry } from '../utils/section-registry'
@@ -24,7 +23,6 @@ import { ClaudeSettingsCard } from './claude-settings-card'
import { GeminiSettingsCard } from './gemini-settings-card'
import { GlobalSettingsCard } from './global-settings-card'
import { GrokSettingsCard } from './grok-settings-card'
import { RoutingReliabilitySection } from './routing-reliability-section'
function formatJsonForEditor(value: string, fallback: string) {
const raw = (value ?? '').toString().trim()
@@ -65,32 +63,7 @@ const MODELS_SECTIONS = [
/>
),
},
{
id: 'routing-reliability',
titleKey: 'Routing Reliability',
build: (settings: ModelSettings) => (
<RoutingReliabilitySection
defaultValues={{
RetryTimes: settings.RetryTimes,
ChannelDisableThreshold: settings.ChannelDisableThreshold,
AutomaticDisableChannelEnabled:
settings.AutomaticDisableChannelEnabled,
AutomaticEnableChannelEnabled: settings.AutomaticEnableChannelEnabled,
AutomaticDisableKeywords: settings.AutomaticDisableKeywords,
AutomaticDisableStatusCodes: settings.AutomaticDisableStatusCodes,
AutomaticRetryStatusCodes: settings.AutomaticRetryStatusCodes,
'monitor_setting.auto_test_channel_enabled':
settings['monitor_setting.auto_test_channel_enabled'],
'monitor_setting.auto_test_channel_minutes':
settings['monitor_setting.auto_test_channel_minutes'],
'monitor_setting.channel_test_concurrency':
settings['monitor_setting.channel_test_concurrency'],
'monitor_setting.channel_test_mode':
settings['monitor_setting.channel_test_mode'],
}}
/>
),
},
{
id: 'gemini',
titleKey: 'Gemini',
@@ -147,28 +120,7 @@ const MODELS_SECTIONS = [
/>
),
},
{
id: 'channel-affinity',
titleKey: 'Channel Affinity',
build: (settings: ModelSettings) => (
<ChannelAffinitySection
defaultValues={{
'channel_affinity_setting.enabled':
settings['channel_affinity_setting.enabled'],
'channel_affinity_setting.switch_on_success':
settings['channel_affinity_setting.switch_on_success'],
'channel_affinity_setting.keep_on_channel_disabled':
settings['channel_affinity_setting.keep_on_channel_disabled'],
'channel_affinity_setting.max_entries':
settings['channel_affinity_setting.max_entries'],
'channel_affinity_setting.default_ttl_seconds':
settings['channel_affinity_setting.default_ttl_seconds'],
'channel_affinity_setting.rules':
settings['channel_affinity_setting.rules'],
}}
/>
),
},
{
id: 'model-deployment',
titleKey: 'Model Deployment',
@@ -0,0 +1,797 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
createRouter,
createRootRoute,
createMemoryHistory,
RouterContextProvider,
} from '@tanstack/react-router'
import {
act,
fireEvent,
render,
screen,
waitFor,
cleanup,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import i18next from 'i18next'
import { useState } from 'react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { api } from '@/lib/api'
import { SettingsPageProvider } from '../../components/settings-page-context'
import { RoutingPolicySection } from '../routing-section'
const options = {
RetryTimes: '2',
'channel_affinity_setting.enabled': 'true',
'channel_affinity_setting.session_mode': '',
'channel_affinity_setting.switch_on_success': 'false',
'channel_affinity_setting.keep_on_channel_disabled': 'false',
'channel_affinity_setting.max_entries': '100000',
'channel_affinity_setting.default_ttl_seconds': '3600',
'channel_affinity_setting.rules': JSON.stringify([
{
name: 'Session rule',
model_regex: ['.*'],
path_regex: [],
key_sources: [{ type: 'request_header', key: 'X-Session' }],
ttl_seconds: 0,
session_mode: 'prefer',
skip_retry_on_failure: false,
include_using_group: false,
include_rule_name: true,
include_model_name: false,
param_override_template: { temperature: 0 },
future_field: { retained: true },
},
]),
AutomaticRetryStatusCodes: '429,500-503',
}
let currentOptions: Record<string, string>
let client: QueryClient
beforeEach(() => {
client = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
currentOptions = { ...options }
vi.spyOn(api, 'get').mockImplementation(async (url) => ({
data: {
success: true,
data:
url === '/api/option/request_policy'
? {
options: currentOptions,
}
: {
enabled: true,
total: 2,
unknown: 0,
by_rule_name: { 'Session rule': 2 },
cache_capacity: 100000,
cache_algo: 'lru',
},
},
}))
vi.spyOn(api, 'patch').mockImplementation(async (_url, request) => {
currentOptions = {
...currentOptions,
...(request as { options: Record<string, string> }).options,
}
return {
data: {
success: true,
data: { options: currentOptions },
},
}
})
})
afterEach(async () => {
cleanup()
client.clear()
vi.restoreAllMocks()
await i18next.changeLanguage('en')
})
function Workspace() {
const [container, setContainer] = useState<HTMLDivElement | null>(null)
return (
<>
<div ref={setContainer} />
<SettingsPageProvider actionsContainer={container}>
<RoutingPolicySection />
</SettingsPageProvider>
</>
)
}
function show() {
const router = createRouter({
routeTree: createRootRoute(),
history: createMemoryHistory({ initialEntries: ['/'] }),
})
render(
<QueryClientProvider client={client}>
<RouterContextProvider router={router}>
<Workspace />
</RouterContextProvider>
</QueryClientProvider>
)
}
it('opens global affinity settings and the complete rules table without switching views', async () => {
show()
expect(await screen.findByRole('table')).toBeVisible()
expect(
screen.getByRole('radio', {
name: 'Prefer the original channel, allow switching',
})
).toBeChecked()
expect(
screen.getByRole('radio', { name: 'Do not keep sessions' })
).toBeVisible()
expect(
screen.getByRole('radio', {
name: 'Prefer the original channel, allow switching',
})
).toBeVisible()
expect(
screen.getByRole('radio', {
name: 'Prefer the original channel, allow switching',
})
).toHaveAccessibleDescription('Reduces cache hit rate')
expect(
screen.getByRole('radio', { name: 'Require the original channel' })
).toBeVisible()
expect(
screen.getByRole('spinbutton', {
name: 'Maximum retries',
})
).toBeVisible()
expect(
screen.queryByRole('switch', { name: 'Switch affinity on success' })
).not.toBeInTheDocument()
await userEvent.click(
screen.getByRole('button', { name: 'Affinity cache settings' })
)
expect(
screen.getByRole('spinbutton', { name: 'Maximum cached sessions' })
).toBeVisible()
expect(
screen.getByRole('spinbutton', {
name: 'Default session lifetime (seconds)',
})
).toBeVisible()
expect(
screen.getByRole('switch', {
name: 'Update the session binding after a successful switch',
})
).toBeVisible()
expect(
screen.getByRole('switch', {
name: 'Keep the session binding when the channel is unavailable',
})
).toBeVisible()
expect(screen.getAllByRole('button', { name: 'Save Changes' })).toHaveLength(
1
)
expect(
screen.queryByRole('button', { name: 'Manage all session rules' })
).not.toBeInTheDocument()
})
it('session rules sit between the session defaults and the retry budget', async () => {
show()
const table = await screen.findByRole('table')
const defaults = screen.getByRole('switch', {
name: 'Enable session affinity',
})
const retries = screen.getByRole('spinbutton', { name: 'Maximum retries' })
const follows = (first: Element, second: Element) =>
Boolean(
first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING
)
expect(follows(defaults, table)).toBe(true)
expect(follows(table, retries)).toBe(true)
expect(
screen.queryByRole('complementary', { name: 'Policy preview' })
).not.toBeInTheDocument()
})
it('editing a rule and retries saves one draft without dropping transforms or extension fields', async () => {
show()
const retries = await screen.findByRole('spinbutton', {
name: 'Maximum retries',
})
fireEvent.change(retries, { target: { value: '5' } })
await userEvent.click(screen.getByRole('button', { name: 'Edit Rule' }))
const dialog = screen.getByRole('dialog')
const behavior = within(dialog).getByRole('combobox', {
name: 'Session behavior',
})
expect(behavior).toHaveValue('prefer')
await userEvent.selectOptions(behavior, 'strict')
fireEvent.change(within(dialog).getByRole('textbox', { name: /^Name/ }), {
target: { value: 'Renamed session' },
})
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
expect(api.patch).not.toHaveBeenCalled()
expect(screen.getByRole('table')).toHaveTextContent('Renamed session')
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
const payload = vi.mocked(api.patch).mock.calls[0][1] as {
options: Record<string, string>
}
expect(payload.options.RetryTimes).toBe('5')
expect(Object.keys(payload.options)).toEqual([
'RetryTimes',
'channel_affinity_setting.rules',
])
expect(
JSON.parse(payload.options['channel_affinity_setting.rules'])[0]
).toMatchObject({
name: 'Renamed session',
session_mode: 'strict',
skip_retry_on_failure: false,
include_using_group: false,
param_override_template: { temperature: 0 },
future_field: { retained: true },
})
})
it('keeps binding options available for rule overrides regardless of the global default', async () => {
show()
const children = await screen.findByRole('group', {
name: 'Channel switching options',
})
const update = within(children).getByRole('switch', {
name: 'Update the session binding after a successful switch',
})
const keep = screen.getByRole('switch', {
name: 'Keep the session binding when the channel is unavailable',
})
expect(children).not.toContainElement(keep)
await userEvent.click(update)
await userEvent.click(
screen.getByRole('radio', { name: 'Require the original channel' })
)
expect(children).toBeVisible()
expect(keep).toBeVisible()
expect(keep).not.toHaveAttribute('aria-disabled', 'true')
await userEvent.click(keep)
await userEvent.click(
screen.getByRole('radio', { name: 'Do not keep sessions' })
)
expect(keep).toBeVisible()
expect(keep).not.toHaveAttribute('aria-disabled', 'true')
expect(update).not.toHaveAttribute('aria-disabled', 'true')
await userEvent.click(
screen.getByRole('radio', {
name: 'Prefer the original channel, allow switching',
})
)
expect(children).toBeVisible()
expect(update).toBeChecked()
expect(keep).toBeChecked()
await userEvent.click(
screen.getByRole('switch', {
name: 'Enable session affinity',
})
)
expect(update).toHaveAttribute('aria-disabled', 'true')
expect(keep).toHaveAttribute('aria-disabled', 'true')
await userEvent.click(
screen.getByRole('switch', {
name: 'Enable session affinity',
})
)
expect(api.patch).not.toHaveBeenCalled()
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
expect(vi.mocked(api.patch).mock.calls[0][1]).toEqual({
options: {
'channel_affinity_setting.session_mode': 'prefer',
'channel_affinity_setting.switch_on_success': 'true',
'channel_affinity_setting.keep_on_channel_disabled': 'true',
},
})
})
it('a failed save retains the edited retries and rules for another save', async () => {
vi.mocked(api.patch).mockResolvedValue({
data: { success: false, message: 'Save rejected' },
})
show()
const retries = await screen.findByRole('spinbutton', {
name: 'Maximum retries',
})
fireEvent.change(retries, { target: { value: '5' } })
await userEvent.click(screen.getByRole('button', { name: 'Edit Rule' }))
const dialog = screen.getByRole('dialog')
fireEvent.change(within(dialog).getByRole('textbox', { name: /^Name/ }), {
target: { value: 'Unsaved rule' },
})
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
expect(await screen.findByText('Save rejected')).toBeVisible()
expect(retries).toHaveValue(5)
expect(screen.getByRole('table')).toHaveTextContent('Unsaved rule')
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(2))
})
it.each([
['off', 'Do not keep sessions'],
['prefer', 'Prefer the original channel, allow switching'],
['strict', 'Require the original channel'],
])(
'global default %s updates only inheriting rules without rewriting rule JSON',
async (mode, label) => {
const original = JSON.parse(
currentOptions['channel_affinity_setting.rules']
)[0]
const rulesJson = JSON.stringify([
{ ...original, name: 'Inherited session', session_mode: 'inherit' },
{ ...original, name: 'Strict session', session_mode: 'strict' },
{ ...original, name: 'Prefer session', session_mode: 'prefer' },
{ ...original, name: 'Off session', session_mode: 'off' },
{
...original,
name: 'Legacy session',
session_mode: undefined,
skip_retry_on_failure: true,
},
])
currentOptions['channel_affinity_setting.rules'] = rulesJson
show()
await userEvent.click(await screen.findByRole('radio', { name: label }))
const inherited = screen.getByRole('row', {
name: /Inherited session.*X-Session/,
})
expect(inherited).toHaveTextContent(label)
expect(inherited).toHaveTextContent('Inherit global default')
expect(
screen.getByRole('row', { name: /Strict session.*X-Session/ })
).toHaveTextContent('Require the original channel')
expect(
screen.getByRole('row', { name: /Prefer session.*X-Session/ })
).toHaveTextContent('Prefer the original channel, allow switching')
expect(
screen.getByRole('row', { name: /Off session.*X-Session/ })
).toHaveTextContent('Do not keep sessions')
expect(
screen.getByRole('row', { name: /Legacy session.*X-Session/ })
).toHaveTextContent('Require the original channel')
expect(
within(screen.getByRole('table')).getAllByText('Rule override')
).toHaveLength(4)
expect(
screen.queryByRole('radio', { name: 'Use per-rule settings' })
).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
expect(vi.mocked(api.patch).mock.calls[0][1]).toEqual({
options: { 'channel_affinity_setting.session_mode': mode },
})
expect(currentOptions['channel_affinity_setting.rules']).toBe(rulesJson)
expect(screen.getByRole('radio', { name: label })).toBeChecked()
await userEvent.click(
within(inherited).getByRole('button', { name: 'Edit Rule' })
)
const dialog = screen.getByRole('dialog')
expect(
within(dialog).getByRole('combobox', { name: 'Session behavior' })
).toHaveValue('inherit')
expect(dialog).toHaveTextContent(`Global default: ${label}`)
}
)
it('switching between visual and JSON editing preserves the shared draft', async () => {
show()
fireEvent.change(
await screen.findByRole('spinbutton', {
name: 'Maximum retries',
}),
{ target: { value: '7' } }
)
await userEvent.click(screen.getByRole('tab', { name: 'JSON' }))
const editor = await screen.findByRole('textbox', { name: 'Rules JSON' })
const updated = JSON.parse(options['channel_affinity_setting.rules'])
updated[0].name = 'JSON rule'
fireEvent.input(editor, { target: { value: JSON.stringify(updated) } })
await userEvent.click(screen.getByRole('tab', { name: 'Visual' }))
expect(screen.getByRole('table')).toHaveTextContent('JSON rule')
expect(
screen.getByRole('spinbutton', {
name: 'Maximum retries',
})
).toHaveValue(7)
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
expect(currentOptions.RetryTimes).toBe('7')
expect(
JSON.parse(currentOptions['channel_affinity_setting.rules'])[0]
).toMatchObject({ name: 'JSON rule', future_field: { retained: true } })
})
it('editing a rule without a session mode saves the chosen override with the retries', async () => {
const legacyRules = JSON.parse(options['channel_affinity_setting.rules'])
delete legacyRules[0].session_mode
currentOptions = {
...options,
'channel_affinity_setting.rules': JSON.stringify(legacyRules),
}
show()
await screen.findByRole('table')
fireEvent.change(
await screen.findByRole('spinbutton', {
name: 'Maximum retries',
}),
{ target: { value: '4' } }
)
await userEvent.click(screen.getByRole('button', { name: 'Edit Rule' }))
const dialog = screen.getByRole('dialog')
const behavior = within(dialog).getByRole('combobox', {
name: 'Session behavior',
})
expect(behavior).toHaveValue('prefer')
await userEvent.selectOptions(behavior, 'strict')
fireEvent.change(within(dialog).getByRole('textbox', { name: /^Name/ }), {
target: { value: 'Renamed rule' },
})
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
expect(currentOptions.RetryTimes).toBe('4')
const savedRule = JSON.parse(
currentOptions['channel_affinity_setting.rules']
)[0]
expect(savedRule).toHaveProperty('session_mode', 'strict')
expect(savedRule).toMatchObject({
name: 'Renamed rule',
skip_retry_on_failure: false,
include_using_group: false,
param_override_template: { temperature: 0 },
future_field: { retained: true },
})
})
it('switches a rule between inheritance and override while preserving other rules', async () => {
const rules = JSON.parse(options['channel_affinity_setting.rules'])
const second = {
...rules[0],
name: 'Strict session',
session_mode: 'strict',
skip_retry_on_failure: true,
}
rules.push(second)
currentOptions['channel_affinity_setting.rules'] = JSON.stringify(rules)
currentOptions['channel_affinity_setting.session_mode'] = 'prefer'
show()
await screen.findByRole('table')
await userEvent.click(
within(
screen.getByRole('row', { name: /Session rule.*X-Session/ })
).getByRole('button', { name: 'Edit Rule' })
)
let dialog = screen.getByRole('dialog')
await userEvent.selectOptions(
within(dialog).getByRole('combobox', { name: 'Session behavior' }),
'inherit'
)
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
expect(
screen.getByRole('row', { name: /Session rule.*X-Session/ })
).toHaveTextContent('Inherit global default')
await userEvent.click(
screen.getByRole('radio', { name: 'Require the original channel' })
)
expect(
screen.getByRole('row', { name: /Session rule.*X-Session/ })
).toHaveTextContent('Require the original channel')
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
expect(
JSON.parse(currentOptions['channel_affinity_setting.rules'])[0].session_mode
).toBe('inherit')
await userEvent.click(
within(
screen.getByRole('row', { name: /Session rule.*X-Session/ })
).getByRole('button', { name: 'Edit Rule' })
)
dialog = screen.getByRole('dialog')
expect(
within(dialog).getByRole('combobox', { name: 'Session behavior' })
).toHaveValue('inherit')
await userEvent.selectOptions(
within(dialog).getByRole('combobox', { name: 'Session behavior' }),
'off'
)
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
expect(
screen.getByRole('row', { name: /Session rule.*X-Session/ })
).toHaveTextContent('Do not keep sessions')
expect(
screen.getByRole('row', { name: /Strict session.*X-Session/ })
).toHaveTextContent('Require the original channel')
expect(
screen.getByRole('radio', { name: 'Require the original channel' })
).toBeChecked()
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(2))
expect(currentOptions['channel_affinity_setting.session_mode']).toBe('strict')
const savedRules = JSON.parse(
currentOptions['channel_affinity_setting.rules']
)
expect(savedRules[0]).toMatchObject({
session_mode: 'off',
param_override_template: { temperature: 0 },
future_field: { retained: true },
})
expect(savedRules[1]).toEqual(second)
})
it('a new blank rule inherits the global default', async () => {
show()
await userEvent.click(await screen.findByRole('button', { name: 'Add Rule' }))
await userEvent.click(screen.getByRole('menuitem', { name: 'Blank Rule' }))
expect(
within(screen.getByRole('dialog')).getByRole('combobox', {
name: 'Session behavior',
})
).toHaveValue('inherit')
})
it('refreshing settings preserves unsaved rule and retry edits', async () => {
show()
fireEvent.change(
await screen.findByRole('spinbutton', {
name: 'Maximum retries',
}),
{ target: { value: '7' } }
)
await userEvent.click(screen.getByRole('button', { name: 'More actions' }))
await userEvent.click(screen.getByRole('menuitem', { name: 'Delete Rule' }))
await userEvent.click(
within(screen.getByRole('alertdialog')).getByRole('button', {
name: 'Delete Rule',
})
)
currentOptions = {
...currentOptions,
'channel_affinity_setting.default_ttl_seconds': '120',
}
await act(async () => {
await client.invalidateQueries({ queryKey: ['request-policy'] })
})
expect(
screen.getByRole('spinbutton', {
name: 'Maximum retries',
})
).toHaveValue(7)
await userEvent.click(
screen.getByRole('button', { name: 'Affinity cache settings' })
)
await waitFor(() =>
expect(
screen.getByRole('spinbutton', {
name: 'Default session lifetime (seconds)',
})
).toHaveValue(120)
)
expect(screen.getByText('No rules yet')).toBeVisible()
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
expect(vi.mocked(api.patch).mock.calls[0][1]).toEqual({
options: { RetryTimes: '7', 'channel_affinity_setting.rules': '[]' },
})
})
it('disabling global affinity preserves every rule and saves zero retries as zero', async () => {
show()
fireEvent.change(
await screen.findByRole('spinbutton', {
name: 'Maximum retries',
}),
{ target: { value: '0' } }
)
await userEvent.click(
screen.getByRole('switch', {
name: 'Enable session affinity',
})
)
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(1))
expect(vi.mocked(api.patch).mock.calls[0][1]).toEqual({
options: { RetryTimes: '0', 'channel_affinity_setting.enabled': 'false' },
})
expect(screen.getByRole('table')).toHaveTextContent('Session rule')
expect(screen.getByRole('table')).toHaveTextContent('Disabled globally')
expect(screen.getByRole('table')).toHaveTextContent('Do not keep sessions')
})
it('invalid JSON stays editable and prevents saving', async () => {
show()
await userEvent.click(await screen.findByRole('tab', { name: 'JSON' }))
const editor = await screen.findByRole('textbox', { name: 'Rules JSON' })
fireEvent.input(editor, { target: { value: '[' } })
expect(screen.getByRole('button', { name: 'Add Rule' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Fill Templates' })).toBeDisabled()
await userEvent.click(screen.getByRole('tab', { name: 'Visual' }))
expect(screen.getByRole('tab', { name: 'JSON' })).toHaveAttribute(
'aria-selected',
'true'
)
expect(editor).toHaveValue('[')
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
expect(await screen.findByText('Invalid rules JSON format')).toBeVisible()
expect(editor).toHaveValue('[')
expect(api.patch).not.toHaveBeenCalled()
})
it('cache cleanup uses the existing cache API without saving the draft', async () => {
vi.spyOn(api, 'delete').mockResolvedValue({ data: { success: true } })
show()
await userEvent.click(
await screen.findByRole('button', { name: 'Clear All Cache' })
)
await userEvent.click(
within(screen.getByRole('alertdialog')).getByRole('button', {
name: 'Continue',
})
)
await waitFor(() =>
expect(api.delete).toHaveBeenCalledWith(
'/api/option/channel_affinity_cache',
{ params: { all: true } }
)
)
expect(api.patch).not.toHaveBeenCalled()
})
it('keyboard navigation switches editor tabs and restores the visual draft', async () => {
const user = userEvent.setup()
show()
const visual = await screen.findByRole('tab', { name: 'Visual' })
visual.focus()
await user.keyboard('{ArrowRight}{Enter}')
expect(screen.getByRole('tab', { name: 'JSON' })).toHaveAttribute(
'aria-selected',
'true'
)
expect(
await screen.findByRole('textbox', { name: 'Rules JSON' })
).toBeVisible()
await user.keyboard('{ArrowLeft}{Enter}')
expect(visual).toHaveAttribute('aria-selected', 'true')
expect(screen.getByRole('table')).toHaveTextContent('Session rule')
expect(screen.getByRole('button', { name: 'Add Rule' })).toBeEnabled()
expect(api.patch).not.toHaveBeenCalled()
})
it('cancelling deletion from the rule menu leaves the rule in the draft', async () => {
show()
await userEvent.click(
await screen.findByRole('button', { name: 'More actions' })
)
await userEvent.click(screen.getByRole('menuitem', { name: 'Delete Rule' }))
const dialog = screen.getByRole('alertdialog')
expect(dialog).toHaveTextContent('Session rule')
await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
expect(screen.getByRole('table')).toHaveTextContent('Session rule')
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
expect(api.patch).not.toHaveBeenCalled()
})
it('the empty state can fill templates without saving them to the server', async () => {
currentOptions['channel_affinity_setting.rules'] = '[]'
show()
const panel = await screen.findByRole('tabpanel', { name: 'Visual' })
expect(within(panel).getByText('No rules yet')).toBeVisible()
await userEvent.click(
within(panel).getByRole('button', { name: 'Fill Templates' })
)
expect(screen.getByRole('table')).toHaveTextContent('codex cli trace')
expect(screen.getByRole('table')).toHaveTextContent('claude cli trace')
expect(screen.queryByText('No rules yet')).not.toBeInTheDocument()
expect(api.patch).not.toHaveBeenCalled()
})
it('long rule fields stay in a keyboard-scrollable table and reveal the full name on focus', async () => {
const rule = JSON.parse(options['channel_affinity_setting.rules'])[0]
const name =
'Production Codex CLI session rule for shared multi-region inference channels'
currentOptions['channel_affinity_setting.rules'] = JSON.stringify([
{
...rule,
name,
key_sources: [
{
type: 'gjson',
path: 'metadata.session.conversation.trace.identifiers.primary_cache_key',
},
],
},
])
show()
const region = await screen.findByRole('region', {
name: 'Session rules table',
})
expect(region).toHaveAttribute('tabindex', '0')
expect(region).toHaveClass('overflow-x-auto')
expect(within(region).getByRole('table')).toHaveClass('table-fixed')
const nameCell = within(region).getByText(name)
expect(nameCell).toHaveClass('truncate')
act(() => region.focus())
await userEvent.tab()
expect(nameCell.closest('[tabindex]')).toHaveFocus()
await waitFor(() => expect(screen.getAllByText(name)).toHaveLength(2))
expect(
within(region).getByRole('button', { name: 'More actions' })
).toBeEnabled()
})
it('unavailable cache statistics show an unknown count and refresh recovers the summary', async () => {
const get = vi.mocked(api.get).getMockImplementation()
if (!get) throw new Error('API fixture is not initialized')
let cacheAvailable = false
vi.mocked(api.get).mockImplementation(async (url, config) => {
if (url === '/api/option/channel_affinity_cache' && !cacheAvailable) {
return { data: { success: false, message: 'Cache service unavailable' } }
}
return get(url, config)
})
show()
const section = await screen.findByRole('region', {
name: 'Session rules',
})
const status = within(section).getByRole('status')
await waitFor(() => expect(status).toHaveTextContent('Unavailable'))
const row = within(section).getByRole('row', {
name: /Session rule.*X-Session/,
})
expect(within(row).getByRole('cell', { name: '—' })).toBeVisible()
cacheAvailable = true
await userEvent.click(
within(section).getByRole('button', { name: 'Refresh Cache' })
)
await waitFor(() => expect(status).toHaveTextContent(/2\s*\/\s*100,000/))
expect(within(row).getByRole('cell', { name: '2' })).toBeVisible()
expect(api.patch).not.toHaveBeenCalled()
})
it.each([
['zhCN', /100,000/, '3,600 seconds'],
['zhTW', /100,000/, '3,600 seconds'],
['en', /100,000/, '3,600 seconds'],
['ja', /100,000/, '3,600 seconds'],
['fr', /100\s000/, /3\s600 seconds/],
['ru', /100\s000/, /3\s600 seconds/],
['vi', /100\.000/, '3.600 seconds'],
['invalid_locale', /100,000/, '3,600 seconds'],
] as const)(
'renders cache statistics and TTL with the project language code %s and updates formatting after a language switch',
async (language, capacity, ttl) => {
const rules = JSON.parse(options['channel_affinity_setting.rules'])
rules[0].ttl_seconds = 3600
currentOptions['channel_affinity_setting.rules'] = JSON.stringify(rules)
await i18next.changeLanguage(language)
show()
const section = await screen.findByRole('region', { name: 'Session rules' })
const status = within(section).getByRole('status')
await waitFor(() => expect(status).toHaveTextContent(capacity))
const table = within(section).getByRole('table')
expect(within(table).getByRole('cell', { name: ttl })).toBeVisible()
expect(within(table).getByRole('cell', { name: '2' })).toBeVisible()
await act(async () => {
await i18next.changeLanguage('fr')
})
await waitFor(() => expect(status).toHaveTextContent(/2\s*\/\s*100\s000/))
expect(
within(table).getByRole('cell', { name: /3\s600 seconds/ })
).toBeVisible()
expect(api.patch).not.toHaveBeenCalled()
}
)
@@ -0,0 +1,368 @@
/*
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 { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
RouterProvider,
} from '@tanstack/react-router'
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { api } from '@/lib/api'
import { Route as ModelsRoute } from '@/routes/_authenticated/system-settings/models/$section'
import { Route as OperationsRoute } from '@/routes/_authenticated/system-settings/operations/$section'
import { Route as PoliciesRoute } from '@/routes/_authenticated/system-settings/request-policies/$section'
import { Route as PolicyIndexRoute } from '@/routes/_authenticated/system-settings/request-policies/index'
import { Route as SecurityRoute } from '@/routes/_authenticated/system-settings/security/$section'
import { RequestPolicies } from '..'
import {
defaultRequestPolicySettings,
type RequestPolicySettings,
} from '../defaults'
type PolicyBeforeLoad = (context: { params: { section: string } }) => void
let queryClient: QueryClient
let settings: RequestPolicySettings
function optionsResponse() {
return {
success: true,
data: Object.entries(settings).map(([key, value]) => ({
key,
value: String(value),
})),
}
}
async function renderPolicies(path: string) {
const root = createRootRoute()
const authenticated = createRoute({
getParentRoute: () => root,
id: '_authenticated',
})
const policyRoute = createRoute({
getParentRoute: () => authenticated,
path: '/system-settings/request-policies/$section',
beforeLoad: PoliciesRoute.options.beforeLoad as PolicyBeforeLoad,
component: RequestPolicies,
})
const routes = [
policyRoute,
createRoute({
getParentRoute: () => authenticated,
path: '/system-settings/request-policies/',
beforeLoad: PolicyIndexRoute.options.beforeLoad as () => void,
}),
createRoute({
getParentRoute: () => authenticated,
path: '/system-settings/models/$section',
beforeLoad: ModelsRoute.options.beforeLoad as PolicyBeforeLoad,
}),
createRoute({
getParentRoute: () => authenticated,
path: '/system-settings/security/$section',
beforeLoad: SecurityRoute.options.beforeLoad as PolicyBeforeLoad,
}),
createRoute({
getParentRoute: () => authenticated,
path: '/system-settings/operations/$section',
beforeLoad: OperationsRoute.options.beforeLoad as PolicyBeforeLoad,
}),
]
const router = createRouter({
routeTree: root.addChildren([authenticated.addChildren(routes)]),
history: createMemoryHistory({ initialEntries: [path] }),
})
render(
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
)
await act(() => router.load())
return router
}
beforeEach(() => {
vi.spyOn(window, 'scrollTo').mockImplementation(() => undefined)
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
settings = {
...defaultRequestPolicySettings,
RetryTimes: 2,
AutomaticRetryStatusCodes: '429,500-503',
AutomaticDisableChannelEnabled: true,
AutomaticEnableChannelEnabled: true,
'monitor_setting.auto_test_channel_enabled': true,
CheckSensitiveEnabled: true,
CheckSensitiveOnPromptEnabled: true,
SensitiveWords: 'blocked',
'channel_affinity_setting.rules': JSON.stringify([
{
name: 'Existing session rule',
model_regex: ['gpt-.*'],
path_regex: ['/v1/chat/completions'],
key_sources: [{ type: 'request_header', key: 'X-Session-ID' }],
ttl_seconds: 600,
skip_retry_on_failure: true,
include_using_group: true,
include_model_name: false,
include_rule_name: true,
param_override_template: { temperature: 0 },
},
]),
}
vi.spyOn(api, 'patch').mockResolvedValue({
data: {
success: true,
data: { options: {} },
},
})
vi.spyOn(api, 'get').mockImplementation(async (url) => {
if (url === '/api/option/') return { data: optionsResponse() }
if (url === '/api/option/request_policy') {
return {
data: {
success: true,
data: {
options: Object.fromEntries(
Object.entries(settings).map(([key, value]) => [
key,
String(value),
])
),
},
},
}
}
return {
data: {
success: true,
data: {
enabled: false,
total: 0,
unknown: 0,
by_rule_name: {},
cache_capacity: 100000,
cache_algo: 'lru',
},
},
}
})
vi.spyOn(api, 'put').mockResolvedValue({ data: { success: true } })
})
afterEach(() => {
cleanup()
queryClient.clear()
})
describe('request policy settings', () => {
it.each([
['retry', 'Save Changes'],
['health', 'Save Changes'],
['filtering', 'Save sensitive words'],
['affinity', 'Save Changes'],
])(
'opening %s and saving unchanged values does not write options',
async (section, saveLabel) => {
await renderPolicies(`/system-settings/request-policies/${section}`)
const save = await screen.findByRole('button', { name: saveLabel })
expect(api.put).not.toHaveBeenCalled()
await userEvent.click(save)
await waitFor(() => expect(save).toBeEnabled())
expect(api.put).not.toHaveBeenCalled()
}
)
it.each([
[
'health',
'Channel test concurrency',
'4',
'monitor_setting.channel_test_concurrency',
4,
],
])(
'saving a changed %s field writes only that original option key',
async (section, label, input, key, value) => {
await renderPolicies(`/system-settings/request-policies/${section}`)
fireEvent.change(await screen.findByRole('spinbutton', { name: label }), {
target: { value: input },
})
await userEvent.click(
screen.getByRole('button', { name: 'Save Changes' })
)
await waitFor(() =>
expect(api.patch).toHaveBeenCalledExactlyOnceWith(
'/api/option/request_policy',
{ options: { [key]: String(value) } }
)
)
}
)
it('turning filtering off preserves the prompt switch and keyword list', async () => {
await renderPolicies('/system-settings/request-policies/filtering')
await userEvent.click(
await screen.findByRole('switch', { name: 'Enable filtering' })
)
const prompt = screen.getByRole('switch', { name: 'Inspect user prompts' })
expect(prompt).toHaveAttribute('aria-disabled', 'true')
expect(prompt).toBeChecked()
expect(
screen.getByRole('textbox', { name: 'Blocked keywords' })
).toHaveValue('blocked')
await userEvent.click(
screen.getByRole('button', { name: 'Save sensitive words' })
)
await waitFor(() =>
expect(api.patch).toHaveBeenCalledExactlyOnceWith(
'/api/option/request_policy',
{ options: { CheckSensitiveEnabled: 'false' } }
)
)
})
it('refreshing another policy keeps unsaved filter text', async () => {
await renderPolicies('/system-settings/request-policies/filtering')
const keywords = await screen.findByRole('textbox', {
name: 'Blocked keywords',
})
fireEvent.change(keywords, { target: { value: 'unsaved' } })
settings.RetryTimes = 5
await act(async () => {
await queryClient.invalidateQueries({ queryKey: ['system-options'] })
})
expect(keywords).toHaveValue('unsaved')
})
it('invalid retry status ranges show validation and do not write options', async () => {
await renderPolicies('/system-settings/request-policies/retry')
const codes = await screen.findByRole('textbox', {
name: 'Auto-retry status codes',
})
expect(codes).toBeVisible()
expect(
screen.queryByRole('button', { name: 'Advanced settings' })
).not.toBeInTheDocument()
fireEvent.change(codes, { target: { value: '599-500' } })
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
expect(codes).toHaveAttribute('aria-invalid', 'true')
expect(api.put).not.toHaveBeenCalled()
})
it('a rejected save keeps the edited retry value and allows another save', async () => {
vi.mocked(api.patch).mockResolvedValue({
data: { success: false, message: 'Save rejected' },
})
await renderPolicies('/system-settings/request-policies/retry')
const retries = await screen.findByRole('spinbutton', {
name: 'Maximum retries',
})
fireEvent.change(retries, { target: { value: '4' } })
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Save Changes' })).toBeEnabled()
)
expect(retries).toHaveValue(4)
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
await waitFor(() => expect(api.patch).toHaveBeenCalledTimes(2))
})
it('failed initial loading shows a retry action instead of editable fallback values', async () => {
vi.mocked(api.get).mockRejectedValueOnce(new Error('Unavailable'))
await renderPolicies('/system-settings/request-policies/retry')
expect(await screen.findByText('Failed to load settings')).toBeVisible()
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
expect(
await screen.findByRole('spinbutton', {
name: 'Maximum retries',
})
).toHaveValue(2)
expect(api.put).not.toHaveBeenCalled()
})
it('turning scheduled checks off explains recovery without changing the recovery setting', async () => {
await renderPolicies('/system-settings/request-policies/health')
await userEvent.click(
await screen.findByRole('switch', { name: 'Scheduled channel tests' })
)
expect(
screen.getByText(
'Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.'
)
).toBeVisible()
expect(
screen.getByRole('switch', { name: 'Re-enable on success' })
).toBeChecked()
expect(api.put).not.toHaveBeenCalled()
})
it('the affinity cache section opens with the keyboard and keeps the existing values', async () => {
await renderPolicies('/system-settings/request-policies/affinity')
const toggle = await screen.findByRole('button', {
name: 'Affinity cache settings',
})
expect(toggle).toHaveAttribute('aria-expanded', 'false')
toggle.focus()
await userEvent.keyboard('{Enter}')
expect(toggle).toHaveAttribute('aria-expanded', 'true')
expect(
screen.getByRole('spinbutton', { name: 'Maximum cached sessions' })
).toHaveValue(100000)
expect(
screen.getByRole('spinbutton', {
name: 'Default session lifetime (seconds)',
})
).toHaveValue(3600)
expect(api.put).not.toHaveBeenCalled()
})
it.each([
['/system-settings/models/channel-affinity', 'routing'],
['/system-settings/models/routing-reliability', 'routing'],
['/system-settings/security/sensitive-words', 'filtering'],
['/system-settings/operations/monitoring', 'health'],
['/system-settings/request-policies/', 'routing'],
['/system-settings/request-policies/unknown', 'routing'],
])('%s opens the corresponding policy page', async (path, section) => {
const router = await renderPolicies(path)
await waitFor(() =>
expect(router.state.location.pathname).toBe(
`/system-settings/request-policies/${section}`
)
)
expect(api.put).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,33 @@
import { api } from '@/lib/api'
import { requireServerSuccess } from '@/lib/server-error-message'
export type PolicyConfig = {
options: Record<string, string>
}
export type PolicyDecision = { action: string; reason: string; source: string }
export type PolicyEvent = {
attempt: number
channel_id?: number
group?: string
rule?: string
status?: number
error_code?: string
error_source?: string
elapsed_ms: number
decision: PolicyDecision
health?: string
}
type Response<T> = { success: boolean; message?: string; data: T }
export async function getPolicyConfig() {
const response = await api.get<Response<PolicyConfig>>(
'/api/option/request_policy'
)
return requireServerSuccess(response.data).data
}
export async function savePolicyConfig(options: Record<string, string>) {
const response = await api.patch<Response<PolicyConfig>>(
'/api/option/request_policy',
{ options }
)
return requireServerSuccess(response.data).data
}
@@ -17,12 +17,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { zodResolver } from '@hookform/resolvers/zod'
import { useMemo, useRef } from 'react'
import { Link } from '@tanstack/react-router'
import { useMemo, useRef, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import * as z from 'zod'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
Form,
FormControl,
@@ -44,6 +46,7 @@ import {
import { Separator } from '@/components/ui/separator'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { handleServerError } from '@/lib/handle-server-error'
import { parseHttpStatusCodeRules } from '@/lib/http-status-code-rules'
import {
@@ -54,8 +57,9 @@ import {
import { SettingsPageFormActions } from '../components/settings-page-context'
import { SettingsSection } from '../components/settings-section'
import { useResetForm } from '../hooks/use-reset-form'
import { useUpdateOption } from '../hooks/use-update-option'
import { safeNumberFieldProps } from '../utils/numeric-field'
import type { HealthSettings } from './defaults'
import { useSavePolicy } from './use-save-policy'
const numericString = z.string().refine((value) => {
const trimmed = value.trim()
@@ -71,18 +75,16 @@ const channelTestModes = [
type ChannelTestMode = (typeof channelTestModes)[number]
const MAX_CHANNEL_TEST_CONCURRENCY = 32
const createRoutingReliabilitySchema = (
const createChannelHealthSchema = (
t: (key: string, options?: Record<string, unknown>) => string
) =>
z
.object({
RetryTimes: z.coerce.number().min(0).max(10),
ChannelDisableThreshold: numericString,
AutomaticDisableChannelEnabled: z.boolean(),
AutomaticEnableChannelEnabled: z.boolean(),
AutomaticDisableKeywords: z.string(),
AutomaticDisableStatusCodes: z.string(),
AutomaticRetryStatusCodes: z.string(),
monitor_setting: z.object({
auto_test_channel_enabled: z.boolean(),
auto_test_channel_minutes: z.coerce
@@ -113,55 +115,26 @@ const createRoutingReliabilitySchema = (
}),
})
}
const retryParsed = parseHttpStatusCodeRules(
values.AutomaticRetryStatusCodes
)
if (!retryParsed.ok) {
ctx.addIssue({
code: 'custom',
path: ['AutomaticRetryStatusCodes'],
message: t('Invalid status code rules: {{tokens}}', {
tokens: retryParsed.invalidTokens.join(', '),
}),
})
}
})
type RoutingReliabilitySchema = ReturnType<
typeof createRoutingReliabilitySchema
>
type RoutingReliabilityFormValues = z.output<RoutingReliabilitySchema>
type RoutingReliabilityFormInput = z.input<RoutingReliabilitySchema>
type ChannelHealthSchema = ReturnType<typeof createChannelHealthSchema>
type ChannelHealthFormValues = z.output<ChannelHealthSchema>
type ChannelHealthFormInput = z.input<ChannelHealthSchema>
type RoutingReliabilitySectionProps = {
defaultValues: {
RetryTimes: number
ChannelDisableThreshold: string
AutomaticDisableChannelEnabled: boolean
AutomaticEnableChannelEnabled: boolean
AutomaticDisableKeywords: string
AutomaticDisableStatusCodes: string
AutomaticRetryStatusCodes: string
'monitor_setting.auto_test_channel_enabled': boolean
'monitor_setting.auto_test_channel_minutes': number
'monitor_setting.channel_test_concurrency': number
'monitor_setting.channel_test_mode': ChannelTestMode
}
type ChannelHealthSectionProps = {
defaultValues: HealthSettings
}
function normalizeLineEndings(value: string) {
return value.replaceAll('\r\n', '\n')
}
type NormalizedRoutingReliabilityValues = {
RetryTimes: number
type NormalizedChannelHealthValues = {
ChannelDisableThreshold: string
AutomaticDisableChannelEnabled: boolean
AutomaticEnableChannelEnabled: boolean
AutomaticDisableKeywords: string
AutomaticDisableStatusCodes: string
AutomaticRetryStatusCodes: string
'monitor_setting.auto_test_channel_enabled': boolean
'monitor_setting.auto_test_channel_minutes': number
'monitor_setting.channel_test_concurrency': number
@@ -176,9 +149,8 @@ function normalizeChannelTestMode(value?: string): ChannelTestMode {
}
const buildFormDefaults = (
defaults: RoutingReliabilitySectionProps['defaultValues']
): RoutingReliabilityFormInput => ({
RetryTimes: defaults.RetryTimes ?? 0,
defaults: ChannelHealthSectionProps['defaultValues']
): ChannelHealthFormInput => ({
ChannelDisableThreshold: defaults.ChannelDisableThreshold ?? '',
AutomaticDisableChannelEnabled: defaults.AutomaticDisableChannelEnabled,
AutomaticEnableChannelEnabled: defaults.AutomaticEnableChannelEnabled,
@@ -186,7 +158,6 @@ const buildFormDefaults = (
defaults.AutomaticDisableKeywords ?? ''
),
AutomaticDisableStatusCodes: defaults.AutomaticDisableStatusCodes ?? '',
AutomaticRetryStatusCodes: defaults.AutomaticRetryStatusCodes ?? '',
monitor_setting: {
auto_test_channel_enabled:
defaults['monitor_setting.auto_test_channel_enabled'],
@@ -201,9 +172,8 @@ const buildFormDefaults = (
})
const normalizeDefaults = (
defaults: RoutingReliabilitySectionProps['defaultValues']
): NormalizedRoutingReliabilityValues => ({
RetryTimes: defaults.RetryTimes ?? 0,
defaults: ChannelHealthSectionProps['defaultValues']
): NormalizedChannelHealthValues => ({
ChannelDisableThreshold: (defaults.ChannelDisableThreshold ?? '').trim(),
AutomaticDisableChannelEnabled: defaults.AutomaticDisableChannelEnabled,
AutomaticEnableChannelEnabled: defaults.AutomaticEnableChannelEnabled,
@@ -213,9 +183,6 @@ const normalizeDefaults = (
AutomaticDisableStatusCodes: parseHttpStatusCodeRules(
defaults.AutomaticDisableStatusCodes ?? ''
).normalized,
AutomaticRetryStatusCodes: parseHttpStatusCodeRules(
defaults.AutomaticRetryStatusCodes ?? ''
).normalized,
'monitor_setting.auto_test_channel_enabled':
defaults['monitor_setting.auto_test_channel_enabled'],
'monitor_setting.auto_test_channel_minutes':
@@ -228,9 +195,8 @@ const normalizeDefaults = (
})
const normalizeFormValues = (
values: RoutingReliabilityFormValues
): NormalizedRoutingReliabilityValues => ({
RetryTimes: values.RetryTimes,
values: ChannelHealthFormValues
): NormalizedChannelHealthValues => ({
ChannelDisableThreshold: values.ChannelDisableThreshold.trim(),
AutomaticDisableChannelEnabled: values.AutomaticDisableChannelEnabled,
AutomaticEnableChannelEnabled: values.AutomaticEnableChannelEnabled,
@@ -240,9 +206,6 @@ const normalizeFormValues = (
AutomaticDisableStatusCodes: parseHttpStatusCodeRules(
values.AutomaticDisableStatusCodes
).normalized,
AutomaticRetryStatusCodes: parseHttpStatusCodeRules(
values.AutomaticRetryStatusCodes
).normalized,
'monitor_setting.auto_test_channel_enabled':
values.monitor_setting.auto_test_channel_enabled,
'monitor_setting.auto_test_channel_minutes':
@@ -252,13 +215,13 @@ const normalizeFormValues = (
'monitor_setting.channel_test_mode': values.monitor_setting.channel_test_mode,
})
export function RoutingReliabilitySection({
export function ChannelHealthSection({
defaultValues,
}: RoutingReliabilitySectionProps) {
}: ChannelHealthSectionProps) {
const { t } = useTranslation()
const updateOption = useUpdateOption()
const routingReliabilitySchema = createRoutingReliabilitySchema(t)
const baselineRef = useRef<NormalizedRoutingReliabilityValues>(
const updateOption = useSavePolicy()
const channelHealthSchema = createChannelHealthSchema(t)
const baselineRef = useRef<NormalizedChannelHealthValues>(
normalizeDefaults(defaultValues)
)
@@ -268,18 +231,20 @@ export function RoutingReliabilitySection({
)
const form = useForm<
RoutingReliabilityFormInput,
ChannelHealthFormInput,
unknown,
RoutingReliabilityFormValues
ChannelHealthFormValues
>({
resolver: zodResolver(routingReliabilitySchema),
resolver: zodResolver(channelHealthSchema),
defaultValues: formDefaults,
})
useResetForm(form, formDefaults)
useEffect(() => {
baselineRef.current = normalizeDefaults(defaultValues)
}, [defaultValues])
const autoDisableStatusCodes = form.watch('AutomaticDisableStatusCodes')
const autoRetryStatusCodes = form.watch('AutomaticRetryStatusCodes')
const channelTestMode = form.watch('monitor_setting.channel_test_mode')
let channelTestModeDescription: string
switch (channelTestMode) {
@@ -302,15 +267,11 @@ export function RoutingReliabilitySection({
() => parseHttpStatusCodeRules(autoDisableStatusCodes),
[autoDisableStatusCodes]
)
const autoRetryParsed = useMemo(
() => parseHttpStatusCodeRules(autoRetryStatusCodes),
[autoRetryStatusCodes]
)
const onSubmit = async (values: RoutingReliabilityFormValues) => {
const onSubmit = async (values: ChannelHealthFormValues) => {
const normalized = normalizeFormValues(values)
const updates = (
Object.keys(normalized) as Array<keyof NormalizedRoutingReliabilityValues>
Object.keys(normalized) as Array<keyof NormalizedChannelHealthValues>
).filter((key) => normalized[key] !== baselineRef.current[key])
if (updates.length === 0) {
@@ -318,86 +279,52 @@ export function RoutingReliabilitySection({
return
}
for (const key of updates) {
const value = normalized[key]
await updateOption.mutateAsync({
key,
value,
})
try {
await updateOption.mutateAsync(
Object.fromEntries(updates.map((key) => [key, String(normalized[key])]))
)
baselineRef.current = normalized
} catch (error) {
handleServerError(error)
}
baselineRef.current = normalized
}
return (
<SettingsSection title={t('Routing Reliability')}>
<SettingsSection title={t('Channel health')}>
<p className='text-muted-foreground text-sm'>
{t('Source: global settings. Changes take effect after saving.')}
</p>
<Form {...form}>
<SettingsForm onSubmit={form.handleSubmit(onSubmit)}>
<SettingsPageFormActions
onSave={form.handleSubmit(onSubmit)}
isSaving={updateOption.isPending}
isSaving={form.formState.isSubmitting}
/>
<div className='flex min-w-0 flex-col gap-4'>
<div className='flex flex-col gap-1'>
<h4 className='text-sm font-medium'>{t('Request retry')}</h4>
</div>
<div className='grid min-w-0 gap-6 xl:grid-cols-[minmax(12rem,24rem)_minmax(0,1fr)]'>
<FormField
control={form.control}
name='RetryTimes'
render={({ field }) => (
<FormItem>
<FormLabel>{t('Retry Times')}</FormLabel>
<FormControl>
<Input
type='number'
min='0'
max='10'
{...safeNumberFieldProps(field)}
/>
</FormControl>
<FormDescription>
{t('Number of times to retry failed requests (0-10)')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='AutomaticRetryStatusCodes'
render={({ field }) => (
<FormItem>
<FormLabel>{t('Auto-retry status codes')}</FormLabel>
<FormControl>
<Input
placeholder={t('e.g. 401, 403, 429, 500-599')}
value={field.value}
onChange={(event) => field.onChange(event.target.value)}
/>
</FormControl>
<FormDescription>
{t(
'Accepts comma-separated status codes and inclusive ranges.'
)}{' '}
{autoRetryParsed.ok &&
autoRetryParsed.normalized &&
autoRetryParsed.normalized !== field.value.trim() && (
<span className='text-muted-foreground'>
{t('Normalized:')} {autoRetryParsed.normalized}
</span>
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
<Separator />
<Alert>
<AlertDescription>
<p>
{form.watch('AutomaticDisableChannelEnabled')
? t(
'Channels must also enable Auto Ban before automatic disabling can take effect.'
)
: t(
'With these settings, automatic disabling is off for all channels.'
)}
</p>
<Link to='/channels'>{t('Channels')}</Link>
</AlertDescription>
</Alert>
{form.watch('AutomaticEnableChannelEnabled') &&
!form.watch('monitor_setting.auto_test_channel_enabled') && (
<Alert>
<AlertDescription>
{t(
'Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.'
)}
</AlertDescription>
</Alert>
)}
<div className='flex min-w-0 flex-col gap-4'>
<div className='flex flex-col gap-1'>
@@ -415,7 +342,7 @@ export function RoutingReliabilitySection({
<FormLabel>{t('Scheduled channel tests')}</FormLabel>
<FormDescription>
{t(
'Automatically probe all channels in the background'
'Run background checks using the selected test mode'
)}
</FormDescription>
</SettingsSwitchContent>
@@ -501,7 +428,7 @@ export function RoutingReliabilitySection({
? t(
'How frequently the system checks auto-disabled channels for recovery'
)
: t('How frequently the system tests all channels')}
: t('Time between scheduled channel checks')}
</FormDescription>
<FormMessage />
</FormItem>
@@ -542,7 +469,7 @@ export function RoutingReliabilitySection({
<FormLabel>{t('Re-enable on success')}</FormLabel>
<FormDescription>
{t(
'Bring channels back online after successful checks'
'Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.'
)}
</FormDescription>
</SettingsSwitchContent>
@@ -573,7 +500,9 @@ export function RoutingReliabilitySection({
<SettingsSwitchContent>
<FormLabel>{t('Disable on failure')}</FormLabel>
<FormDescription>
{t('Automatically disable channels when tests fail')}
{t(
'Apply disable rules to upstream request errors and scheduled or bulk health checks'
)}
</FormDescription>
</SettingsSwitchContent>
<FormControl>
@@ -591,7 +520,9 @@ export function RoutingReliabilitySection({
name='ChannelDisableThreshold'
render={({ field }) => (
<FormItem>
<FormLabel>{t('Disable threshold (seconds)')}</FormLabel>
<FormLabel>
{t('Health check timeout threshold (seconds)')}
</FormLabel>
<FormControl>
<Input
type='number'
@@ -603,7 +534,7 @@ export function RoutingReliabilitySection({
</FormControl>
<FormDescription>
{t(
'Automatically disable channels exceeding this response time'
'Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.'
)}
</FormDescription>
<FormMessage />
@@ -0,0 +1,54 @@
import { useTranslation } from 'react-i18next'
import type { PolicyEvent } from './api'
import { policyLabel } from './policy-label'
export function PolicyDecisionRecord(props: {
events: PolicyEvent[] | null
channelNames?: Record<number, string>
}) {
const { t } = useTranslation()
return (
<ol aria-label={t('Request decision flow')} className='space-y-0 text-sm'>
{(props.events ?? []).map((event, index) => (
<li
key={`${event.attempt}:${event.channel_id ?? 0}:${event.decision.action}:${event.decision.reason}:${event.rule ?? ''}`}
className='border-border relative ml-3 min-w-0 border-l pb-5 pl-6 last:border-transparent last:pb-1'
>
<span
aria-hidden='true'
className='border-border bg-background absolute -left-3 flex size-6 items-center justify-center rounded-full border text-xs'
>
{index + 1}
</span>
<p
className={
event.decision.action === 'stop'
? 'font-medium text-amber-700 dark:text-amber-400'
: 'font-medium'
}
>
{policyLabel(t, event.decision.reason)}
{event.channel_id
? ` · ${props.channelNames?.[event.channel_id] ?? `#${event.channel_id}`}`
: ''}
{event.status && event.decision.action === 'failure'
? ` · HTTP ${event.status}`
: ''}
</p>
<p className='text-muted-foreground text-xs break-words'>
{event.attempt > 0 ? `${t('Attempt')} ${event.attempt} · ` : ''}
{event.elapsed_ms} ms
{event.group ? ` · ${event.group}` : ''}
{event.rule ? ` · ${event.rule}` : ''}
{event.status ? ` · HTTP ${event.status}` : ''}
</p>
<p className='text-muted-foreground text-xs'>
{t('Source')}: {policyLabel(t, event.decision.source)}
{event.health ? ` · ${policyLabel(t, event.health)}` : ''}
</p>
</li>
))}
</ol>
)
}
@@ -0,0 +1,72 @@
/*
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 { ChannelAffinitySettings } from '../general/channel-affinity/types'
import type { SecuritySettings } from '../types'
export type RetrySettings = {
RetryTimes: number
AutomaticRetryStatusCodes: string
}
export type HealthSettings = {
ChannelDisableThreshold: string
AutomaticDisableChannelEnabled: boolean
AutomaticEnableChannelEnabled: boolean
AutomaticDisableKeywords: string
AutomaticDisableStatusCodes: string
'monitor_setting.auto_test_channel_enabled': boolean
'monitor_setting.auto_test_channel_minutes': number
'monitor_setting.channel_test_concurrency': number
'monitor_setting.channel_test_mode':
| 'scheduled_all'
| 'auto_ban_only'
| 'passive_recovery'
}
export type FilteringSettings = Pick<
SecuritySettings,
'CheckSensitiveEnabled' | 'CheckSensitiveOnPromptEnabled' | 'SensitiveWords'
>
export type RequestPolicySettings = RetrySettings &
HealthSettings &
FilteringSettings &
Pick<ChannelAffinitySettings, keyof ChannelAffinitySettings>
export const defaultRequestPolicySettings: RequestPolicySettings = {
RetryTimes: 0,
AutomaticRetryStatusCodes:
'100-199,300-399,401-407,409-499,500-503,505-523,525-599',
ChannelDisableThreshold: '',
AutomaticDisableChannelEnabled: false,
AutomaticEnableChannelEnabled: false,
AutomaticDisableKeywords: '',
AutomaticDisableStatusCodes: '401',
'monitor_setting.auto_test_channel_enabled': false,
'monitor_setting.auto_test_channel_minutes': 10,
'monitor_setting.channel_test_concurrency': 1,
'monitor_setting.channel_test_mode': 'scheduled_all',
'channel_affinity_setting.enabled': false,
'channel_affinity_setting.session_mode': '',
'channel_affinity_setting.switch_on_success': true,
'channel_affinity_setting.keep_on_channel_disabled': false,
'channel_affinity_setting.max_entries': 100000,
'channel_affinity_setting.default_ttl_seconds': 3600,
'channel_affinity_setting.rules': '[]',
CheckSensitiveEnabled: false,
CheckSensitiveOnPromptEnabled: false,
SensitiveWords: '',
}
@@ -0,0 +1,36 @@
/*
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 { SettingsPage } from '../components/settings-page'
import { defaultRequestPolicySettings } from './defaults'
import {
getPolicySectionContent,
getPolicySectionMeta,
} from './section-registry'
export function RequestPolicies() {
return (
<SettingsPage
routePath='/_authenticated/system-settings/request-policies/$section'
defaultSettings={defaultRequestPolicySettings}
defaultSection='routing'
getSectionContent={getPolicySectionContent}
getSectionMeta={getPolicySectionMeta}
/>
)
}
@@ -0,0 +1,79 @@
import type { TFunction } from 'i18next'
// Labels for the decision events recorded by the backend request policy state
// (reasons, sources and health), the session behaviors, and the auto-disable
// sources reported by the channel operations summary.
export function policyLabel(t: TFunction, value: string): string {
switch (value) {
case 'upstream_failure':
return t('Upstream request failed')
case 'request_failed':
return t('Request failed')
case 'task_failed':
return t('Task failed')
case 'strict_session':
return t('Session behavior prevents switching channels')
case 'attempt_budget_exhausted':
return t('Total attempt budget exhausted')
case 'channel_error':
return t('Channel error')
case 'unrecognized_status':
return t('Unrecognized status code')
case 'task_accepted':
return t('The task was accepted; submission cannot be replayed')
case 'pinned_channel':
return t('Fixed channel constraint')
case 'local_rejection':
return t('Request rejected locally')
case 'non_retryable_error':
case 'system_retry_exclusion':
return t('System retry exclusion')
case 'status_not_retryable':
return t('Status is outside the retry rules')
case 'retry_status_matched':
return t('Status matches the retry rules')
case 'session_rule_matched':
return t('Session rule matched')
case 'channel_selected':
return t('Channel selected')
case 'request_completed':
return t('Request completed')
case 'stream_not_successful':
return t('Stream did not complete successfully')
case 'channel':
return t('Channel')
case 'global':
return t('Global default')
case 'global_and_channel':
return t('Global and channel settings')
case 'session_rule':
return t('Session rule')
case 'system':
return t('System constraint')
case 'routing':
return t('Channel selection')
case 'upstream':
return t('Upstream response')
case 'transport':
return t('Upstream connection')
case 'local':
return t('Local check')
case 'channel_constraint':
return t('Fixed channel constraint')
case 'unchanged':
return t('Unchanged')
case 'channel_disable_requested':
return t('Channel disable requested')
case 'key_disable_requested':
return t('Current key disable requested')
case 'off':
case '':
return t('Do not keep sessions')
case 'prefer':
return t('Prefer the original channel, allow switching')
case 'strict':
return t('Require the original channel')
default:
return value
}
}
@@ -0,0 +1,55 @@
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { getChannelOps } from '@/features/channels/api'
import { ROLE } from '@/lib/roles'
import { requireServerSuccess } from '@/lib/server-error-message'
import { useAuthStore } from '@/stores/auth-store'
import { policyLabel } from './policy-label'
export function RelatedPolicyLink(props: { section: 'routing' | 'health' }) {
const { t } = useTranslation()
const isRoot = useAuthStore(
(state) => state.auth.user?.role === ROLE.SUPER_ADMIN
)
if (!isRoot) return null
return (
<Link
className='text-primary ml-1 underline underline-offset-4'
to='/system-settings/request-policies/$section'
params={{ section: props.section }}
>
{t('Request policies')}
</Link>
)
}
export function ChannelHealthSource(props: { autoBan: boolean }) {
const { t } = useTranslation()
const query = useQuery({
queryKey: ['channel-ops', { autoBan: props.autoBan }],
queryFn: async () =>
requireServerSuccess(await getChannelOps(props.autoBan)),
retry: false,
staleTime: 60000,
meta: { errorToast: false },
})
const policy = query.data?.data?.request_policy
return (
<>
{policy ? (
<span>
{policy.automatic_disable
? t('Auto-disable enabled')
: t('Auto-disable disabled')}{' '}
· {t('Source')}: {policyLabel(t, policy.source)}
</span>
) : (
t('Requires global auto-disable and this channel option.')
)}
<RelatedPolicyLink section='health' />
</>
)
}
@@ -22,6 +22,7 @@ import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import * as z from 'zod'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
Form,
FormControl,
@@ -33,15 +34,18 @@ import {
} from '@/components/ui/form'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { handleServerError } from '@/lib/handle-server-error'
import {
SettingsForm,
SettingsControlGroup,
SettingsControlChildren,
SettingsSwitchContent,
SettingsSwitchItem,
} from '../components/settings-form-layout'
import { SettingsPageFormActions } from '../components/settings-page-context'
import { SettingsSection } from '../components/settings-section'
import { useUpdateOption } from '../hooks/use-update-option'
import { useSavePolicy } from './use-save-policy'
const sensitiveSchema = z.object({
CheckSensitiveEnabled: z.boolean(),
@@ -51,15 +55,15 @@ const sensitiveSchema = z.object({
type SensitiveFormValues = z.infer<typeof sensitiveSchema>
type SensitiveWordsSectionProps = {
type RequestChecksSectionProps = {
defaultValues: SensitiveFormValues
}
export function SensitiveWordsSection({
export function RequestChecksSection({
defaultValues,
}: SensitiveWordsSectionProps) {
}: RequestChecksSectionProps) {
const { t } = useTranslation()
const updateOption = useUpdateOption()
const updateOption = useSavePolicy()
const form = useForm<SensitiveFormValues>({
resolver: zodResolver(sensitiveSchema),
defaultValues,
@@ -75,21 +79,51 @@ export function SensitiveWordsSection({
value !== defaultValues[key as keyof SensitiveFormValues]
)
for (const [key, value] of updates) {
await updateOption.mutateAsync({ key, value: value ?? '' })
try {
if (updates.length > 0) {
await updateOption.mutateAsync(
Object.fromEntries(
updates.map(([key, value]) => [key, String(value ?? '')])
)
)
}
} catch (error) {
handleServerError(error)
}
}
return (
<SettingsSection title={t('Sensitive Words')}>
<SettingsSection title={t('Request checks')}>
<p className='text-muted-foreground text-sm'>
{t('Source: global settings. Changes take effect after saving.')}
</p>
<h3 className='text-sm font-medium'>{t('Request text filtering')}</h3>
<p className='text-muted-foreground text-sm'>
{t(
'Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.'
)}
</p>
<Form {...form}>
<SettingsForm onSubmit={form.handleSubmit(onSubmit)}>
<SettingsPageFormActions
onSave={form.handleSubmit(onSubmit)}
isSaving={updateOption.isPending}
isSaving={form.formState.isSubmitting}
saveLabel='Save sensitive words'
/>
<div className='space-y-4'>
<Alert>
<AlertDescription>
{form.watch('CheckSensitiveEnabled') &&
form.watch('CheckSensitiveOnPromptEnabled') &&
form.watch('SensitiveWords')?.trim()
? t(
'Prompt text filtering is active with the current form values.'
)
: t(
'Prompt text filtering needs both switches enabled and a non-empty keyword list.'
)}
</AlertDescription>
</Alert>
<SettingsControlGroup>
<FormField
control={form.control}
name='CheckSensitiveEnabled'
@@ -113,29 +147,32 @@ export function SensitiveWordsSection({
)}
/>
<FormField
control={form.control}
name='CheckSensitiveOnPromptEnabled'
render={({ field }) => (
<SettingsSwitchItem>
<SettingsSwitchContent>
<FormLabel>{t('Inspect user prompts')}</FormLabel>
<FormDescription>
{t(
'When enabled, prompts are scanned before reaching upstream models.'
)}
</FormDescription>
</SettingsSwitchContent>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</SettingsSwitchItem>
)}
/>
</div>
<SettingsControlChildren>
<FormField
control={form.control}
name='CheckSensitiveOnPromptEnabled'
render={({ field }) => (
<SettingsSwitchItem>
<SettingsSwitchContent>
<FormLabel>{t('Inspect user prompts')}</FormLabel>
<FormDescription>
{t(
'When enabled, prompts are scanned before reaching upstream models.'
)}
</FormDescription>
</SettingsSwitchContent>
<FormControl>
<Switch
disabled={!form.watch('CheckSensitiveEnabled')}
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</SettingsSwitchItem>
)}
/>
</SettingsControlChildren>
</SettingsControlGroup>
<FormField
control={form.control}
@@ -0,0 +1,86 @@
/*
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 { useFormContext } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import {
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { SettingsCard } from '../components/settings-card'
import { safeNumberFieldProps } from '../utils/numeric-field'
import type { RoutingPolicyFormValues } from './routing-form'
export function RetrySection() {
const { t } = useTranslation()
const form = useFormContext<RoutingPolicyFormValues>()
return (
<SettingsCard title={t('Retry budget')} className='shadow-none'>
<div className='space-y-4'>
<FormField
control={form.control}
name='RetryTimes'
render={({ field }) => (
<FormItem>
<FormLabel>{t('Maximum retries')}</FormLabel>
<FormControl>
<Input
type='number'
min={0}
max={99}
step={1}
{...safeNumberFieldProps(field)}
/>
</FormControl>
<FormDescription>
{t('Excludes the first attempt. Counted per group.')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='AutomaticRetryStatusCodes'
render={({ field }) => (
<FormItem>
<FormLabel>{t('Auto-retry status codes')}</FormLabel>
<FormControl>
<Input
{...field}
placeholder={t('e.g. 401, 403, 429, 500-599')}
/>
</FormControl>
<FormDescription>
{t('2xx, 504 and 524 are always excluded.')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
</SettingsCard>
)
}
@@ -0,0 +1,82 @@
import type { TFunction } from 'i18next'
import { z } from 'zod'
import { parseHttpStatusCodeRules } from '@/lib/http-status-code-rules'
export function createRoutingPolicySchema(t: TFunction) {
return z.object({
RetryTimes: z.number().int().min(0).max(99),
AutomaticRetryStatusCodes: z
.string()
.refine(
(value) => parseHttpStatusCodeRules(value).ok,
t('Invalid status code rules')
),
channel_affinity_setting: z.object({
enabled: z.boolean(),
session_mode: z.enum(['', 'off', 'prefer', 'strict']),
switch_on_success: z.boolean(),
keep_on_channel_disabled: z.boolean(),
max_entries: z.number().int().min(0),
default_ttl_seconds: z.number().int().min(0),
rules: z.string().superRefine((value, context) => {
try {
const rules: unknown = JSON.parse(value)
if (!Array.isArray(rules)) {
context.addIssue({
code: 'custom',
message: t('Rules JSON must be an array'),
})
}
} catch {
context.addIssue({
code: 'custom',
message: t('Invalid rules JSON format'),
})
}
}),
}),
})
}
export type RoutingPolicyFormValues = z.infer<
ReturnType<typeof createRoutingPolicySchema>
>
export function routingPolicyFormValues(
options: Record<string, string>
): RoutingPolicyFormValues {
return {
RetryTimes: Number(options.RetryTimes),
AutomaticRetryStatusCodes: options.AutomaticRetryStatusCodes,
channel_affinity_setting: {
enabled: options['channel_affinity_setting.enabled'] === 'true',
session_mode: (options['channel_affinity_setting.session_mode'] ||
'') as RoutingPolicyFormValues['channel_affinity_setting']['session_mode'],
switch_on_success:
options['channel_affinity_setting.switch_on_success'] === 'true',
keep_on_channel_disabled:
options['channel_affinity_setting.keep_on_channel_disabled'] === 'true',
max_entries: Number(options['channel_affinity_setting.max_entries']),
default_ttl_seconds: Number(
options['channel_affinity_setting.default_ttl_seconds']
),
rules: options['channel_affinity_setting.rules'] || '[]',
},
}
}
export function routingPolicyOptions(
values: RoutingPolicyFormValues
): Record<string, string> {
return {
RetryTimes: String(values.RetryTimes),
AutomaticRetryStatusCodes: values.AutomaticRetryStatusCodes,
...Object.fromEntries(
Object.entries(values.channel_affinity_setting).map(([key, value]) => [
`channel_affinity_setting.${key}`,
String(value),
])
),
}
}
@@ -0,0 +1,329 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo } from 'react'
import { useForm, useFormContext, useWatch } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { ErrorState } from '@/components/error-state'
import { LoadingState } from '@/components/loading-state'
import { Accordion } from '@/components/ui/accordion'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { handleServerError } from '@/lib/handle-server-error'
import { parseHttpStatusCodeRules } from '@/lib/http-status-code-rules'
import { SettingsAccordion } from '../components/settings-accordion'
import { SettingsCard } from '../components/settings-card'
import {
SettingsControlChildren,
SettingsSwitchField,
} from '../components/settings-form-layout'
import { SettingsPageFormActions } from '../components/settings-page-context'
import { ChannelAffinitySection } from '../general/channel-affinity'
import { safeNumberFieldProps } from '../utils/numeric-field'
import { getPolicyConfig, type PolicyConfig } from './api'
import { policyLabel } from './policy-label'
import { RetrySection } from './retry-section'
import {
createRoutingPolicySchema,
routingPolicyFormValues,
routingPolicyOptions,
type RoutingPolicyFormValues,
} from './routing-form'
import { useSavePolicy } from './use-save-policy'
export function RoutingPolicySection() {
const { t } = useTranslation()
const query = useQuery({
queryKey: ['request-policy'],
queryFn: getPolicyConfig,
staleTime: Infinity,
})
if (query.isPending) return <LoadingState />
if (query.isError) {
return (
<ErrorState
title={t('Failed to load settings')}
onRetry={() => void query.refetch()}
/>
)
}
return <RoutingPolicyEditor config={query.data} />
}
function RoutingPolicyEditor(props: { config: PolicyConfig }) {
const { t } = useTranslation()
const mutation = useSavePolicy()
const schema = useMemo(() => createRoutingPolicySchema(t), [t])
const defaults = useMemo(
() => routingPolicyFormValues(props.config.options),
[props.config.options]
)
const form = useForm<RoutingPolicyFormValues>({
resolver: zodResolver(schema),
defaultValues: defaults,
})
// Subscribe so refreshes can preserve every dirty field, including rule JSON.
const { dirtyFields } = form.formState
useEffect(() => {
form.reset(defaults, { keepDirtyValues: true })
}, [defaults, form])
const values = useWatch({
control: form.control,
compute: (current) => current,
})
const save = async (submitted: RoutingPolicyFormValues) => {
const next = routingPolicyOptions(submitted)
next.AutomaticRetryStatusCodes = parseHttpStatusCodeRules(
next.AutomaticRetryStatusCodes
).normalized
const delta = Object.fromEntries(
Object.entries(next).filter(([key, value]) => {
const previous = props.config.options[key]
if (key === 'channel_affinity_setting.rules') {
return (
JSON.stringify(JSON.parse(value)) !==
JSON.stringify(JSON.parse(previous || '[]'))
)
}
if (key === 'AutomaticRetryStatusCodes') {
return value !== parseHttpStatusCodeRules(previous).normalized
}
return value !== previous
})
)
if (Object.keys(delta).length === 0) {
toast.info(t('No changes to save'))
return
}
try {
const data = await mutation.mutateAsync(delta)
form.reset(routingPolicyFormValues(data.options))
} catch (error) {
handleServerError(error)
}
}
const submit = form.handleSubmit((submitted) => save(submitted))
// The session rules stay in the main column, between the defaults they
// inherit and the retry budget.
return (
<Form {...form}>
<div className='min-w-0 space-y-5'>
<SettingsPageFormActions
onSave={submit}
isSaving={mutation.isPending}
/>
<div className='min-w-0 space-y-4'>
<AffinitySettings />
<FormField
control={form.control}
name='channel_affinity_setting.rules'
render={({ field }) => (
<FormItem>
<ChannelAffinitySection
rulesJson={field.value}
onRulesChange={field.onChange}
enabled={values.channel_affinity_setting.enabled}
globalSessionMode={
values.channel_affinity_setting.session_mode
}
/>
<FormMessage />
</FormItem>
)}
/>
<RetrySection />
{mutation.isError ? (
<p role='alert' className='text-destructive text-sm'>
{mutation.error.message}
</p>
) : null}
{Object.keys(dirtyFields).length > 0 &&
!schema.safeParse(values).success ? (
<Alert>
<AlertDescription>
{t('Correct the invalid settings before saving.')}
</AlertDescription>
</Alert>
) : null}
</div>
</div>
</Form>
)
}
function AffinitySettings() {
const { t } = useTranslation()
const form = useFormContext<RoutingPolicyFormValues>()
const enabled = useWatch({
control: form.control,
name: 'channel_affinity_setting.enabled',
})
return (
<SettingsCard
title={t('Session defaults')}
description={t('Rules can inherit or override these defaults.')}
className='shadow-none'
>
<FormField
control={form.control}
name='channel_affinity_setting.enabled'
render={({ field }) => (
<SettingsSwitchField
controlId='channel_affinity_setting.enabled'
checked={field.value}
onCheckedChange={field.onChange}
label={t('Enable session affinity')}
/>
)}
/>
<FormField
control={form.control}
name='channel_affinity_setting.session_mode'
render={({ field }) => (
<FormItem className='mt-4'>
<FormControl>
<RadioGroup
aria-label={t('Session behavior')}
value={field.value || 'prefer'}
onValueChange={field.onChange}
className='gap-2 sm:grid-cols-3'
>
{(['off', 'prefer', 'strict'] as const).map((mode) => (
<div key={mode} className='rounded-lg border'>
<Label
htmlFor={`global-session-${mode}`}
className='hover:bg-muted/30 flex h-full cursor-pointer items-center gap-3 rounded-lg px-4 py-3 font-normal'
>
<RadioGroupItem
id={`global-session-${mode}`}
aria-labelledby={`global-session-${mode}-label`}
aria-describedby={
mode === 'prefer'
? 'global-session-prefer-description'
: undefined
}
value={mode}
onClick={() => field.onChange(mode)}
/>
<span className='flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1'>
<span id={`global-session-${mode}-label`}>
{policyLabel(t, mode)}
</span>
{mode === 'prefer' ? (
<span
id='global-session-prefer-description'
className='text-muted-foreground text-xs font-normal'
>
{t('Reduces cache hit rate')}
</span>
) : null}
</span>
</Label>
</div>
))}
</RadioGroup>
</FormControl>
<SettingsControlChildren
role='group'
aria-label={t('Channel switching options')}
className='mt-3'
>
<FormField
control={form.control}
name='channel_affinity_setting.switch_on_success'
render={({ field: switchField }) => (
<SettingsSwitchField
controlId='channel_affinity_setting.switch_on_success'
disabled={!enabled}
checked={switchField.value}
onCheckedChange={switchField.onChange}
label={t(
'Update the session binding after a successful switch'
)}
description={t('Later requests follow the new channel.')}
/>
)}
/>
</SettingsControlChildren>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='channel_affinity_setting.keep_on_channel_disabled'
render={({ field }) => (
<SettingsSwitchField
controlId='channel_affinity_setting.keep_on_channel_disabled'
className='mt-4'
disabled={!enabled}
checked={field.value}
onCheckedChange={field.onChange}
label={t(
'Keep the session binding when the channel is unavailable'
)}
description={t('Otherwise the binding is removed.')}
/>
)}
/>
<Accordion className='mt-4'>
<SettingsAccordion
value='session-advanced'
title={t('Affinity cache settings')}
keepMounted
>
<div className='space-y-4'>
<div className='grid gap-4 sm:grid-cols-2'>
{(
[
{
name: 'channel_affinity_setting.max_entries',
label: t('Maximum cached sessions'),
},
{
name: 'channel_affinity_setting.default_ttl_seconds',
label: t('Default session lifetime (seconds)'),
},
] as const
).map((item) => (
<FormField
key={item.name}
control={form.control}
name={item.name}
render={({ field }) => (
<FormItem>
<FormLabel>{item.label}</FormLabel>
<FormControl>
<Input
type='number'
min={0}
step={1}
{...safeNumberFieldProps(field)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
))}
</div>
</div>
</SettingsAccordion>
</Accordion>
</SettingsCard>
)
}
@@ -0,0 +1,63 @@
/*
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 { createSectionRegistry } from '../utils/section-registry'
import { ChannelHealthSection } from './channel-health-section'
import type { RequestPolicySettings } from './defaults'
import { RequestChecksSection } from './request-checks-section'
import { RoutingPolicySection } from './routing-section'
const POLICY_SECTIONS = [
{
id: 'filtering',
titleKey: 'Request checks',
build: (settings: RequestPolicySettings) => (
<RequestChecksSection
defaultValues={{
CheckSensitiveEnabled: settings.CheckSensitiveEnabled,
CheckSensitiveOnPromptEnabled: settings.CheckSensitiveOnPromptEnabled,
SensitiveWords: settings.SensitiveWords,
}}
/>
),
},
{
id: 'routing',
titleKey: 'Sessions and retries',
build: () => <RoutingPolicySection />,
},
{
id: 'health',
titleKey: 'Channel health',
build: (settings: RequestPolicySettings) => (
<ChannelHealthSection defaultValues={settings} />
),
},
] as const
export type PolicySectionId = (typeof POLICY_SECTIONS)[number]['id']
const registry = createSectionRegistry<PolicySectionId, RequestPolicySettings>({
sections: POLICY_SECTIONS,
defaultSection: 'routing',
basePath: '/system-settings/request-policies',
urlStyle: 'path',
})
export const POLICY_SECTION_IDS = registry.sectionIds
export const getPolicySectionNavItems = registry.getSectionNavItems
export const getPolicySectionContent = registry.getSectionContent
export const getPolicySectionMeta = registry.getSectionMeta
@@ -0,0 +1,23 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { handleServerError } from '@/lib/handle-server-error'
import { savePolicyConfig } from './api'
export function useSavePolicy() {
const client = useQueryClient()
const { t } = useTranslation()
return useMutation({
mutationFn: savePolicyConfig,
onSuccess: (data) => {
client.setQueryData(['request-policy'], data)
void client.invalidateQueries({ queryKey: ['system-options'] })
void client.invalidateQueries({ queryKey: ['channel-ops'] })
toast.success(t('Saved successfully'))
},
onError: (error) => handleServerError(error),
meta: { errorToast: false },
})
}
@@ -17,7 +17,6 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { RateLimitSection } from '../request-limits/rate-limit-section'
import { SensitiveWordsSection } from '../request-limits/sensitive-words-section'
import { SSRFSection } from '../request-limits/ssrf-section'
import { TokenLimitSection } from '../request-limits/token-limit-section'
import type { SecuritySettings } from '../types'
@@ -41,19 +40,7 @@ const SECURITY_SECTIONS = [
/>
),
},
{
id: 'sensitive-words',
titleKey: 'Sensitive Words',
build: (settings: SecuritySettings) => (
<SensitiveWordsSection
defaultValues={{
CheckSensitiveEnabled: settings.CheckSensitiveEnabled,
CheckSensitiveOnPromptEnabled: settings.CheckSensitiveOnPromptEnabled,
SensitiveWords: settings.SensitiveWords,
}}
/>
),
},
{
id: 'ssrf',
titleKey: 'SSRF Protection',
-20
View File
@@ -257,26 +257,6 @@ export type ModelSettings = {
MaxTokenAutoGroups: number
DefaultUseAutoGroup: boolean
'group_ratio_setting.group_special_usable_group': string
RetryTimes: number
ChannelDisableThreshold: string
AutomaticDisableChannelEnabled: boolean
AutomaticEnableChannelEnabled: boolean
AutomaticDisableKeywords: string
AutomaticDisableStatusCodes: string
AutomaticRetryStatusCodes: string
'monitor_setting.auto_test_channel_enabled': boolean
'monitor_setting.auto_test_channel_minutes': number
'monitor_setting.channel_test_concurrency': number
'monitor_setting.channel_test_mode':
| 'scheduled_all'
| 'auto_ban_only'
| 'passive_recovery'
'channel_affinity_setting.enabled': boolean
'channel_affinity_setting.switch_on_success': boolean
'channel_affinity_setting.keep_on_channel_disabled': boolean
'channel_affinity_setting.max_entries': number
'channel_affinity_setting.default_ttl_seconds': number
'channel_affinity_setting.rules': string
'model_deployment.ionet.api_key': string
'model_deployment.ionet.enabled': boolean
}
@@ -60,6 +60,7 @@ import { DynamicPricingBreakdown } from '@/features/pricing/components/dynamic-p
import { usePricingData } from '@/features/pricing/hooks/use-pricing-data'
import { BILLING_PRICING_VARS } from '@/features/pricing/lib/billing-expr'
import { pluginUsageSchema } from '@/features/pricing/lib/plugin-pricing'
import { PolicyDecisionRecord } from '@/features/system-settings/request-policies/decision-record'
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
import { formatBillingCurrencyFromUSD } from '@/lib/currency'
import { formatLogQuota, formatTokens, formatUseTime } from '@/lib/format'
@@ -788,6 +789,14 @@ export function DetailsDialog(props: DetailsDialogProps) {
)}
{/* Quota saturation marker (admin only) */}
{props.isAdmin && adminInfo?.request_policy?.length ? (
<DetailSection
label={t('Request policy decisions')}
icon={<Route className='size-4' />}
>
<PolicyDecisionRecord events={adminInfo.request_policy} />
</DetailSection>
) : null}
{props.isAdmin && other?.admin_info?.quota_saturation && (
<DetailSection
icon={<AlertTriangle className='size-3.5' aria-hidden='true' />}
+2
View File
@@ -1,3 +1,4 @@
import type { PolicyEvent } from '@/features/system-settings/request-policies/api'
/*
Copyright (C) 2023-2026 QuantumNous
@@ -115,6 +116,7 @@ export interface ToolSurchargeItem {
export interface LogOtherData {
admin_info?: {
request_policy?: PolicyEvent[]
is_multi_key?: boolean
multi_key_index?: number
use_channel?: number[]
+92 -3
View File
@@ -53,6 +53,7 @@
"{{count}} FAQ entries will be removed from the list.": "{{count}} FAQ entries will be removed from the list.",
"{{count}} hours ago": "{{count}} hours ago",
"{{count}} incidents": "{{count}} incidents",
"2xx, 504 and 524 are always excluded.": "2xx, 504 and 524 are always excluded.",
"{{count}} incidents in the last 24 hours": "{{count}} incidents in the last 24 hours",
"{{count}} incidents in the last 30 days": "{{count}} incidents in the last 30 days",
"{{count}} IP(s)": "{{count}} IP(s)",
@@ -208,6 +209,7 @@
"Action": "Action",
"Action confirmation": "Action Confirmation",
"Actions": "Actions",
"Actions for {{name}}": "Actions for {{name}}",
"Activate / Roll back": "Activate / Roll back",
"active": "active",
"Active": "Active",
@@ -351,6 +353,7 @@
"Advanced text editing": "Advanced text editing",
"Aesthetic style": "Aesthetic style",
"Affected windows:": "Affected windows:",
"Affinity cache settings": "Affinity cache settings",
"After clicking the button, you'll be asked to authorize the bot": "After clicking the button, you'll be asked to authorize the bot",
"After conversion": "After conversion",
"After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.": "After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.",
@@ -390,6 +393,7 @@
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.",
"All Groups": "All Groups",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.",
"All models": "All models",
"All Models": "All Models",
"All models in use are properly configured.": "All models in use are properly configured.",
"All Must Match (AND)": "All Must Match (AND)",
@@ -559,6 +563,7 @@
"Apply {{field}} for {{name}}": "Apply {{field}} for {{name}}",
"Apply All Upstream Updates": "Apply All Upstream Updates",
"Apply changes": "Apply changes",
"Apply disable rules to upstream request errors and scheduled or bulk health checks": "Apply disable rules to upstream request errors and scheduled or bulk health checks",
"Apply Filters": "Apply Filters",
"Apply IP Filter to Resolved Domains": "Apply IP Filter to Resolved Domains",
"Apply Overwrite": "Apply Overwrite",
@@ -609,6 +614,7 @@
"At least one model regex pattern is required": "At least one model regex pattern is required",
"At least one valid key source is required": "At least one valid key source is required",
"Attach": "Attach",
"Attempt": "Attempt",
"Audio": "Audio",
"Audio and Realtime pricing must be converted manually.": "Audio and Realtime pricing must be converted manually.",
"Audio and text-only requests keep their respective pricing.": "Audio and text-only requests keep their respective pricing.",
@@ -670,6 +676,8 @@
"Auto refresh (5s)": "Auto refresh (5s)",
"Auto Sync Upstream Models": "Auto Sync Upstream Models",
"Auto-disable channel": "Auto-disable channel",
"Auto-disable disabled": "Auto-disable disabled",
"Auto-disable enabled": "Auto-disable enabled",
"Auto-disable rules": "Auto-disable rules",
"Auto-disable status codes": "Auto-disable status codes",
"Auto-disable-enabled channels only": "Auto-disable-enabled channels only",
@@ -965,9 +973,11 @@
"Channel copied successfully": "Channel copied successfully",
"Channel created successfully": "Channel created successfully",
"Channel deleted successfully": "Channel deleted successfully",
"Channel disable requested": "Channel disable requested",
"Channel disabled successfully": "Channel disabled successfully",
"Channel enabled successfully": "Channel enabled successfully",
"Channel Extra Settings": "Channel Extra Settings",
"Channel health": "Channel health",
"Channel health checks": "Channel health checks",
"Channel ID": "Channel ID",
"Channel ID is required": "Channel ID is required",
@@ -977,6 +987,9 @@
"Channel Management": "Channel Management",
"Channel models": "Channel models",
"Channel name is required": "Channel name is required",
"Channel selected": "Channel selected",
"Channel selection": "Channel selection",
"Channel switching options": "Channel switching options",
"Channel test completed": "Channel test completed",
"Channel test concurrency": "Channel test concurrency",
"Channel test concurrency must be between 1 and 32": "Channel test concurrency must be between 1 and 32",
@@ -994,6 +1007,7 @@
"Channels {{channels}} · Groups {{groups}}": "Channels {{channels}} · Groups {{groups}}",
"Channels and groups": "Channels and groups",
"Channels deleted successfully": "Channels deleted successfully",
"Channels must also enable Auto Ban before automatic disabling can take effect.": "Channels must also enable Auto Ban before automatic disabling can take effect.",
"Character chat, storytelling, persona": "Character chat, storytelling, persona",
"Charge.": "Charge.",
"Chart Preferences": "Chart Preferences",
@@ -1031,6 +1045,7 @@
"checkout.session.completed": "checkout.session.completed",
"checkout.session.expired": "checkout.session.expired",
"Checks hourly while you are online, including pre-releases.": "Checks hourly while you are online, including pre-releases.",
"Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.": "Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.",
"Chinese": "Chinese",
"Choose a complete upstream protocol plan or edit individual route groups.": "Choose a complete upstream protocol plan or edit individual route groups.",
"Choose a provider or plugin to configure your channel.": "Choose a provider or plugin to configure your channel.",
@@ -1514,7 +1529,6 @@
"Creem product ID from your Creem dashboard.": "Creem product ID from your Creem dashboard.",
"Creem products must be a JSON array": "Creem products must be a JSON array",
"Cross-group": "Cross-group",
"Cross-group retry": "Cross-group retry",
"Cumulative usage": "Cumulative usage",
"Currency": "Currency",
"Currency & Display": "Currency & Display",
@@ -1528,6 +1542,7 @@
"Current email: {{email}}. Enter a new email to change.": "Current email: {{email}}. Enter a new email to change.",
"Current exchange rate: 1 USD = {{rate}} {{currency}}": "Current exchange rate: 1 USD = {{rate}} {{currency}}",
"Current key": "Current key",
"Current key disable requested": "Current key disable requested",
"Current legacy JSON is invalid, cannot append": "Current legacy JSON is invalid, cannot append",
"Current Level Only": "Current Level Only",
"Current load": "Current load",
@@ -1627,6 +1642,7 @@
"Default placeholder": "Default placeholder",
"Default range": "Default range",
"Default Responses API version, if empty, will use the API version above": "Default Responses API version, if empty, will use the API version above",
"Default session lifetime (seconds)": "Default session lifetime (seconds)",
"Default system prompt for this channel": "Default system prompt for this channel",
"Default time granularity": "Default time granularity",
"Default to auto groups": "Default to auto groups",
@@ -1680,10 +1696,12 @@
"Delete plugin version?": "Delete plugin version?",
"Delete Provider": "Delete Provider",
"Delete Request Header": "Delete Request Header",
"Delete Rule": "Delete Rule",
"Delete selected API keys": "Delete selected API keys",
"Delete selected channels": "Delete selected channels",
"Delete selected models": "Delete selected models",
"Delete selected redemption codes": "Delete selected redemption codes",
"Delete session rule “{{name}}”? Save your changes to apply the removal.": "Delete session rule “{{name}}”? Save your changes to apply the removal.",
"Delete stale instance": "Delete stale instance",
"Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.": "Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.",
"Delete stale instances": "Delete stale instances",
@@ -1777,6 +1795,7 @@
"Disabled": "Disabled",
"Disabled all channels with tag: {{tag}}": "Disabled all channels with tag: {{tag}}",
"Disabled channels with tag {{tag}}": "Disabled channels with tag {{tag}}",
"Disabled globally": "Disabled globally",
"Disabled lanes are omitted on save.": "Disabled lanes are omitted on save.",
"Disabled Reason": "Disabled Reason",
"Disabled Time": "Disabled Time",
@@ -1824,6 +1843,7 @@
"Displayed": "Displayed",
"Displayed in": "Displayed in",
"Displays the mobile sidebar.": "Displays the mobile sidebar.",
"Do not keep sessions": "Do not keep sessions",
"Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.": "Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.",
"Do not repeat check-in; only once per day": "Do not repeat check-in; only once per day",
"Do not wait one second between polling async tasks for this channel": "Do not wait one second between polling async tasks for this channel",
@@ -1936,6 +1956,7 @@
"Edit chat preset": "Edit chat preset",
"Edit discount tier": "Edit discount tier",
"Edit FAQ": "Edit FAQ",
"Enable session affinity": "Enable session affinity",
"Edit group": "Edit group",
"Edit group rate limit": "Edit group rate limit",
"Edit JSON object directly. Suitable for simple parameter overrides.": "Edit JSON object directly. Suitable for simple parameter overrides.",
@@ -2112,6 +2133,7 @@
"Enter password (8-20 characters)": "Enter password (8-20 characters)",
"Enter password (8–128 characters)": "Enter password (8–128 characters)",
"Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.": "Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.",
"Excludes the first attempt. Counted per group.": "Excludes the first attempt. Counted per group.",
"Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.": "Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.",
"Enter quota in {{currency}}": "Enter quota in {{currency}}",
"Enter quota in tokens": "Enter quota in tokens",
@@ -2333,6 +2355,7 @@
"Failed to load plugins": "Failed to load plugins",
"Failed to load profile": "Failed to load profile",
"Failed to load redemption codes": "Failed to load redemption codes",
"Failed to load settings": "Failed to load settings",
"Failed to load setup data": "Failed to load setup data",
"Failed to load setup status": "Failed to load setup status",
"Failed to load SGLang status": "Failed to load SGLang status",
@@ -2374,6 +2397,7 @@
"Failed to set tag": "Failed to set tag",
"Failed to setup 2FA": "Failed to setup 2FA",
"Failed to show model in model square": "Failed to show model in model square",
"Fill a CLI template or add a blank rule.": "Fill a CLI template or add a blank rule.",
"Failed to sign out other sessions": "Failed to sign out other sessions",
"Failed to sign out session": "Failed to sign out session",
"Failed to start {{provider}} login": "Failed to start {{provider}} login",
@@ -2517,6 +2541,7 @@
"Fix order": "Fix order",
"Fixed": "Fixed",
"Fixed abilities: {{success}} succeeded, {{fails}} failed": "Channel consistency repaired: {{success}} succeeded, {{fails}} failed",
"Fixed channel constraint": "Fixed channel constraint",
"Fixed fee per request": "Fixed fee per request",
"Fixed price": "Fixed price",
"Fixed price (USD)": "Fixed price (USD)",
@@ -2637,8 +2662,11 @@
"GitHub rate limit reached. Try again later.": "GitHub rate limit reached. Try again later.",
"Give the group a recognizable name and optional description.": "Give the group a recognizable name and optional description.",
"Give this group a recognizable name.": "Give this group a recognizable name.",
"Global and channel settings": "Global and channel settings",
"Global configuration and administrative tools.": "Global configuration and administrative tools.",
"Global Coverage": "Global Coverage",
"Global default": "Global default",
"Global default: {{mode}}": "Global default: {{mode}}",
"Global Model Configuration": "Global Model Configuration",
"Global throughput": "Global throughput",
"Go Back": "Go Back",
@@ -2686,6 +2714,7 @@
"Group name cannot be changed when editing.": "Group name cannot be changed when editing.",
"Group prices cannot be expanded because this expression is not a standard tiered pricing expression.": "Group prices cannot be expanded because this expression is not a standard tiered pricing expression.",
"Group Pricing": "Group Pricing",
"How a session is identified and which channel it keeps.": "How a session is identified and which channel it keeps.",
"Group pricing usage guide": "Group pricing usage guide",
"group ratio": "group ratio",
"Group Ratio": "Group Ratio",
@@ -2720,6 +2749,7 @@
"Header Value (supports string or JSON mapping)": "Header Value (supports string or JSON mapping)",
"header. Anthropic-formatted endpoints accept the": "header. Anthropic-formatted endpoints accept the",
"Health": "Health",
"Health check timeout threshold (seconds)": "Health check timeout threshold (seconds)",
"Healthy": "Healthy",
"Hidden": "Hidden",
"Hidden — verify to reveal": "Hidden — verify to reveal",
@@ -2883,6 +2913,7 @@
"Index URL": "Index URL",
"Information unavailable": "Information unavailable",
"Inherit global Auto order": "Inherit global Auto order",
"Inherit global default": "Inherit global default",
"Inherit vendor icon": "Inherit vendor icon",
"Inherited": "Inherited",
"Inherited from {{vendor}}": "Inherited from {{vendor}}",
@@ -2953,6 +2984,7 @@
"Invalid response": "Invalid response",
"Invalid rules JSON format": "Invalid rules JSON format",
"Invalid status code mapping entries: {{entries}}": "Invalid status code mapping entries: {{entries}}",
"Invalid status code rules": "Invalid status code rules",
"Invalid status code rules: {{tokens}}": "Invalid status code rules: {{tokens}}",
"Invalid vLLM server address": "Invalid vLLM server address",
"Invalidate": "Invalidate",
@@ -2979,6 +3011,7 @@
"IP Whitelist (supports CIDR)": "IP Whitelist (supports CIDR)",
"IP: {{ip}} · Method: {{method}}": "IP: {{ip}} · Method: {{method}}",
"is less than the configured maximum cache size": "is less than the configured maximum cache size",
"Later requests follow the new channel.": "Later requests follow the new channel.",
"is the default price; ": "is the default price; ",
"It seems like the page you're looking for": "It seems like the page you're looking for",
"Items": "Items",
@@ -3018,6 +3051,7 @@
"Keep original value (skip if target exists)": "Keep original value (skip if target exists)",
"Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.": "Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.",
"Keep the platform ready": "Keep the platform ready",
"Keep the session binding when the channel is unavailable": "Keep the session binding when the channel is unavailable",
"Keep this above 1 minute to avoid heavy database load": "Keep this above 1 minute to avoid heavy database load",
"Keep this vendor": "Keep this vendor",
"Keep-alive Ping": "Keep-alive Ping",
@@ -3174,6 +3208,7 @@
"Logo": "Logo",
"Logo URL": "Logo URL",
"Logs": "Logs",
"Maximum retries": "Maximum retries",
"Long passwords are unavailable until the password storage upgrade is complete.": "Long passwords are unavailable until the password storage upgrade is complete.",
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.",
"Low balance": "Low balance",
@@ -3246,6 +3281,7 @@
"Maximum 1000 characters. Supports Markdown and HTML.": "Maximum 1000 characters. Supports Markdown and HTML.",
"Maximum 200 characters": "Maximum 200 characters",
"Maximum 500 characters. Supports Markdown and HTML.": "Maximum 500 characters. Supports Markdown and HTML.",
"Maximum cached sessions": "Maximum cached sessions",
"Maximum check-in quota": "Maximum check-in quota",
"Maximum custom groups per token": "Maximum custom groups per token",
"Maximum input window": "Maximum input window",
@@ -3430,6 +3466,7 @@
"months": "months",
"Moonshot": "Moonshot",
"More": "More",
"More actions": "More actions",
"More Apps": "More Apps",
"more mapping": "more mapping",
"More models ({{count}})": "More models ({{count}})",
@@ -3893,6 +3930,7 @@
"Open in New Tab": "Open in New Tab",
"Open menu": "Open menu",
"Open Query Balance to view the upstream JSON response": "Open Query Balance to view the upstream JSON response",
"Otherwise the binding is removed.": "Otherwise the binding is removed.",
"Open release": "Open release",
"Open source": "Open source",
"Open Source": "Open Source",
@@ -4292,6 +4330,7 @@
"Pre-consumed": "Pre-consumed",
"Pre-Consumed Quota": "Pre-Consumed Quota",
"Pre-release": "Pre-release",
"Prefer the original channel, allow switching": "Prefer the original channel, allow switching",
"Preference saved as {{pref}}, but no active subscription. Requests will be rejected.": "Preference saved as {{pref}}, but no active subscription. Requests will be rejected.",
"Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.": "Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.",
"Preferences": "Preferences",
@@ -4424,6 +4463,8 @@
"Prompt Caching": "Prompt Caching",
"Prompt Details": "Prompt Details",
"Prompt price ($/1M tokens)": "Prompt price ($/1M tokens)",
"Prompt text filtering is active with the current form values.": "Prompt text filtering is active with the current form values.",
"Prompt text filtering needs both switches enabled and a non-empty keyword list.": "Prompt text filtering needs both switches enabled and a non-empty keyword list.",
"Proprietary": "Proprietary",
"Protect login and registration with Cloudflare Turnstile": "Protect login and registration with Cloudflare Turnstile",
"Provide a JSON object where each key maps to an endpoint definition.": "Provide a JSON object where each key maps to an endpoint definition.",
@@ -4587,6 +4628,7 @@
"Redirecting to payment page...": "Redirecting to payment page...",
"Redirecting to sign in in {{seconds}} seconds.": "Redirecting to sign in in {{seconds}} seconds.",
"Redirects to {{model}}": "Redirects to {{model}}",
"Reduces cache hit rate": "Reduces cache hit rate",
"Reduces repeated wording": "Reduces repeated wording",
"Reference Video": "Reference Video",
"Referral link:": "Referral link:",
@@ -4706,9 +4748,12 @@
"Request Body Memory Cache": "Request Body Memory Cache",
"Request body must be a JSON object.": "Request body must be a JSON object.",
"Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.": "Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.",
"Request checks": "Request checks",
"Request completed": "Request completed",
"Request conversion": "Request conversion",
"Request Conversion": "Request Conversion",
"Request Count": "Request Count",
"Request decision flow": "Request decision flow",
"Request error occurred": "Request error occurred",
"Request failed": "Request failed",
"Request flow": "Request flow",
@@ -4724,13 +4769,16 @@
"Request names your users call": "Request names your users call",
"Request overrides, routing behavior, and upstream model automation": "Request overrides, routing behavior, and upstream model automation",
"Request Path": "Request Path",
"Request policies": "Request policies",
"Request processing": "Request processing",
"Request rejected locally": "Request rejected locally",
"Request retry": "Request retry",
"Request rule pricing": "Request rule pricing",
"Request rules apply on top of this amount.": "Request rules apply on top of this amount.",
"Request simulation": "Request simulation",
"Request success rate sampled over the last 24 hours": "Request success rate sampled over the last 24 hours",
"Request success rate; {{incidents}} incident buckets in the last 24 hours": "Request success rate; {{incidents}} incident buckets in the last 24 hours",
"Request text filtering": "Request text filtering",
"Request timed out, please refresh and restart GitHub login": "Request timed out, please refresh and restart GitHub login",
"Request-based": "Request-based",
"Requested items": "Requested items",
@@ -4750,15 +4798,18 @@
"Requests will be forwarded to this worker. Trailing slashes are removed automatically.": "Requests will be forwarded to this worker. Trailing slashes are removed automatically.",
"Requests:": "Requests:",
"Require email verification for new accounts": "Require email verification for new accounts",
"Retry budget": "Retry budget",
"Require job success before follow-up actions": "Require job success before follow-up actions",
"Require login to view models": "Require login to view models",
"Require login to view rankings": "Require login to view rankings",
"Require the original channel": "Require the original channel",
"required": "required",
"Required": "Required",
"Required events:": "Required events:",
"Required provider, authentication, model, and group settings": "Required provider, authentication, model, and group settings",
"Required to expose MjProxy-style image generation to end users.": "Required to expose MjProxy-style image generation to end users.",
"Requires an available channel and access to its group.": "Requires an available channel and access to its group.",
"Requires global auto-disable and this channel option.": "Requires global auto-disable and this channel option.",
"Requires upstream WebSocket support": "Requires upstream WebSocket support",
"Rerank": "Rerank",
"Reroll": "Reroll",
@@ -4816,7 +4867,6 @@
"Response time: {{duration}}": "Response time: {{duration}}",
"Response too large": "Response too large",
"Responses API Version": "Responses API Version",
"Responses WebSocket": "Responses WebSocket",
"Restore default pricing": "Restore default pricing",
"Restore defaults": "Restore defaults",
"Restore global Auto": "Restore global Auto",
@@ -4831,6 +4881,7 @@
"Retry Chain": "Retry Chain",
"Retry Settings": "Retry Settings",
"Retry Suggestion": "Retry Suggestion",
"Rules can inherit or override these defaults.": "Rules can inherit or override these defaults.",
"Retry Times": "Retry Times",
"Return a custom error immediately": "Return a custom error immediately",
"Return Custom Error": "Return Custom Error",
@@ -4904,13 +4955,16 @@
"Rule {{line}} prune_objects is missing conditions": "Rule {{line}} prune_objects is missing conditions",
"Rule {{line}} return_error requires a message field": "Rule {{line}} return_error requires a message field",
"Rule Description (optional)": "Rule Description (optional)",
"Rule editor mode": "Rule editor mode",
"Rule group": "Rule group",
"Rule override": "Rule override",
"rules": "rules",
"Rules": "Rules",
"Rules are checked in order. The first match determines the price.": "Rules are checked in order. The first match determines the price.",
"Rules JSON": "Rules JSON",
"Rules JSON must be an array": "Rules JSON must be an array",
"Rules match the original model value from the client request body.": "Rules match the original model value from the client request body.",
"Run background checks using the selected test mode": "Run background checks using the selected test mode",
"Run dry run": "Run dry run",
"Run GC": "Run GC",
"Run tests for the selected models": "Run tests for the selected models",
@@ -4982,6 +5036,8 @@
"Scheduled channel tests": "Scheduled channel tests",
"Scheduled full test": "Scheduled full test",
"Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.": "Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.",
"Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.": "Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.",
"Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.": "Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.",
"scheduling controls": "scheduling controls",
"Science": "Science",
"Scope": "Scope",
@@ -5095,6 +5151,7 @@
"Select locations": "Select locations",
"Select model": "Select model",
"Select Model": "Select Model",
"Session defaults": "Session defaults",
"Select model {{model}}": "Select model {{model}}",
"Select models": "Select models",
"Select models (empty for allow all)": "Select models (empty for allow all)",
@@ -5105,6 +5162,7 @@
"Select or enter color value": "Select or enter color value",
"Select or enter method identifier": "Select or enter method identifier",
"Select or enter model name": "Select or enter model name",
"Sessions and retries": "Sessions and retries",
"Select or enter payment type": "Select or enter payment type",
"Select or enter payment type key": "Select or enter payment type key",
"Select payment method": "Select payment method",
@@ -5167,8 +5225,14 @@
"Server Token": "Server Token",
"Service account JSON file(s)": "Service account JSON file(s)",
"Session": "Session",
"Session behavior": "Session behavior",
"Session behavior prevents switching channels": "Session behavior prevents switching channels",
"Session expired!": "Session expired!",
"Session expired?": "Session expired?",
"Session rule": "Session rule",
"Session rule matched": "Session rule matched",
"Session rules": "Session rules",
"Session rules table": "Session rules table",
"Session signed out": "Session signed out",
"Sessions & Access": "Sessions & Access",
"Set": "Set",
@@ -5321,6 +5385,7 @@
"Source name": "Source name",
"Source vendors": "Source vendors",
"Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.": "Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.",
"Source: global settings. Changes take effect after saving.": "Source: global settings. Changes take effect after saving.",
"sources": "sources",
"Space-separated OAuth scopes": "Space-separated OAuth scopes",
"Spark model version, e.g., v2.1 (version number in API URL)": "Spark model version, e.g., v2.1 (version number in API URL)",
@@ -5370,6 +5435,8 @@
"Status Code": "Status Code",
"Status Code Mapping": "Status Code Mapping",
"Status code mapping must use valid HTTP status codes": "Status code mapping must use valid HTTP status codes",
"Status is outside the retry rules": "Status is outside the retry rules",
"Status matches the retry rules": "Status matches the retry rules",
"Status Page Slug": "Status Page Slug",
"Status short": "Status",
"Status:": "Status:",
@@ -5391,6 +5458,7 @@
"Stored value is not echoed back for security": "Stored value is not echoed back for security",
"stream": "stream",
"Stream": "Stream",
"Stream did not complete successfully": "Stream did not complete successfully",
"Stream Mode": "Stream Mode",
"Stream Status": "Stream Status",
"Stream tokens incrementally as they are generated": "Stream tokens incrementally as they are generated",
@@ -5432,6 +5500,7 @@
"succeeded": "succeeded",
"Success": "Success",
"Success rate": "Success rate",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.",
"Successfully created {{count}} API Key(s)": "Successfully created {{count}} API Key(s)",
"Successfully created {{count}} redemption codes": "Successfully created {{count}} redemption codes",
"Successfully deleted {{count}} API key(s)": "Successfully deleted {{count}} API key(s)",
@@ -5471,6 +5540,7 @@
"Switch to JSON": "Switch to JSON",
"Switch to Visual": "Switch to Visual",
"Switch to visual editor": "Switch to visual editor",
"Switch to visual mode to add rules or apply templates.": "Switch to visual mode to add rules or apply templates.",
"Switch to visual pricing?": "Switch to visual pricing?",
"Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.": "Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.",
"Sync Endpoint": "Sync Endpoint",
@@ -5500,6 +5570,7 @@
"System Administration": "System Administration",
"System Announcements": "System Announcements",
"System Behavior": "System Behavior",
"System constraint": "System constraint",
"System data statistics": "System data statistics",
"System default": "System default",
"System Info": "System Info",
@@ -5517,6 +5588,7 @@
"System Prompt": "System Prompt",
"System Prompt Concatenation": "System Prompt Concatenation",
"System Prompt Override": "System Prompt Override",
"System retry exclusion": "System retry exclusion",
"System settings": "System settings",
"System Settings": "System Settings",
"System setup wizard": "System setup wizard",
@@ -5551,6 +5623,7 @@
"Task": "Task",
"Task billing": "Task billing",
"Task Details": "Task Details",
"Task failed": "Task failed",
"Task History": "Task History",
"Task ID": "Task ID",
"Task ID:": "Task ID:",
@@ -5659,6 +5732,7 @@
"The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.": "The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.",
"The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.": "The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.",
"The system currently uses: {{domain}}": "The system currently uses: {{domain}}",
"The task was accepted; submission cannot be replayed": "The task was accepted; submission cannot be replayed",
"The Telegram authorization request is invalid or expired.": "The Telegram authorization request is invalid or expired.",
"The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.": "The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.",
"The token group that will have a custom ratio": "The token group that will have a custom ratio",
@@ -5820,6 +5894,7 @@
"Tiered pricing": "Tiered pricing",
"tiers": "tiers",
"Time": "Time",
"Time between scheduled channel checks": "Time between scheduled channel checks",
"Time functions use the timezone written in the expression.": "Time functions use the timezone written in the expression.",
"Time Granularity": "Time Granularity",
"Time range": "Time range",
@@ -5933,6 +6008,7 @@
"Total {{count}} records": "Total {{count}} records",
"Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.": "Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.",
"Total Allocated": "Total Allocated",
"Total attempt budget exhausted": "Total attempt budget exhausted",
"Total check-ins": "Total check-ins",
"Total consumed": "Total consumed",
"Total consumed quota": "Total consumed quota",
@@ -6028,6 +6104,7 @@
"Unbind": "Unbind",
"Unbind failed": "Unbind failed",
"Unbound {{provider}}": "Unbound {{provider}}",
"Unchanged": "Unchanged",
"Underflow": "Underflow",
"Underground": "Underground",
"Understand how user groups, token groups, ratios, and special rules work together.": "Understand how user groups, token groups, ratios, and special rules work together.",
@@ -6083,6 +6160,7 @@
"Update the configuration for this custom OAuth provider.": "Update the configuration for this custom OAuth provider.",
"Update the redemption code by providing necessary info.": "Update the redemption code by providing necessary info.",
"Update the reusable bundle below.": "Update the reusable bundle below.",
"Update the session binding after a successful switch": "Update the session binding after a successful switch",
"Update the user by providing necessary info.": "Update the user by providing necessary info.",
"Update vendor information for {{name}}": "Update vendor information for {{name}}",
"Update your password for account:": "Update your password for account:",
@@ -6148,7 +6226,9 @@
"Upstream prices fetched successfully": "Upstream prices fetched successfully",
"Upstream protocol plan": "Upstream protocol plan",
"Upstream ratios fetched successfully": "Upstream ratios fetched successfully",
"Upstream request failed": "Upstream request failed",
"Upstream Request ID": "Upstream Request ID",
"Upstream response": "Upstream response",
"Upstream Response": "Upstream Response",
"Upstream Response (billing-usage-anthropic-estimated)": "Upstream Response (billing-usage-anthropic-estimated)",
"Upstream Response (billing-usage-anthropic)": "Upstream Response (billing-usage-anthropic)",
@@ -6523,6 +6603,7 @@
"with conflicts": "with conflicts",
"With linked models": "With linked models",
"with the API key from your token settings.": "with the API key from your token settings.",
"With these settings, automatic disabling is off for all channels.": "With these settings, automatic disabling is off for all channels.",
"Without additional conditions, only the type above is used for pruning.": "Without additional conditions, only the type above is used for pruning.",
"Without linked models": "Without linked models",
"Worked example": "Worked example",
@@ -6586,6 +6667,14 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Channel error": "Channel error",
"Unrecognized status code": "Unrecognized status code",
"Correct the invalid settings before saving.": "Correct the invalid settings before saving.",
"Upstream connection": "Upstream connection",
"Local check": "Local check",
"Responses WebSocket": "Responses WebSocket",
"Cross-group retry": "Cross-group retry",
"Request policy decisions": "Request policy decisions"
}
}
+92 -3
View File
@@ -53,6 +53,7 @@
"{{count}} FAQ entries will be removed from the list.": "{{count}} entrées de FAQ seront retirées de la liste.",
"{{count}} hours ago": "il y a {{count}} heures",
"{{count}} incidents": "{{count}} incidents",
"2xx, 504 and 524 are always excluded.": "2xx, 504 et 524 sont toujours exclus.",
"{{count}} incidents in the last 24 hours": "{{count}} incidents au cours des dernières 24 heures",
"{{count}} incidents in the last 30 days": "{{count}} incidents au cours des 30 derniers jours",
"{{count}} IP(s)": "{{count}} IP",
@@ -208,6 +209,7 @@
"Action": "Action",
"Action confirmation": "Confirmation de l'action",
"Actions": "Actions",
"Actions for {{name}}": "Actions pour {{name}}",
"Activate / Roll back": "Activer / Restaurer",
"active": "actif",
"Active": "Actif",
@@ -351,6 +353,7 @@
"Advanced text editing": "Édition de texte avancée",
"Aesthetic style": "Style esthétique",
"Affected windows:": "Fenêtres affectées :",
"Affinity cache settings": "Cache d’affinité",
"After clicking the button, you'll be asked to authorize the bot": "Après avoir cliqué sur le bouton, il vous sera demandé d'autoriser le bot",
"After conversion": "Après conversion",
"After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.": "Après conversion, les règles de réservation et d’arrondi des expressions s’appliquent. Les prix unitaires effectifs sont conservés, mais les montants arrondis peuvent différer.",
@@ -390,6 +393,7 @@
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "Tous les noms de groupes sont gérés ici. Le taux s’applique lorsque les appels sont facturés sous ce groupe ; le taux de recharge s’applique aux utilisateurs appartenant à ce groupe.",
"All Groups": "Tous les groupes",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "Tous les groupes partagent un même ensemble de noms géré dans le tableau des groupes tarifaires, mais un nom joue deux rôles distincts : en tant que groupe d’utilisateurs il décrit l’utilisateur, en tant que groupe de jetons il détermine le routage et la facturation.",
"All models": "Tous les modèles",
"All Models": "Tous les modèles",
"All models in use are properly configured.": "Tous les modèles utilisés sont correctement configurés.",
"All Must Match (AND)": "Toutes doivent correspondre (AND)",
@@ -559,6 +563,7 @@
"Apply {{field}} for {{name}}": "Appliquer {{field}} à {{name}}",
"Apply All Upstream Updates": "Appliquer toutes les mises à jour upstream",
"Apply changes": "Appliquer",
"Apply disable rules to upstream request errors and scheduled or bulk health checks": "Appliquer les règles aux erreurs en amont et aux contrôles périodiques ou groupés",
"Apply Filters": "Appliquer les filtres",
"Apply IP Filter to Resolved Domains": "Appliquer le filtre IP aux domaines résolus",
"Apply Overwrite": "Appliquer l'écrasement",
@@ -609,6 +614,7 @@
"At least one model regex pattern is required": "Au moins un modèle de regex est requis",
"At least one valid key source is required": "Au moins une source de clé valide est requise",
"Attach": "Joindre",
"Attempt": "Tentative",
"Audio": "Audio",
"Audio and Realtime pricing must be converted manually.": "Les tarifs audio et Realtime doivent être convertis manuellement.",
"Audio and text-only requests keep their respective pricing.": "Les requêtes audio et texte seul conservent leurs tarifs respectifs.",
@@ -670,6 +676,8 @@
"Auto refresh (5s)": "Actualiser auto (5 s)",
"Auto Sync Upstream Models": "Synchronisation automatique des modèles en amont",
"Auto-disable channel": "Désactivation auto",
"Auto-disable disabled": "Désactivation automatique inactive",
"Auto-disable enabled": "Désactivation automatique active",
"Auto-disable rules": "Règles de désactivation automatique",
"Auto-disable status codes": "Codes de statut de désactivation auto",
"Auto-disable-enabled channels only": "Canaux avec désactivation automatique uniquement",
@@ -965,9 +973,11 @@
"Channel copied successfully": "Canal copié avec succès",
"Channel created successfully": "Canal créé avec succès",
"Channel deleted successfully": "Canal supprimé avec succès",
"Channel disable requested": "Désactivation du canal demandée",
"Channel disabled successfully": "Canal désactivé avec succès",
"Channel enabled successfully": "Canal activé avec succès",
"Channel Extra Settings": "Paramètres supplémentaires du canal",
"Channel health": "État des canaux",
"Channel health checks": "Contrôles de santé des canaux",
"Channel ID": "ID du Canal",
"Channel ID is required": "L'ID du canal est requis",
@@ -977,6 +987,9 @@
"Channel Management": "Gestion des canaux",
"Channel models": "Modèles de canaux",
"Channel name is required": "Le nom du canal est requis",
"Channel selected": "Canal sélectionné",
"Channel selection": "Sélection du canal",
"Channel switching options": "Options de changement de canal",
"Channel test completed": "Test du canal terminé",
"Channel test concurrency": "Parallélisme des tests de canaux",
"Channel test concurrency must be between 1 and 32": "Le parallélisme des tests de canaux doit être compris entre 1 et 32",
@@ -994,6 +1007,7 @@
"Channels {{channels}} · Groups {{groups}}": "Canaux {{channels}} · Groupes {{groups}}",
"Channels and groups": "Canaux et groupes",
"Channels deleted successfully": "Canaux supprimés avec succès",
"Channels must also enable Auto Ban before automatic disabling can take effect.": "Chaque canal doit aussi activer la désactivation automatique pour que les règles s’appliquent.",
"Character chat, storytelling, persona": "Discussion de personnages, narration, persona",
"Charge.": "Facturer.",
"Chart Preferences": "Préférences des graphiques",
@@ -1031,6 +1045,7 @@
"checkout.session.completed": "checkout.session.completed",
"checkout.session.expired": "checkout.session.expired",
"Checks hourly while you are online, including pre-releases.": "Vérification chaque heure en ligne, versions préliminaires incluses.",
"Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.": "Compare les textes extraits des requêtes prises en charge aux mots-clés, sans tenir compte de la casse. Une correspondance rejette la requête avant son envoi au fournisseur, sans affecter la santé du canal. Images, audio et réponses générées ne sont pas vérifiés.",
"Chinese": "Chinois",
"Choose a complete upstream protocol plan or edit individual route groups.": "Choisissez un plan de protocole amont complet ou modifiez les groupes de routes.",
"Choose a provider or plugin to configure your channel.": "Choisissez un fournisseur ou une extension pour configurer le canal.",
@@ -1514,7 +1529,6 @@
"Creem product ID from your Creem dashboard.": "ID du produit Creem depuis votre tableau de bord Creem.",
"Creem products must be a JSON array": "Les produits Creem doivent être un tableau JSON",
"Cross-group": "Inter-groupes",
"Cross-group retry": "Nouvelle tentative inter-groupes",
"Cumulative usage": "Utilisation cumulée",
"Currency": "Devise",
"Currency & Display": "Devise et affichage",
@@ -1528,6 +1542,7 @@
"Current email: {{email}}. Enter a new email to change.": "E-mail actuel : {{email}}. Saisissez un nouvel e-mail pour le modifier.",
"Current exchange rate: 1 USD = {{rate}} {{currency}}": "Taux actuel : 1 USD = {{rate}} {{currency}}",
"Current key": "Clé actuelle",
"Current key disable requested": "Désactivation de la clé actuelle demandée",
"Current legacy JSON is invalid, cannot append": "Le JSON ancien format actuel n'est pas valide, impossible d'ajouter",
"Current Level Only": "Niveau actuel uniquement",
"Current load": "Charge actuelle",
@@ -1627,6 +1642,7 @@
"Default placeholder": "Icône par défaut",
"Default range": "Plage par défaut",
"Default Responses API version, if empty, will use the API version above": "Version API des réponses par défaut, si vide, utilisera la version API ci-dessus",
"Default session lifetime (seconds)": "Durée de session par défaut (secondes)",
"Default system prompt for this channel": "Invite système par défaut pour ce canal",
"Default time granularity": "Granularité temporelle par défaut",
"Default to auto groups": "Par défaut aux groupes automatiques",
@@ -1680,10 +1696,12 @@
"Delete plugin version?": "Supprimer cette version du plugin ?",
"Delete Provider": "Supprimer le fournisseur",
"Delete Request Header": "Supprimer un en-tête de requête",
"Delete Rule": "Supprimer la règle",
"Delete selected API keys": "Supprimer les clés API sélectionnées",
"Delete selected channels": "Supprimer les canaux sélectionnés",
"Delete selected models": "Supprimer les modèles sélectionnés",
"Delete selected redemption codes": "Supprimer les codes sélectionnés",
"Delete session rule “{{name}}”? Save your changes to apply the removal.": "Supprimer la règle de session « {{name}} » ? Enregistrez les modifications pour appliquer la suppression.",
"Delete stale instance": "Supprimer l'instance expirée",
"Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.": "Supprimer l'instance expirée \"{{name}}\" ? Si elle a de nouveau signalé son état, elle ne sera pas supprimée.",
"Delete stale instances": "Supprimer les instances expirées",
@@ -1777,6 +1795,7 @@
"Disabled": "Désactivé",
"Disabled all channels with tag: {{tag}}": "Tous les canaux avec le tag {{tag}} ont été désactivés",
"Disabled channels with tag {{tag}}": "Canaux avec l'étiquette {{tag}} désactivés",
"Disabled globally": "Désactivé globalement",
"Disabled lanes are omitted on save.": "Les voies désactivées sont omises à l’enregistrement.",
"Disabled Reason": "Raison de la désactivation",
"Disabled Time": "Heure de désactivation",
@@ -1824,6 +1843,7 @@
"Displayed": "Affiché",
"Displayed in": "Affiché en",
"Displays the mobile sidebar.": "Affiche la barre latérale mobile.",
"Do not keep sessions": "Sans maintien de session",
"Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.": "Ne faites pas trop confiance à cette fonctionnalité. L'IP peut être usurpée. Veuillez l'utiliser avec nginx, CDN et autres passerelles.",
"Do not repeat check-in; only once per day": "Ne répétez pas le check-in ; une seule fois par jour",
"Do not wait one second between polling async tasks for this channel": "Ne pas attendre une seconde entre les interrogations des tâches asynchrones pour ce canal",
@@ -1936,6 +1956,7 @@
"Edit chat preset": "Modifier le préréglage de chat",
"Edit discount tier": "Modifier le palier de remise",
"Edit FAQ": "Modifier la FAQ",
"Enable session affinity": "Activer l’affinité de session",
"Edit group": "Modifier le groupe",
"Edit group rate limit": "Modifier la limite de taux de groupe",
"Edit JSON object directly. Suitable for simple parameter overrides.": "Modifier l'objet JSON directement. Adapté aux substitutions de paramètres simples.",
@@ -2112,6 +2133,7 @@
"Enter password (8-20 characters)": "Saisir le mot de passe (8-20 caractères)",
"Enter password (8–128 characters)": "Saisissez un mot de passe (8 à 128 caractères)",
"Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.": "Saisissez les anciens domaines, un par ligne, sans protocole, port ni chemin. Des ports différents sur un même domaine ne nécessitent pas de domaines compatibles.",
"Excludes the first attempt. Counted per group.": "Hors première tentative, compté par groupe.",
"Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.": "Saisissez les anciens domaines des clés d’accès, un par ligne. Les clés existantes restent utilisables avec ces domaines ; les nouvelles utilisent le domaine principal.",
"Enter quota in {{currency}}": "Saisir le quota en {{currency}}",
"Enter quota in tokens": "Saisir le quota en tokens",
@@ -2333,6 +2355,7 @@
"Failed to load plugins": "Échec du chargement des extensions",
"Failed to load profile": "Échec du chargement du profil",
"Failed to load redemption codes": "Échec du chargement des codes d'échange",
"Failed to load settings": "Échec du chargement des paramètres",
"Failed to load setup data": "Échec du chargement des données de configuration",
"Failed to load setup status": "Échec du chargement de l'état de configuration",
"Failed to load SGLang status": "Échec du chargement de l’état de SGLang",
@@ -2374,6 +2397,7 @@
"Failed to set tag": "Échec de la définition de l'étiquette",
"Failed to setup 2FA": "Échec de la configuration de 2FA",
"Failed to show model in model square": "Impossible d’afficher le modèle dans la galerie",
"Fill a CLI template or add a blank rule.": "Remplissez un modèle CLI ou ajoutez une règle vide.",
"Failed to sign out other sessions": "Impossible de déconnecter les autres sessions",
"Failed to sign out session": "Impossible de déconnecter la session",
"Failed to start {{provider}} login": "Échec du démarrage de la connexion {{provider}}",
@@ -2517,6 +2541,7 @@
"Fix order": "Corriger l’ordre",
"Fixed": "Corrections",
"Fixed abilities: {{success}} succeeded, {{fails}} failed": "Cohérence des canaux réparée : {{success}} réussie(s), {{fails}} échouée(s)",
"Fixed channel constraint": "Contrainte de canal fixe",
"Fixed fee per request": "Frais fixes par requête",
"Fixed price": "Prix fixe",
"Fixed price (USD)": "Prix fixe (USD)",
@@ -2637,8 +2662,11 @@
"GitHub rate limit reached. Try again later.": "Limite de requêtes GitHub atteinte. Réessayez plus tard.",
"Give the group a recognizable name and optional description.": "Donnez au groupe un nom reconnaissable et une description facultative.",
"Give this group a recognizable name.": "Donnez un nom reconnaissable à ce groupe.",
"Global and channel settings": "Paramètres globaux et du canal",
"Global configuration and administrative tools.": "Configuration globale et outils d'administration.",
"Global Coverage": "Couverture mondiale",
"Global default": "Valeur globale par défaut",
"Global default: {{mode}}": "Valeur globale : {{mode}}",
"Global Model Configuration": "Configuration globale du modèle",
"Global throughput": "Débit global",
"Go Back": "Retour",
@@ -2686,6 +2714,7 @@
"Group name cannot be changed when editing.": "Le nom du groupe ne peut pas être modifié lors de la modification.",
"Group prices cannot be expanded because this expression is not a standard tiered pricing expression.": "Les prix par groupe ne peuvent pas être détaillés car cette expression n'est pas une expression tarifaire par paliers standard.",
"Group Pricing": "Tarification des groupes",
"How a session is identified and which channel it keeps.": "Comment une session est identifiée et quel canal elle conserve.",
"Group pricing usage guide": "Guide d'utilisation des groupes tarifaires",
"group ratio": "ratio de groupe",
"Group Ratio": "Ratio de groupe",
@@ -2720,6 +2749,7 @@
"Header Value (supports string or JSON mapping)": "Valeur de l'en-tête (chaîne ou mappage JSON)",
"header. Anthropic-formatted endpoints accept the": ". Les points de terminaison au format Anthropic acceptent à la place",
"Health": "Santé",
"Health check timeout threshold (seconds)": "Seuil de durée des contrôles (secondes)",
"Healthy": "Normal",
"Hidden": "Masqué",
"Hidden — verify to reveal": "Masqué — vérifiez pour révéler",
@@ -2883,6 +2913,7 @@
"Index URL": "URL de l’index",
"Information unavailable": "Information indisponible",
"Inherit global Auto order": "Hériter de l’ordre Auto global",
"Inherit global default": "Utiliser la valeur globale",
"Inherit vendor icon": "Hériter de l’icône du fournisseur",
"Inherited": "Hérité",
"Inherited from {{vendor}}": "Héritée de {{vendor}}",
@@ -2953,6 +2984,7 @@
"Invalid response": "Réponse invalide",
"Invalid rules JSON format": "Format JSON des règles invalide",
"Invalid status code mapping entries: {{entries}}": "Entrées de mappage de code d'état invalides : {{entries}}",
"Invalid status code rules": "Règles de codes d’état invalides",
"Invalid status code rules: {{tokens}}": "Règles de code de statut invalides : {{tokens}}",
"Invalid vLLM server address": "Adresse du serveur vLLM invalide",
"Invalidate": "Invalider",
@@ -2979,6 +3011,7 @@
"IP Whitelist (supports CIDR)": "Liste blanche IP (supporte CIDR)",
"IP: {{ip}} · Method: {{method}}": "IP : {{ip}} · Méthode : {{method}}",
"is less than the configured maximum cache size": "est inférieur à la taille maximale du cache configurée",
"Later requests follow the new channel.": "Les requêtes suivantes suivent le nouveau canal.",
"is the default price; ": "est le prix par défaut ; ",
"It seems like the page you're looking for": "Il semble que la page que vous recherchez",
"Items": "Éléments",
@@ -3018,6 +3051,7 @@
"Keep original value (skip if target exists)": "Conserver la valeur originale (ignorer si la cible existe)",
"Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.": "Conservez les domaines des clés existantes, un par ligne. Si le domaine principal passe de www.example.com à example.com, gardez www.example.com ici.",
"Keep the platform ready": "Gardez la plateforme prête",
"Keep the session binding when the channel is unavailable": "Conserver la liaison si le canal est indisponible",
"Keep this above 1 minute to avoid heavy database load": "Gardez cette valeur au-dessus de 1 minute pour éviter une charge excessive de la base de données",
"Keep this vendor": "Fournisseur à conserver",
"Keep-alive Ping": "Ping de maintien de connexion",
@@ -3174,6 +3208,7 @@
"Logo": "Logo",
"Logo URL": "URL du logo",
"Logs": "Journaux",
"Maximum retries": "Nombre maximal de tentatives",
"Long passwords are unavailable until the password storage upgrade is complete.": "Les mots de passe longs seront disponibles après la mise à niveau du stockage des mots de passe.",
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Cherchez une règle de taux spécial correspondant à ce groupe d’utilisateurs et ce groupe de facturation. Si elle existe, utilisez son taux ; sinon le taux de base du groupe de facturation.",
"Low balance": "Solde faible",
@@ -3246,6 +3281,7 @@
"Maximum 1000 characters. Supports Markdown and HTML.": "Maximum 1000 caractères. Prend en charge Markdown et HTML.",
"Maximum 200 characters": "Maximum 200 caractères",
"Maximum 500 characters. Supports Markdown and HTML.": "Maximum 500 caractères. Prend en charge Markdown et HTML.",
"Maximum cached sessions": "Nombre maximal de sessions en cache",
"Maximum check-in quota": "Quota maximum de connexion",
"Maximum custom groups per token": "Nombre maximal de groupes personnalisés par jeton",
"Maximum input window": "Fenêtre d'entrée maximale",
@@ -3430,6 +3466,7 @@
"months": "mois",
"Moonshot": "Moonshot",
"More": "Plus",
"More actions": "Autres actions",
"More Apps": "Plus",
"more mapping": "plus de mappage",
"More models ({{count}})": "Autres modèles ({{count}})",
@@ -3893,6 +3930,7 @@
"Open in New Tab": "Ouvrir dans un nouvel onglet",
"Open menu": "Ouvrir le menu",
"Open Query Balance to view the upstream JSON response": "Ouvrez « Consulter le solde » pour voir la réponse JSON amont",
"Otherwise the binding is removed.": "Sinon, la liaison est supprimée.",
"Open release": "Ouvrir la version",
"Open source": "Open source",
"Open Source": "Open source",
@@ -4292,6 +4330,7 @@
"Pre-consumed": "Pré-consommé",
"Pre-Consumed Quota": "Quota pré-consommé",
"Pre-release": "Version préliminaire",
"Prefer the original channel, allow switching": "Préférer le canal initial, autoriser le repli",
"Preference saved as {{pref}}, but no active subscription. Requests will be rejected.": "Préférence enregistrée comme {{pref}}, mais aucun abonnement actif. Les demandes seront rejetées.",
"Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.": "Préférence enregistrée comme {{pref}}, mais aucun abonnement actif. Le portefeuille sera utilisé automatiquement.",
"Preferences": "Préférences",
@@ -4424,6 +4463,8 @@
"Prompt Caching": "Mise en cache des invites",
"Prompt Details": "Détails de l'invite",
"Prompt price ($/1M tokens)": "Prix du prompt ($/1M de jetons)",
"Prompt text filtering is active with the current form values.": "Le filtrage des prompts est actif avec les valeurs du formulaire.",
"Prompt text filtering needs both switches enabled and a non-empty keyword list.": "Le filtrage nécessite les deux options activées et une liste de mots-clés non vide.",
"Proprietary": "Propriétaire",
"Protect login and registration with Cloudflare Turnstile": "Protéger la connexion et l'inscription avec Cloudflare Turnstile",
"Provide a JSON object where each key maps to an endpoint definition.": "Fournissez un objet JSON où chaque clé correspond à une définition de point de terminaison.",
@@ -4587,6 +4628,7 @@
"Redirecting to payment page...": "Redirection vers la page de paiement...",
"Redirecting to sign in in {{seconds}} seconds.": "Redirection vers la connexion dans {{seconds}} secondes.",
"Redirects to {{model}}": "Redirige vers {{model}}",
"Reduces cache hit rate": "Réduit le taux de succès du cache",
"Reduces repeated wording": "Réduit les formulations répétées",
"Reference Video": "Vidéo de référence",
"Referral link:": "Lien de parrainage :",
@@ -4706,9 +4748,12 @@
"Request Body Memory Cache": "Cache mémoire du corps de requête",
"Request body must be a JSON object.": "Le corps de la requête doit être un objet JSON.",
"Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.": "Le passage du corps de requête est activé. Le corps sera envoyé directement en amont sans conversion.",
"Request checks": "Contrôle des requêtes",
"Request completed": "Requête terminée",
"Request conversion": "Conversion de requête",
"Request Conversion": "Conversion de requête",
"Request Count": "Nombre de requêtes",
"Request decision flow": "Parcours de décision",
"Request error occurred": "Une erreur de requête est survenue",
"Request failed": "Échec de la requête",
"Request flow": "Flux de requête",
@@ -4724,13 +4769,16 @@
"Request names your users call": "Noms de requête utilisés par vos utilisateurs",
"Request overrides, routing behavior, and upstream model automation": "Surcharges de requête, comportement de routage et automatisation des modèles amont",
"Request Path": "Chemin de requête",
"Request policies": "Politiques de requête",
"Request processing": "Traitement des requêtes",
"Request rejected locally": "Requête rejetée localement",
"Request retry": "Relance des requêtes",
"Request rule pricing": "Règles de tarification de requête",
"Request rules apply on top of this amount.": "Les règles de requête s’appliquent en plus de ce montant.",
"Request simulation": "Simulation de requête",
"Request success rate sampled over the last 24 hours": "Taux de réussite des requêtes échantillonné sur les dernières 24 heures",
"Request success rate; {{incidents}} incident buckets in the last 24 hours": "Taux de réussite des requêtes ; {{incidents}} créneaux avec incident sur les dernières 24 heures",
"Request text filtering": "Filtrage du texte des requêtes",
"Request timed out, please refresh and restart GitHub login": "Délai dépassé, veuillez actualiser la page puis relancer la connexion GitHub",
"Request-based": "Selon la requête",
"Requested items": "Éléments demandés",
@@ -4750,15 +4798,18 @@
"Requests will be forwarded to this worker. Trailing slashes are removed automatically.": "Les requêtes seront transmises à ce worker. Les barres obliques finales sont automatiquement supprimées.",
"Requests:": "Requêtes :",
"Require email verification for new accounts": "Exiger la vérification de l'e-mail pour les nouveaux comptes",
"Retry budget": "Budget de tentatives",
"Require job success before follow-up actions": "Exiger le succès de la tâche avant les actions de suivi",
"Require login to view models": "Exiger la connexion pour voir les modèles",
"Require login to view rankings": "Exiger la connexion pour voir les classements",
"Require the original channel": "Exiger le canal initial",
"required": "requis",
"Required": "Requis",
"Required events:": "Événements requis :",
"Required provider, authentication, model, and group settings": "Paramètres requis de fournisseur, authentification, modèles et groupes",
"Required to expose MjProxy-style image generation to end users.": "Requis pour exposer la génération d'images style MjProxy aux utilisateurs finaux.",
"Requires an available channel and access to its group.": "Nécessite un canal disponible et l’accès à son groupe.",
"Requires global auto-disable and this channel option.": "Nécessite l’activation globale et celle de ce canal.",
"Requires upstream WebSocket support": "Nécessite WebSocket en amont",
"Rerank": "Reclasser",
"Reroll": "Relancer",
@@ -4816,7 +4867,6 @@
"Response time: {{duration}}": "Temps de réponse : {{duration}}",
"Response too large": "Réponse trop volumineuse",
"Responses API Version": "Version de l'API des réponses",
"Responses WebSocket": "Responses WebSocket",
"Restore default pricing": "Rétablir les tarifs par défaut",
"Restore defaults": "Restaurer les paramètres par défaut",
"Restore global Auto": "Restaurer l’Auto global",
@@ -4831,6 +4881,7 @@
"Retry Chain": "Chaîne de tentatives",
"Retry Settings": "Paramètres de relance",
"Retry Suggestion": "Suggestion de relance",
"Rules can inherit or override these defaults.": "Les règles peuvent hériter ou remplacer ces valeurs.",
"Retry Times": "Nombre de tentatives",
"Return a custom error immediately": "Retourner immédiatement une erreur personnalisée",
"Return Custom Error": "Retourner une erreur personnalisée",
@@ -4904,13 +4955,16 @@
"Rule {{line}} prune_objects is missing conditions": "La règle {{line}} prune_objects n'a pas de conditions",
"Rule {{line}} return_error requires a message field": "La règle {{line}} return_error nécessite un champ message",
"Rule Description (optional)": "Description de la règle (optionnel)",
"Rule editor mode": "Mode d’édition des règles",
"Rule group": "Groupe de règles",
"Rule override": "Réglage de la règle",
"rules": "règles",
"Rules": "Règles",
"Rules are checked in order. The first match determines the price.": "Les règles sont évaluées dans l’ordre. La première correspondance détermine le prix.",
"Rules JSON": "Règles JSON",
"Rules JSON must be an array": "Le JSON des règles doit être un tableau",
"Rules match the original model value from the client request body.": "Les règles correspondent à la valeur model originale du corps de la requête client.",
"Run background checks using the selected test mode": "Exécuter les contrôles en arrière-plan selon le mode choisi",
"Run dry run": "Lancer la simulation",
"Run GC": "Exécuter le GC",
"Run tests for the selected models": "Exécuter les tests pour les modèles sélectionnés",
@@ -4982,6 +5036,8 @@
"Scheduled channel tests": "Tests de canaux planifiés",
"Scheduled full test": "Test complet planifié",
"Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.": "Le test complet planifié sonde les canaux non désactivés manuellement ; la récupération passive vérifie uniquement les canaux désactivés automatiquement après des échecs de requêtes réelles.",
"Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.": "Si la désactivation automatique est active globalement et pour le canal, un contrôle périodique ou groupé dépassant cette durée peut le désactiver.",
"Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.": "Le rétablissement périodique est inactif. Les tests groupés peuvent toujours réactiver les canaux désactivés automatiquement.",
"scheduling controls": "contrôles d'ordonnancement",
"Science": "Science",
"Scope": "Portée",
@@ -5095,6 +5151,7 @@
"Select locations": "Sélectionner des emplacements",
"Select model": "Sélectionner un modèle",
"Select Model": "Sélectionner le modèle",
"Session defaults": "Sessions par défaut",
"Select model {{model}}": "Sélectionner le modèle {{model}}",
"Select models": "Sélectionner les modèles",
"Select models (empty for allow all)": "Sélectionner les modèles (vide pour autoriser tout)",
@@ -5105,6 +5162,7 @@
"Select or enter color value": "Sélectionner ou saisir une valeur de couleur",
"Select or enter method identifier": "Sélectionner ou saisir l’identifiant du mode",
"Select or enter model name": "Sélectionner ou saisir le nom du modèle",
"Sessions and retries": "Sessions et tentatives",
"Select or enter payment type": "Sélectionner ou saisir le type de paiement",
"Select or enter payment type key": "Sélectionner ou saisir la clé de type de paiement",
"Select payment method": "Sélectionner le mode de paiement",
@@ -5167,8 +5225,14 @@
"Server Token": "Jeton de serveur",
"Service account JSON file(s)": "Fichier(s) JSON de compte de service",
"Session": "Session",
"Session behavior": "Maintien de session",
"Session behavior prevents switching channels": "Le comportement de session empêche le changement de canal",
"Session expired!": "Session expirée !",
"Session expired?": "Session expirée ?",
"Session rule": "Règle de session",
"Session rule matched": "Règle de session correspondante",
"Session rules": "Règles de session",
"Session rules table": "Tableau des règles de session",
"Session signed out": "Session déconnectée",
"Sessions & Access": "Sessions et accès",
"Set": "Définir",
@@ -5321,6 +5385,7 @@
"Source name": "Nom de la source",
"Source vendors": "Fournisseurs sources",
"Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.": "Les fournisseurs sources seront supprimés après le transfert des modèles. Les informations du fournisseur cible sont conservées.",
"Source: global settings. Changes take effect after saving.": "Source : paramètres globaux. Les modifications prennent effet après enregistrement.",
"sources": "sources",
"Space-separated OAuth scopes": "Scopes OAuth séparés par des espaces",
"Spark model version, e.g., v2.1 (version number in API URL)": "Version du modèle Spark, par exemple v2.1 (numéro de version dans l'URL de l'API)",
@@ -5370,6 +5435,8 @@
"Status Code": "Code de statut",
"Status Code Mapping": "Mappage des codes d'état",
"Status code mapping must use valid HTTP status codes": "Le mappage des codes d'état doit utiliser des codes d'état HTTP valides",
"Status is outside the retry rules": "Code hors des règles de reprise",
"Status matches the retry rules": "Code conforme aux règles de reprise",
"Status Page Slug": "Slug de la page d'état",
"Status short": "État",
"Status:": "Statut :",
@@ -5391,6 +5458,7 @@
"Stored value is not echoed back for security": "Par sécurité, la valeur enregistrée n'est pas affichée",
"stream": "Flux",
"Stream": "Flux",
"Stream did not complete successfully": "Flux non terminé avec succès",
"Stream Mode": "Mode streaming",
"Stream Status": "Statut du flux",
"Stream tokens incrementally as they are generated": "Diffuser les jetons au fur et à mesure de leur génération",
@@ -5432,6 +5500,7 @@
"succeeded": "réussi",
"Success": "Succès",
"Success rate": "Taux de réussite",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Les contrôles périodiques ou groupés réussis peuvent rétablir les canaux désactivés automatiquement. Ceux désactivés manuellement le restent.",
"Successfully created {{count}} API Key(s)": "{{count}} clé(s) API créée(s) avec succès",
"Successfully created {{count}} redemption codes": "{{count}} codes de réduction créés avec succès",
"Successfully deleted {{count}} API key(s)": "{{count}} clé(s) API supprimée(s) avec succès",
@@ -5471,6 +5540,7 @@
"Switch to JSON": "Passer à JSON",
"Switch to Visual": "Passer à l'affichage visuel",
"Switch to visual editor": "Passer à l’éditeur visuel",
"Switch to visual mode to add rules or apply templates.": "Passez en mode visuel pour ajouter des règles ou appliquer des modèles.",
"Switch to visual pricing?": "Passer à la tarification visuelle ?",
"Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.": "L’expression sera régénérée à partir du tableau des prix. Sa mise en forme et les noms des paliers seront remplacés. Les modifications prendront effet après enregistrement.",
"Sync Endpoint": "Point de terminaison de synchronisation",
@@ -5500,6 +5570,7 @@
"System Administration": "Administration du système",
"System Announcements": "Annonces système",
"System Behavior": "Comportement du système",
"System constraint": "Contrainte système",
"System data statistics": "Statistiques des données système",
"System default": "Système par défaut",
"System Info": "Infos système",
@@ -5517,6 +5588,7 @@
"System Prompt": "Invite système",
"System Prompt Concatenation": "Concaténation des invites système",
"System Prompt Override": "Remplacement du prompt système",
"System retry exclusion": "Exclusion système de reprise",
"System settings": "Paramètres système",
"System Settings": "Paramètres du système",
"System setup wizard": "Assistant de configuration du système",
@@ -5551,6 +5623,7 @@
"Task": "Tâche",
"Task billing": "Facturation de tâche",
"Task Details": "Détails de la tâche",
"Task failed": "Échec de la tâche",
"Task History": "Historique des tâches",
"Task ID": "ID de la tâche",
"Task ID:": "ID de tâche :",
@@ -5659,6 +5732,7 @@
"The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.": "La synchronisation récupérera les modèles et fournisseurs manquants à partir de la source sélectionnée. Les enregistrements existants ne sont mis à jour que lorsque vous approuvez les conflits.",
"The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.": "Le système facture toujours en USD. La devise du site facilite la saisie et la conversion des prix ; les montants sont convertis en USD au taux du site. Changer de devise ne modifie pas le prix réel. Les expressions de facturation brutes utilisent toujours les USD.",
"The system currently uses: {{domain}}": "Le système utilise actuellement : {{domain}}",
"The task was accepted; submission cannot be replayed": "Tâche acceptée : soumission non rejouable",
"The Telegram authorization request is invalid or expired.": "La demande d’autorisation Telegram est invalide ou a expiré.",
"The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.": "Le nom de fournisseur OAuth telegram est réservé. Demandez à votre administrateur de renommer le fournisseur personnalisé en conflit.",
"The token group that will have a custom ratio": "Le groupe de jetons qui aura un ratio personnalisé",
@@ -5820,6 +5894,7 @@
"Tiered pricing": "Tarification par paliers",
"tiers": "paliers",
"Time": "Heure",
"Time between scheduled channel checks": "Intervalle entre les contrôles périodiques des canaux",
"Time functions use the timezone written in the expression.": "Les fonctions temporelles utilisent le fuseau horaire indiqué dans l’expression.",
"Time Granularity": "Granularité temporelle",
"Time range": "Plage horaire",
@@ -5933,6 +6008,7 @@
"Total {{count}} records": "{{count}} enregistrements au total",
"Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.": "Total = utilisé + restant. Ce n’est ni une allocation initiale ni un budget périodique. Modifier le quota restant change le total et le pourcentage.",
"Total Allocated": "Total alloué",
"Total attempt budget exhausted": "Budget de tentatives épuisé",
"Total check-ins": "Total des connexions",
"Total consumed": "Consommé total",
"Total consumed quota": "Quota total consommé",
@@ -6028,6 +6104,7 @@
"Unbind": "Dissocier",
"Unbind failed": "Échec de la dissociation",
"Unbound {{provider}}": "{{provider}} dissocié",
"Unchanged": "Inchangé",
"Underflow": "Sous-dépassement",
"Underground": "Underground",
"Understand how user groups, token groups, ratios, and special rules work together.": "Comprendre comment les groupes utilisateur, groupes de jetons, ratios et règles spéciales fonctionnent ensemble.",
@@ -6083,6 +6160,7 @@
"Update the configuration for this custom OAuth provider.": "Mettre à jour la configuration de ce fournisseur OAuth personnalisé.",
"Update the redemption code by providing necessary info.": "Mettez à jour le code de remboursement en fournissant les informations nécessaires.",
"Update the reusable bundle below.": "Mettez à jour le bundle réutilisable ci-dessous.",
"Update the session binding after a successful switch": "Actualiser la liaison après un changement réussi",
"Update the user by providing necessary info.": "Mettre à jour l'utilisateur en fournissant les informations nécessaires.",
"Update vendor information for {{name}}": "Mettre à jour les informations du fournisseur pour {{name}}",
"Update your password for account:": "Mettez à jour votre mot de passe pour le compte :",
@@ -6148,7 +6226,9 @@
"Upstream prices fetched successfully": "Prix amont récupérés avec succès",
"Upstream protocol plan": "Plan de protocole amont",
"Upstream ratios fetched successfully": "Ratios en amont récupérés avec succès",
"Upstream request failed": "Échec de requête amont",
"Upstream Request ID": "ID de requête en amont",
"Upstream response": "Réponse amont",
"Upstream Response": "Réponse amont",
"Upstream Response (billing-usage-anthropic-estimated)": "Réponse amont (billing-usage-anthropic-estimated)",
"Upstream Response (billing-usage-anthropic)": "Réponse amont (billing-usage-anthropic)",
@@ -6523,6 +6603,7 @@
"with conflicts": "avec des conflits",
"With linked models": "Avec modèles associés",
"with the API key from your token settings.": "par la clé API de votre page de jetons.",
"With these settings, automatic disabling is off for all channels.": "Avec ces paramètres, la désactivation automatique est inactive pour tous les canaux.",
"Without additional conditions, only the type above is used for pruning.": "Sans conditions supplémentaires, seul le type ci-dessus est utilisé pour le nettoyage.",
"Without linked models": "Sans modèle associé",
"Worked example": "Exemple détaillé",
@@ -6586,6 +6667,14 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Channel error": "Erreur de canal",
"Unrecognized status code": "Code d'état non reconnu",
"Correct the invalid settings before saving.": "Corrigez les paramètres invalides avant de les enregistrer.",
"Upstream connection": "Connexion amont",
"Local check": "Vérification locale",
"Responses WebSocket": "Responses WebSocket",
"Cross-group retry": "Nouvelle tentative inter-groupes",
"Request policy decisions": "Décisions de la politique de requête"
}
}
+92 -3
View File
@@ -53,6 +53,7 @@
"{{count}} FAQ entries will be removed from the list.": "{{count}} 件の FAQ 項目がリストから削除されます。",
"{{count}} hours ago": "{{count}} 時間前",
"{{count}} incidents": "{{count}} 件のインシデント",
"2xx, 504 and 524 are always excluded.": "2xx・504・524 は常に除外されます。",
"{{count}} incidents in the last 24 hours": "過去 24 時間に {{count}} 件のインシデント",
"{{count}} incidents in the last 30 days": "過去 30 日間で {{count}} 件のインシデント",
"{{count}} IP(s)": "{{count}} IP",
@@ -208,6 +209,7 @@
"Action": "アクション",
"Action confirmation": "操作確認",
"Actions": "操作",
"Actions for {{name}}": "{{name}} の操作",
"Activate / Roll back": "有効化 / ロールバック",
"active": "有効",
"Active": "有効",
@@ -351,6 +353,7 @@
"Advanced text editing": "高度なテキスト編集",
"Aesthetic style": "スタイル",
"Affected windows:": "対象ウィンドウ:",
"Affinity cache settings": "セッションキャッシュ設定",
"After clicking the button, you'll be asked to authorize the bot": "ボタンをクリックすると、ボットの認証を求められます",
"After conversion": "変換後",
"After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.": "変換後は式の事前引き落としと丸め規則が適用されます。有効な単価は維持されますが、個々の丸め後の料金は異なる場合があります。",
@@ -390,6 +393,7 @@
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "すべてのグループ名はここで管理します。倍率はこのグループとして課金される呼び出しに適用され、チャージ倍率はこのグループに所属するユーザーに適用されます。",
"All Groups": "すべてのグループ",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "すべてのグループは料金グループ表で管理される同じ名前プールを共有しますが、1つの名前には2つの役割があります。ユーザーグループとしてはユーザーの属性を表し、トークングループとしてはルーティングと課金を決定します。",
"All models": "すべてのモデル",
"All Models": "すべてのモデル",
"All models in use are properly configured.": "使用中のすべてのモデルが適切に構成されています。",
"All Must Match (AND)": "すべて一致(AND)",
@@ -559,6 +563,7 @@
"Apply {{field}} for {{name}}": "{{name}} に {{field}} を適用",
"Apply All Upstream Updates": "すべてのアップストリーム更新を適用",
"Apply changes": "変更を適用",
"Apply disable rules to upstream request errors and scheduled or bulk health checks": "上流リクエストのエラーと定期または一括ヘルスチェックに無効化ルールを適用します",
"Apply Filters": "フィルターを適用",
"Apply IP Filter to Resolved Domains": "解決されたドメインにIPフィルターを適用",
"Apply Overwrite": "上書き適用",
@@ -609,6 +614,7 @@
"At least one model regex pattern is required": "少なくとも1つのモデル正規表現パターンが必要です",
"At least one valid key source is required": "少なくとも1つの有効なキーソースが必要です",
"Attach": "添付",
"Attempt": "試行",
"Audio": "音声",
"Audio and Realtime pricing must be converted manually.": "音声と Realtime の料金は手動で変換してください。",
"Audio and text-only requests keep their respective pricing.": "音声とテキストのみのリクエストには、それぞれ従来の料金を適用します。",
@@ -670,6 +676,8 @@
"Auto refresh (5s)": "自動更新(5秒)",
"Auto Sync Upstream Models": "アップストリームモデルの自動同期",
"Auto-disable channel": "チャネル自動無効化",
"Auto-disable disabled": "自動無効化が無効",
"Auto-disable enabled": "自動無効化が有効",
"Auto-disable rules": "自動無効化ルール",
"Auto-disable status codes": "自動無効化するステータスコード",
"Auto-disable-enabled channels only": "自動無効化が有効なチャネルのみ",
@@ -965,9 +973,11 @@
"Channel copied successfully": "チャネルが正常にコピーされました",
"Channel created successfully": "チャネルが正常に作成されました",
"Channel deleted successfully": "チャネルが正常に削除されました",
"Channel disable requested": "チャネル無効化を要求",
"Channel disabled successfully": "チャネルが正常に無効化されました",
"Channel enabled successfully": "チャネルが正常に有効化されました",
"Channel Extra Settings": "チャネル詳細設定",
"Channel health": "チャネルの健全性",
"Channel health checks": "チャネルヘルスチェック",
"Channel ID": "チャネルID",
"Channel ID is required": "チャネル ID が必要です",
@@ -977,6 +987,9 @@
"Channel Management": "チャネル管理",
"Channel models": "チャネルモデル",
"Channel name is required": "チャネル名が必要です",
"Channel selected": "チャネルを選択",
"Channel selection": "チャネル選択",
"Channel switching options": "チャネル切り替えの設定",
"Channel test completed": "チャネルテストが完了しました",
"Channel test concurrency": "チャンネルテストの同時実行数",
"Channel test concurrency must be between 1 and 32": "チャンネルテストの同時実行数は1~32にしてください",
@@ -994,6 +1007,7 @@
"Channels {{channels}} · Groups {{groups}}": "チャネル {{channels}} · グループ {{groups}}",
"Channels and groups": "チャネルとグループ",
"Channels deleted successfully": "チャネルが正常に削除されました",
"Channels must also enable Auto Ban before automatic disabling can take effect.": "自動無効化ルールを適用するには、各チャネルでも自動無効化を有効にしてください。",
"Character chat, storytelling, persona": "キャラクター会話・ストーリーテリング・ペルソナ",
"Charge.": "課金する。",
"Chart Preferences": "チャートの環境設定",
@@ -1031,6 +1045,7 @@
"checkout.session.completed": "checkout.session.completed",
"checkout.session.expired": "checkout.session.expired",
"Checks hourly while you are online, including pre-releases.": "オンライン中はプレリリースを含め、1時間ごとに確認します。",
"Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.": "対応リクエストから抽出したテキストを、大文字と小文字を区別せずキーワードと照合します。一致すると上流への送信前に拒否し、チャネルの健全性には影響しません。画像、音声、生成された応答は検査しません。",
"Chinese": "中国語",
"Choose a complete upstream protocol plan or edit individual route groups.": "完全な上流プロトコルプランを選ぶか、ルートグループを個別に編集します。",
"Choose a provider or plugin to configure your channel.": "プロバイダーまたはプラグインを選択して、チャネルを設定します。",
@@ -1514,7 +1529,6 @@
"Creem product ID from your Creem dashboard.": "Creem ダッシュボードから取得した Creem 製品 ID。",
"Creem products must be a JSON array": "Creem 製品は JSON 配列でなければなりません",
"Cross-group": "グループ横断",
"Cross-group retry": "グループ横断リトライ",
"Cumulative usage": "累積使用量",
"Currency": "通貨",
"Currency & Display": "通貨と表示",
@@ -1528,6 +1542,7 @@
"Current email: {{email}}. Enter a new email to change.": "現在のメール: {{email}}。変更するには新しいメールアドレスを入力してください。",
"Current exchange rate: 1 USD = {{rate}} {{currency}}": "現在の為替レート:1 USD = {{rate}} {{currency}}",
"Current key": "現在のキー",
"Current key disable requested": "現在のキーの無効化を要求",
"Current legacy JSON is invalid, cannot append": "現在の旧形式JSONが無効なため、追加できません",
"Current Level Only": "現在の階層のみ",
"Current load": "現在の負荷",
@@ -1627,6 +1642,7 @@
"Default placeholder": "既定の代替アイコン",
"Default range": "デフォルト範囲",
"Default Responses API version, if empty, will use the API version above": "デフォルトの応答APIバージョン。空の場合、上記のAPIバージョンが使用されます",
"Default session lifetime (seconds)": "セッションの既定の有効期間(秒)",
"Default system prompt for this channel": "このチャネルのデフォルトのシステムプロンプト",
"Default time granularity": "デフォルトの時間粒度",
"Default to auto groups": "デフォルトで自動グループ化",
@@ -1680,10 +1696,12 @@
"Delete plugin version?": "プラグインのバージョンを削除しますか?",
"Delete Provider": "プロバイダーを削除",
"Delete Request Header": "リクエストヘッダーを削除",
"Delete Rule": "ルールを削除",
"Delete selected API keys": "選択したAPIキーを削除",
"Delete selected channels": "選択したチャネルを削除",
"Delete selected models": "選択したモデルを削除",
"Delete selected redemption codes": "選択した引き換えコードを削除",
"Delete session rule “{{name}}”? Save your changes to apply the removal.": "セッションルール「{{name}}」を削除しますか?変更を保存すると削除が適用されます。",
"Delete stale instance": "期限切れインスタンスを削除",
"Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.": "期限切れインスタンス \"{{name}}\" を削除しますか?再度報告されている場合は削除されません。",
"Delete stale instances": "期限切れインスタンスを削除",
@@ -1777,6 +1795,7 @@
"Disabled": "無効",
"Disabled all channels with tag: {{tag}}": "タグ「{{tag}}」の全チャネルを無効にしました",
"Disabled channels with tag {{tag}}": "タグ {{tag}} のチャネルを無効化しました",
"Disabled globally": "全体で無効",
"Disabled lanes are omitted on save.": "無効な価格レーンは保存時に省略されます。",
"Disabled Reason": "無効化の理由",
"Disabled Time": "無効化された時刻",
@@ -1824,6 +1843,7 @@
"Displayed": "表示中",
"Displayed in": "表示単位",
"Displays the mobile sidebar.": "モバイルサイドバーを表示します。",
"Do not keep sessions": "セッションを維持しない",
"Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.": "この機能を過信しないでください。IPは偽装される可能性があります。nginx、CDNなどのゲートウェイと併用してください。",
"Do not repeat check-in; only once per day": "チェックインを繰り返さないでください;1日1回のみ",
"Do not wait one second between polling async tasks for this channel": "このチャネルの非同期タスクをポーリングする間に1秒待機しない",
@@ -1936,6 +1956,7 @@
"Edit chat preset": "チャットプリセットを編集",
"Edit discount tier": "割引ティアを編集",
"Edit FAQ": "FAQ を編集",
"Enable session affinity": "セッション維持を有効にする",
"Edit group": "グループを編集",
"Edit group rate limit": "グループレート制限を編集",
"Edit JSON object directly. Suitable for simple parameter overrides.": "JSONオブジェクトを直接編集します。シンプルなパラメータオーバーライドに適しています。",
@@ -2112,6 +2133,7 @@
"Enter password (8-20 characters)": "パスワードを入力 (8~20文字)",
"Enter password (8–128 characters)": "パスワードを入力(8~128文字)",
"Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.": "以前のドメインを1行に1つ入力し、プロトコル、ポート、パスは含めないでください。同じドメインでポートのみが異なる場合、互換ドメインへの追加は不要です。",
"Excludes the first attempt. Counted per group.": "初回を除く、グループごとの回数です。",
"Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.": "以前のパスキードメインを1行に1つ入力してください。既存のパスキーはこれらのドメインで引き続き認証でき、新しいパスキーはメインドメインを使用します。",
"Enter quota in {{currency}}": "{{currency}} でクォータを入力",
"Enter quota in tokens": "トークン単位でクォータを入力",
@@ -2333,6 +2355,7 @@
"Failed to load plugins": "プラグインの読み込みに失敗しました",
"Failed to load profile": "プロファイルの読み込みに失敗しました",
"Failed to load redemption codes": "引き換えコードの読み込みに失敗しました",
"Failed to load settings": "設定を読み込めませんでした",
"Failed to load setup data": "セットアップデータの読み込みに失敗しました",
"Failed to load setup status": "セットアップ状態の読み込みに失敗しました",
"Failed to load SGLang status": "SGLang の状態を読み込めませんでした",
@@ -2374,6 +2397,7 @@
"Failed to set tag": "タグの設定に失敗しました",
"Failed to setup 2FA": "2FA の設定に失敗しました",
"Failed to show model in model square": "モデル広場に表示できませんでした",
"Fill a CLI template or add a blank rule.": "CLI テンプレートを使うか、空のルールを追加してください。",
"Failed to sign out other sessions": "他のセッションのサインアウトに失敗しました",
"Failed to sign out session": "セッションのサインアウトに失敗しました",
"Failed to start {{provider}} login": "{{provider}} ログインの開始に失敗しました",
@@ -2517,6 +2541,7 @@
"Fix order": "順序を修正",
"Fixed": "修正",
"Fixed abilities: {{success}} succeeded, {{fails}} failed": "チャネル整合性を修復しました:成功 {{success}} 件、失敗 {{fails}} 件",
"Fixed channel constraint": "固定チャネル制約",
"Fixed fee per request": "リクエストごとの固定料金",
"Fixed price": "固定価格",
"Fixed price (USD)": "固定価格 (USD)",
@@ -2637,8 +2662,11 @@
"GitHub rate limit reached. Try again later.": "GitHub のリクエスト上限に達しました。しばらくしてから再試行してください。",
"Give the group a recognizable name and optional description.": "グループに認識しやすい名前とオプションの説明を付けます。",
"Give this group a recognizable name.": "このグループに認識しやすい名前を付けます。",
"Global and channel settings": "全体設定とチャネル設定",
"Global configuration and administrative tools.": "グローバル設定と管理ツール。",
"Global Coverage": "グローバルカバレッジ",
"Global default": "全体の既定値",
"Global default: {{mode}}": "全体のデフォルト:{{mode}}",
"Global Model Configuration": "グローバルモデル設定",
"Global throughput": "全体スループット",
"Go Back": "戻る",
@@ -2686,6 +2714,7 @@
"Group name cannot be changed when editing.": "編集時はグループ名を変更できません。",
"Group prices cannot be expanded because this expression is not a standard tiered pricing expression.": "この式は標準の段階制料金式ではないため、グループ別価格を展開できません。",
"Group Pricing": "グループ料金",
"How a session is identified and which channel it keeps.": "セッションの識別方法と使用するチャネルを定義します。",
"Group pricing usage guide": "グループ料金の使用ガイド",
"group ratio": "グループ倍率",
"Group Ratio": "グループ倍率",
@@ -2720,6 +2749,7 @@
"Header Value (supports string or JSON mapping)": "ヘッダー値(文字列またはJSONマッピング対応)",
"header. Anthropic-formatted endpoints accept the": " ヘッダーが必要です。Anthropic 形式のエンドポイントでは",
"Health": "ヘルスケア",
"Health check timeout threshold (seconds)": "ヘルスチェックの時間しきい値(秒)",
"Healthy": "正常",
"Hidden": "非表示",
"Hidden — verify to reveal": "非表示 — 確認して表示",
@@ -2883,6 +2913,7 @@
"Index URL": "インデックス URL",
"Information unavailable": "情報を取得できません",
"Inherit global Auto order": "グローバル Auto 順序を継承",
"Inherit global default": "全体のデフォルトを継承",
"Inherit vendor icon": "プロバイダーのアイコンを継承",
"Inherited": "継承",
"Inherited from {{vendor}}": "{{vendor}} から継承",
@@ -2953,6 +2984,7 @@
"Invalid response": "無効な応答",
"Invalid rules JSON format": "ルール JSON の形式が不正です",
"Invalid status code mapping entries: {{entries}}": "無効なステータスコードマッピング:{{entries}}",
"Invalid status code rules": "ステータスコードのルールが無効です",
"Invalid status code rules: {{tokens}}": "無効なステータスコードルール:{{tokens}}",
"Invalid vLLM server address": "vLLM サーバーのアドレスが無効です",
"Invalidate": "無効化",
@@ -2979,6 +3011,7 @@
"IP Whitelist (supports CIDR)": "IP ホワイトリスト(CIDR対応)",
"IP: {{ip}} · Method: {{method}}": "IP: {{ip}} · 方法: {{method}}",
"is less than the configured maximum cache size": "設定された最大キャッシュサイズより小さい",
"Later requests follow the new channel.": "以降のリクエストは新しいチャネルを使用します。",
"is the default price; ": "はデフォルト価格です; ",
"It seems like the page you're looking for": "お探しのページは",
"Items": "項目",
@@ -3018,6 +3051,7 @@
"Keep original value (skip if target exists)": "元の値を保持(ターゲットが存在する場合はスキップ)",
"Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.": "既存のパスキーで使用しているドメインを1行に1つ入力します。メインドメインを www.example.com から example.com に変更した場合は、ここに www.example.com を残してください。",
"Keep the platform ready": "プラットフォームを準備状態に保つ",
"Keep the session binding when the channel is unavailable": "チャネルが利用できない場合も関連付けを保持",
"Keep this above 1 minute to avoid heavy database load": "データベースへの負荷を避けるため、これを1分以上に保ってください",
"Keep this vendor": "このプロバイダーを残す",
"Keep-alive Ping": "キープアライブPing",
@@ -3174,6 +3208,7 @@
"Logo": "ロゴ",
"Logo URL": "ロゴURL",
"Logs": "ログ",
"Maximum retries": "最大再試行回数",
"Long passwords are unavailable until the password storage upgrade is complete.": "パスワード保存方式の更新が完了するまで、長いパスワードは使用できません。",
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "このユーザーグループと課金グループに一致する特別倍率ルールを探します。あればその倍率を、なければ料金表の課金グループの基本倍率を使います。",
"Low balance": "残高不足",
@@ -3246,6 +3281,7 @@
"Maximum 1000 characters. Supports Markdown and HTML.": "最大1000文字。MarkdownとHTMLをサポートしています。",
"Maximum 200 characters": "最大200文字",
"Maximum 500 characters. Supports Markdown and HTML.": "最大500文字。MarkdownとHTMLをサポートしています。",
"Maximum cached sessions": "キャッシュするセッションの上限",
"Maximum check-in quota": "最大チェックインクォータ",
"Maximum custom groups per token": "トークンごとのカスタムグループ上限",
"Maximum input window": "最大入力ウィンドウ",
@@ -3430,6 +3466,7 @@
"months": "ヶ月",
"Moonshot": "Moonshot",
"More": "もっと見る",
"More actions": "その他の操作",
"More Apps": "さらに",
"more mapping": "さらにマッピング",
"More models ({{count}})": "その他のモデル({{count}})",
@@ -3893,6 +3930,7 @@
"Open in New Tab": "新しいタブで開く",
"Open menu": "メニューを開く",
"Open Query Balance to view the upstream JSON response": "「残高照会」を開いて上流の JSON レスポンスを確認してください",
"Otherwise the binding is removed.": "オフの場合は関連付けを削除します。",
"Open release": "リリースを開く",
"Open source": "オープンソース",
"Open Source": "オープンソース",
@@ -4292,6 +4330,7 @@
"Pre-consumed": "事前消費",
"Pre-Consumed Quota": "事前消費クォータ",
"Pre-release": "プレリリース",
"Prefer the original channel, allow switching": "元のチャネルを優先し、切り替えを許可",
"Preference saved as {{pref}}, but no active subscription. Requests will be rejected.": "設定は{{pref}}として保存されましたが、アクティブなサブスクリプションがありません。リクエストは拒否されます。",
"Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.": "設定は{{pref}}として保存されましたが、アクティブなサブスクリプションがありません。ウォレットが自動的に使用されます。",
"Preferences": "環境設定",
@@ -4424,6 +4463,8 @@
"Prompt Caching": "プロンプトキャッシング",
"Prompt Details": "プロンプトの詳細",
"Prompt price ($/1M tokens)": "プロンプト価格 (100万トークンあたり$)",
"Prompt text filtering is active with the current form values.": "現在のフォーム設定ではプロンプトのテキストフィルターが有効です。",
"Prompt text filtering needs both switches enabled and a non-empty keyword list.": "プロンプトのテキストフィルターには、両方のスイッチと空でないキーワード一覧が必要です。",
"Proprietary": "プロプライエタリ",
"Protect login and registration with Cloudflare Turnstile": "Cloudflare Turnstile でログインと登録を保護する",
"Provide a JSON object where each key maps to an endpoint definition.": "各キーがエンドポイント定義にマップされる JSON オブジェクトを提供してください。",
@@ -4587,6 +4628,7 @@
"Redirecting to payment page...": "支払いページにリダイレクト中...",
"Redirecting to sign in in {{seconds}} seconds.": "{{seconds}} 秒後にログインページへ移動します。",
"Redirects to {{model}}": "{{model}} にリダイレクト",
"Reduces cache hit rate": "キャッシュヒット率が低下します",
"Reduces repeated wording": "同じ表現の繰り返しを抑えます",
"Reference Video": "参照動画",
"Referral link:": "紹介リンク:",
@@ -4706,9 +4748,12 @@
"Request Body Memory Cache": "リクエストボディのメモリキャッシュ",
"Request body must be a JSON object.": "リクエスト本文は JSON オブジェクトである必要があります。",
"Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.": "リクエストボディのパススルーが有効です。リクエストボディは変換なしで直接アップストリームに送信されます。",
"Request checks": "リクエスト検査",
"Request completed": "リクエスト完了",
"Request conversion": "リクエスト変換",
"Request Conversion": "リクエスト変換",
"Request Count": "リクエスト数",
"Request decision flow": "リクエスト判断フロー",
"Request error occurred": "リクエストエラーが発生しました",
"Request failed": "リクエスト失敗",
"Request flow": "リクエストフロー",
@@ -4724,13 +4769,16 @@
"Request names your users call": "ユーザーが呼び出すリクエストモデル名",
"Request overrides, routing behavior, and upstream model automation": "リクエスト上書き、ルーティング動作、上流モデル自動化",
"Request Path": "リクエストパス",
"Request policies": "リクエストポリシー",
"Request processing": "リクエスト処理",
"Request rejected locally": "ローカルで拒否",
"Request retry": "リクエスト再試行",
"Request rule pricing": "リクエストルールの課金",
"Request rules apply on top of this amount.": "リクエストルールはこの金額に追加で適用されます。",
"Request simulation": "リクエストのシミュレーション",
"Request success rate sampled over the last 24 hours": "過去 24 時間にサンプリングされたリクエスト成功率",
"Request success rate; {{incidents}} incident buckets in the last 24 hours": "リクエスト成功率;過去 24 時間に {{incidents}} 個のインシデント時間枠",
"Request text filtering": "リクエストのテキストフィルター",
"Request timed out, please refresh and restart GitHub login": "タイムアウトしました。ページをリロードして GitHub ログインをやり直してください",
"Request-based": "リクエスト条件あり",
"Requested items": "リクエスト件数",
@@ -4750,15 +4798,18 @@
"Requests will be forwarded to this worker. Trailing slashes are removed automatically.": "リクエストはこのワーカーに転送されます。末尾のスラッシュは自動的に削除されます。",
"Requests:": "リクエスト:",
"Require email verification for new accounts": "新しいアカウントにメール認証を要求する",
"Retry budget": "再試行予算",
"Require job success before follow-up actions": "フォローアップ アクション前にジョブの成功を要求",
"Require login to view models": "モデルを表示するにはログインを要求する",
"Require login to view rankings": "ランキングを表示するにはログインを要求する",
"Require the original channel": "元のチャネルを必須にする",
"required": "必須",
"Required": "必須",
"Required events:": "必須イベント:",
"Required provider, authentication, model, and group settings": "必須のプロバイダー、認証、モデル、グループ設定",
"Required to expose MjProxy-style image generation to end users.": "エンドユーザーに MjProxy スタイルの画像生成を公開するために必要です。",
"Requires an available channel and access to its group.": "利用可能なチャネルと、そのグループへのアクセス権が必要です。",
"Requires global auto-disable and this channel option.": "全体とこのチャネルの両方で自動無効化を有効にする必要があります。",
"Requires upstream WebSocket support": "上流の WebSocket 対応が必要",
"Rerank": "再ランク付け",
"Reroll": "やり直し",
@@ -4816,7 +4867,6 @@
"Response time: {{duration}}": "応答時間: {{duration}}",
"Response too large": "応答が大きすぎます",
"Responses API Version": "応答APIバージョン",
"Responses WebSocket": "Responses WebSocket",
"Restore default pricing": "既定の料金に戻す",
"Restore defaults": "既定に戻す",
"Restore global Auto": "グローバル Auto に戻す",
@@ -4831,6 +4881,7 @@
"Retry Chain": "リトライチェーン",
"Retry Settings": "再試行設定",
"Retry Suggestion": "リトライ提案",
"Rules can inherit or override these defaults.": "ルールはこの設定を継承または上書きできます。",
"Retry Times": "再試行回数",
"Return a custom error immediately": "即座にカスタムエラーを返す",
"Return Custom Error": "カスタムエラーを返す",
@@ -4904,13 +4955,16 @@
"Rule {{line}} prune_objects is missing conditions": "ルール {{line}} のprune_objectsに条件がありません",
"Rule {{line}} return_error requires a message field": "ルール {{line}} のreturn_errorにはmessageフィールドが必要です",
"Rule Description (optional)": "ルール説明(任意)",
"Rule editor mode": "ルールの編集モード",
"Rule group": "ルールグループ",
"Rule override": "ルールの個別設定",
"rules": "ルール",
"Rules": "ルール",
"Rules are checked in order. The first match determines the price.": "ルールは順番に判定され、最初に一致したルールで料金が決まります。",
"Rules JSON": "ルール JSON",
"Rules JSON must be an array": "ルール JSON は配列である必要があります",
"Rules match the original model value from the client request body.": "ルールはクライアントリクエスト本文の元の model 値に一致します。",
"Run background checks using the selected test mode": "選択したテストモードでバックグラウンド検査を実行します",
"Run dry run": "ドライランを実行",
"Run GC": "GC 実行",
"Run tests for the selected models": "選択したモデルのテストを実行",
@@ -4982,6 +5036,8 @@
"Scheduled channel tests": "スケジュールされたチャネルテスト",
"Scheduled full test": "定期フルテスト",
"Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.": "定期フルテストは手動で無効化されていないチャネルを検査します。パッシブ復旧は実リクエストの失敗後に自動無効化されたチャネルのみを確認します。",
"Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.": "全体とチャネルの両方で自動無効化が有効な場合、定期または一括ヘルスチェックがこの時間を超えると無効化されることがあります。",
"Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.": "定期復旧は無効です。一括チャネルテストでは、自動無効化されたチャネルを復旧できます。",
"scheduling controls": "スケジューリング制御",
"Science": "科学",
"Scope": "スコープ",
@@ -5095,6 +5151,7 @@
"Select locations": "ロケーションを選択",
"Select model": "モデルを選択",
"Select Model": "モデルを選択",
"Session defaults": "セッションのデフォルト",
"Select model {{model}}": "モデル {{model}} を選択",
"Select models": "モデルを選択",
"Select models (empty for allow all)": "モデルを選択 (すべて許可する場合は空)",
@@ -5105,6 +5162,7 @@
"Select or enter color value": "色の値を選択または入力",
"Select or enter method identifier": "決済方法の識別子を選択または入力",
"Select or enter model name": "モデル名を選択または入力",
"Sessions and retries": "セッションと再試行",
"Select or enter payment type": "支払いタイプを選択または入力",
"Select or enter payment type key": "支払いタイプキーを選択または入力",
"Select payment method": "お支払い方法を選択",
@@ -5167,8 +5225,14 @@
"Server Token": "サーバートークン",
"Service account JSON file(s)": "サービスアカウントJSONファイル",
"Session": "セッション",
"Session behavior": "セッション維持",
"Session behavior prevents switching channels": "セッション設定によりチャネルの切り替えが禁止されています",
"Session expired!": "セッションが期限切れです!",
"Session expired?": "セッションが期限切れになりましたか?",
"Session rule": "セッションルール",
"Session rule matched": "セッションルールに一致",
"Session rules": "セッションルール",
"Session rules table": "セッションルール一覧",
"Session signed out": "セッションからサインアウトしました",
"Sessions & Access": "セッションとアクセス",
"Set": "設定",
@@ -5321,6 +5385,7 @@
"Source name": "ソース名",
"Source vendors": "移動元のプロバイダー",
"Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.": "モデルの割り当てを移した後、移動元のプロバイダーは削除されます。移動先の情報は維持されます。",
"Source: global settings. Changes take effect after saving.": "適用元:全体設定。変更は保存後に反映されます。",
"sources": "ソース",
"Space-separated OAuth scopes": "スペース区切りのOAuthスコープ",
"Spark model version, e.g., v2.1 (version number in API URL)": "Sparkモデルバージョン(例:v2.1、API URLのバージョン番号)",
@@ -5370,6 +5435,8 @@
"Status Code": "ステータスコード",
"Status Code Mapping": "ステータスコードマッピング",
"Status code mapping must use valid HTTP status codes": "ステータスコードマッピングには有効な HTTP ステータスコードを使用する必要があります",
"Status is outside the retry rules": "ステータスが再試行ルールの対象外",
"Status matches the retry rules": "ステータスが再試行ルールに一致",
"Status Page Slug": "ステータスページスラッグ",
"Status short": "状態",
"Status:": "ステータス:",
@@ -5391,6 +5458,7 @@
"Stored value is not echoed back for security": "セキュリティのため、保存済みの値は表示されません",
"stream": "ストリーム",
"Stream": "ストリーム",
"Stream did not complete successfully": "ストリームが正常完了しませんでした",
"Stream Mode": "ストリーミングモード",
"Stream Status": "ストリーム状態",
"Stream tokens incrementally as they are generated": "トークンを生成と同時にストリーミング",
@@ -5432,6 +5500,7 @@
"succeeded": "成功",
"Success": "成功",
"Success rate": "成功率",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "定期または一括テストの成功後、自動無効化されたチャネルを復旧できます。手動で無効にしたチャネルは復旧しません。",
"Successfully created {{count}} API Key(s)": "{{count}}個のAPIキーが正常に作成されました",
"Successfully created {{count}} redemption codes": "{{count}}件の引き換えコードが正常に作成されました",
"Successfully deleted {{count}} API key(s)": "{{count}}個のAPIキーが正常に削除されました",
@@ -5471,6 +5540,7 @@
"Switch to JSON": "JSONに切り替え",
"Switch to Visual": "ビジュアルに切り替え",
"Switch to visual editor": "ビジュアル編集に切り替え",
"Switch to visual mode to add rules or apply templates.": "ルールの追加やテンプレートの適用はビジュアルモードで行えます。",
"Switch to visual pricing?": "ビジュアル料金設定に切り替えますか?",
"Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.": "切り替えると価格表から式が再生成され、元の書式と段階名が置き換わります。変更は保存後に適用されます。",
"Sync Endpoint": "同期エンドポイント",
@@ -5500,6 +5570,7 @@
"System Administration": "システム管理",
"System Announcements": "システムのお知らせ",
"System Behavior": "システムの動作",
"System constraint": "システム制約",
"System data statistics": "システムデータ統計",
"System default": "システムデフォルト",
"System Info": "システム情報",
@@ -5517,6 +5588,7 @@
"System Prompt": "システムプロンプト",
"System Prompt Concatenation": "システムプロンプトの連結",
"System Prompt Override": "システムプロンプト上書き",
"System retry exclusion": "システムによる再試行除外",
"System settings": "システム設定",
"System Settings": "システム設定",
"System setup wizard": "システムセットアップウィザード",
@@ -5551,6 +5623,7 @@
"Task": "タスク",
"Task billing": "タスク課金",
"Task Details": "タスク詳細",
"Task failed": "タスク失敗",
"Task History": "タスク履歴",
"Task ID": "タスクID",
"Task ID:": "タスクID:",
@@ -5659,6 +5732,7 @@
"The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.": "同期により、選択されたソースから不足しているモデルとベンダーが取得されます。既存のレコードは、競合を承認した場合にのみ更新されます。",
"The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.": "システムの内部計算は常に米ドルです。サイト通貨は価格の入力と換算を簡単にするためのもので、金額はサイトの為替レートで米ドルに換算されます。通貨を切り替えても実際の価格は変わりません。課金式の直接編集では常に米ドルを使用します。",
"The system currently uses: {{domain}}": "現在システムが使っている値:{{domain}}",
"The task was accepted; submission cannot be replayed": "タスク受理済みのため再送信不可",
"The Telegram authorization request is invalid or expired.": "Telegram の認証リクエストが無効か、有効期限が切れています。",
"The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.": "OAuth プロバイダー名 telegram は予約されています。管理者に競合するカスタムプロバイダーの名前変更を依頼してください。",
"The token group that will have a custom ratio": "カスタム比率を持つトークングループ",
@@ -5820,6 +5894,7 @@
"Tiered pricing": "階層料金",
"tiers": "階層",
"Time": "時間",
"Time between scheduled channel checks": "定期チャネルチェックの実行間隔",
"Time functions use the timezone written in the expression.": "時刻関数は式で指定されたタイムゾーンを使用します。",
"Time Granularity": "時間の粒度",
"Time range": "時間範囲",
@@ -5933,6 +6008,7 @@
"Total {{count}} records": "全 {{count}} 件",
"Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.": "合計 = 使用済み + 残り。初期の割当量や期間ごとの予算ではありません。残りを変更すると合計と使用率も変わります。",
"Total Allocated": "総割り当て",
"Total attempt budget exhausted": "全試行回数を消費済み",
"Total check-ins": "総チェックイン数",
"Total consumed": "合計消費量",
"Total consumed quota": "合計消費クォータ",
@@ -6028,6 +6104,7 @@
"Unbind": "連携解除",
"Unbind failed": "連携解除に失敗しました",
"Unbound {{provider}}": "{{provider}}の連携を解除しました",
"Unchanged": "変更なし",
"Underflow": "アンダーフロー",
"Underground": "アンダーグラウンド",
"Understand how user groups, token groups, ratios, and special rules work together.": "ユーザーグループ、トークングループ、倍率、特殊ルールがどのように連携するかを理解します。",
@@ -6083,6 +6160,7 @@
"Update the configuration for this custom OAuth provider.": "このカスタムOAuthプロバイダーの設定を更新します。",
"Update the redemption code by providing necessary info.": "必要な情報を提供して、引き換えコードを更新してください。",
"Update the reusable bundle below.": "以下の再利用可能なバンドルを更新してください。",
"Update the session binding after a successful switch": "切り替え成功後にセッションの関連付けを更新",
"Update the user by providing necessary info.": "必要な情報を提供してユーザーを更新します。",
"Update vendor information for {{name}}": "{{name}} のベンダー情報を更新",
"Update your password for account:": "アカウントのパスワードを更新:",
@@ -6148,7 +6226,9 @@
"Upstream prices fetched successfully": "上流価格を正常に取得しました",
"Upstream protocol plan": "上流プロトコルプラン",
"Upstream ratios fetched successfully": "アップストリーム比率が正常に取得されました",
"Upstream request failed": "上流リクエスト失敗",
"Upstream Request ID": "上流リクエストID",
"Upstream response": "上流レスポンス",
"Upstream Response": "アップストリームレスポンス",
"Upstream Response (billing-usage-anthropic-estimated)": "アップストリームレスポンス (billing-usage-anthropic-estimated)",
"Upstream Response (billing-usage-anthropic)": "アップストリームレスポンス (billing-usage-anthropic)",
@@ -6523,6 +6603,7 @@
"with conflicts": "競合あり",
"With linked models": "関連モデルあり",
"with the API key from your token settings.": "をトークン設定の API キーに置き換えてください。",
"With these settings, automatic disabling is off for all channels.": "現在の設定では、すべてのチャネルで自動無効化が無効です。",
"Without additional conditions, only the type above is used for pruning.": "追加条件がない場合、上記のtypeのみが削除に使用されます。",
"Without linked models": "関連モデルなし",
"Worked example": "具体例",
@@ -6586,6 +6667,14 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V 4",
"Zoom": "ズーム"
"Zoom": "ズーム",
"Channel error": "チャネルエラー",
"Unrecognized status code": "認識できないステータスコード",
"Correct the invalid settings before saving.": "無効な設定を修正してから保存してください。",
"Upstream connection": "上流接続",
"Local check": "ローカルチェック",
"Responses WebSocket": "Responses WebSocket",
"Cross-group retry": "グループ横断リトライ",
"Request policy decisions": "リクエストポリシーの判断"
}
}
+92 -3
View File
@@ -53,6 +53,7 @@
"{{count}} FAQ entries will be removed from the list.": "{{count}} записей FAQ будут удалены из списка.",
"{{count}} hours ago": "{{count}} часов назад",
"{{count}} incidents": "{{count}} инцидентов",
"2xx, 504 and 524 are always excluded.": "2xx, 504 и 524 всегда исключены.",
"{{count}} incidents in the last 24 hours": "{{count}} инцидентов за последние 24 часа",
"{{count}} incidents in the last 30 days": "{{count}} инцидентов за последние 30 дней",
"{{count}} IP(s)": "{{count}} IP",
@@ -208,6 +209,7 @@
"Action": "Действие",
"Action confirmation": "Подтверждение действия",
"Actions": "Операции",
"Actions for {{name}}": "Действия для {{name}}",
"Activate / Roll back": "Активировать / Откатить",
"active": "активный",
"Active": "Активна",
@@ -351,6 +353,7 @@
"Advanced text editing": "Расширенное редактирование текста",
"Aesthetic style": "Стиль",
"Affected windows:": "Затронутые окна:",
"Affinity cache settings": "Настройки кеша привязки",
"After clicking the button, you'll be asked to authorize the bot": "После нажатия кнопки вам будет предложено авторизовать бота",
"After conversion": "После преобразования",
"After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.": "После преобразования действуют правила резервирования и округления выражений. Текущие цены за единицу сохраняются, но округлённые суммы отдельных списаний могут отличаться.",
@@ -390,6 +393,7 @@
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "Все названия групп управляются здесь. Коэффициент применяется, когда вызовы тарифицируются по этой группе; коэффициент пополнения применяется к пользователям, состоящим в этой группе.",
"All Groups": "Все группы",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "Все группы используют общий набор имён из таблицы тарифных групп, но одно имя играет две разные роли: как группа пользователя оно описывает пользователя, как группа токена — определяет маршрутизацию и тарификацию.",
"All models": "Все модели",
"All Models": "Все модели",
"All models in use are properly configured.": "Все используемые модели настроены правильно.",
"All Must Match (AND)": "Все должны совпасть (AND)",
@@ -559,6 +563,7 @@
"Apply {{field}} for {{name}}": "Применить {{field}} для {{name}}",
"Apply All Upstream Updates": "Применить все обновления из upstream",
"Apply changes": "Применить изменения",
"Apply disable rules to upstream request errors and scheduled or bulk health checks": "Применять правила отключения к ошибкам провайдера и периодическим или массовым проверкам",
"Apply Filters": "Применить фильтры",
"Apply IP Filter to Resolved Domains": "Применить IP-фильтр к разрешенным доменам",
"Apply Overwrite": "Применить перезапись",
@@ -609,6 +614,7 @@
"At least one model regex pattern is required": "Требуется хотя бы один шаблон регулярного выражения модели",
"At least one valid key source is required": "Требуется хотя бы один действительный источник ключа",
"Attach": "Прикрепить",
"Attempt": "Попытка",
"Audio": "Аудио",
"Audio and Realtime pricing must be converted manually.": "Тарифы аудио и Realtime необходимо преобразовать вручную.",
"Audio and text-only requests keep their respective pricing.": "Для аудио и текстовых запросов сохраняются соответствующие правила расчёта.",
@@ -670,6 +676,8 @@
"Auto refresh (5s)": "Автообновление (5 с)",
"Auto Sync Upstream Models": "Автоматическая синхронизация моделей провайдера",
"Auto-disable channel": "Автоотключение канала",
"Auto-disable disabled": "Автоотключение выключено",
"Auto-disable enabled": "Автоотключение включено",
"Auto-disable rules": "Правила автоотключения",
"Auto-disable status codes": "Коды автоотключения",
"Auto-disable-enabled channels only": "Только каналы с автовыключением",
@@ -965,9 +973,11 @@
"Channel copied successfully": "Канал успешно скопирован",
"Channel created successfully": "Канал успешно создан",
"Channel deleted successfully": "Канал успешно удалён",
"Channel disable requested": "Запрошено отключение канала",
"Channel disabled successfully": "Канал успешно отключён",
"Channel enabled successfully": "Канал успешно включён",
"Channel Extra Settings": "Дополнительные настройки канала",
"Channel health": "Состояние каналов",
"Channel health checks": "Проверки состояния каналов",
"Channel ID": "ID канала",
"Channel ID is required": "Требуется ID канала",
@@ -977,6 +987,9 @@
"Channel Management": "Управление каналами",
"Channel models": "Модели каналов",
"Channel name is required": "Имя канала обязательно",
"Channel selected": "Канал выбран",
"Channel selection": "Выбор канала",
"Channel switching options": "Параметры переключения канала",
"Channel test completed": "Тест канала завершён",
"Channel test concurrency": "Параллельность проверки каналов",
"Channel test concurrency must be between 1 and 32": "Параллельность проверки каналов должна быть от 1 до 32",
@@ -994,6 +1007,7 @@
"Channels {{channels}} · Groups {{groups}}": "Каналы {{channels}} · Группы {{groups}}",
"Channels and groups": "Каналы и группы",
"Channels deleted successfully": "Каналы успешно удалены",
"Channels must also enable Auto Ban before automatic disabling can take effect.": "Для применения правил автоотключение также должно быть включено у самого канала.",
"Character chat, storytelling, persona": "Диалог с персонажем, сторителлинг, персона",
"Charge.": "Списание.",
"Chart Preferences": "Настройки графиков",
@@ -1031,6 +1045,7 @@
"checkout.session.completed": "checkout.session.completed",
"checkout.session.expired": "checkout.session.expired",
"Checks hourly while you are online, including pre-releases.": "Проверка каждый час при подключении к сети, включая предварительные версии.",
"Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.": "Проверяет текст из поддерживаемых запросов по ключевым словам без учёта регистра. Совпадение отклоняет запрос до отправки провайдеру и не влияет на здоровье канала. Изображения, аудио и сгенерированные ответы не проверяются.",
"Chinese": "Китайский",
"Choose a complete upstream protocol plan or edit individual route groups.": "Выберите полную схему протокола поставщика или измените группы маршрутов.",
"Choose a provider or plugin to configure your channel.": "Выберите поставщика или плагин для настройки канала.",
@@ -1514,7 +1529,6 @@
"Creem product ID from your Creem dashboard.": "ID продукта Creem из вашего дашборда Creem.",
"Creem products must be a JSON array": "Продукты Creem должны быть JSON-массивом",
"Cross-group": "Межгрупповой",
"Cross-group retry": "Повтор между группами",
"Cumulative usage": "Суммарное использование",
"Currency": "Валюта",
"Currency & Display": "Валюта и отображение",
@@ -1528,6 +1542,7 @@
"Current email: {{email}}. Enter a new email to change.": "Текущий email: {{email}}. Введите новый email для изменения.",
"Current exchange rate: 1 USD = {{rate}} {{currency}}": "Текущий курс: 1 USD = {{rate}} {{currency}}",
"Current key": "Текущий ключ",
"Current key disable requested": "Запрошено отключение текущего ключа",
"Current legacy JSON is invalid, cannot append": "Текущий JSON старого формата невалиден, добавление невозможно",
"Current Level Only": "Только текущий уровень",
"Current load": "Текущая нагрузка",
@@ -1627,6 +1642,7 @@
"Default placeholder": "Значок по умолчанию",
"Default range": "Диапазон по умолчанию",
"Default Responses API version, if empty, will use the API version above": "Версия API ответов по умолчанию; если пусто, будет использоваться версия API, указанная выше",
"Default session lifetime (seconds)": "Срок сессии по умолчанию (секунды)",
"Default system prompt for this channel": "Системный промпт по умолчанию для этого канала",
"Default time granularity": "Гранулярность времени по умолчанию",
"Default to auto groups": "По умолчанию использовать автогруппы",
@@ -1680,10 +1696,12 @@
"Delete plugin version?": "Удалить версию плагина?",
"Delete Provider": "Удалить провайдер",
"Delete Request Header": "Удалить заголовок запроса",
"Delete Rule": "Удалить правило",
"Delete selected API keys": "Удалить выбранные ключи API",
"Delete selected channels": "Удалить выбранные каналы",
"Delete selected models": "Удалить выбранные модели",
"Delete selected redemption codes": "Удалить выбранные коды погашения",
"Delete session rule “{{name}}”? Save your changes to apply the removal.": "Удалить правило сессии «{{name}}»? Сохраните изменения, чтобы применить удаление.",
"Delete stale instance": "Удалить устаревший экземпляр",
"Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.": "Удалить устаревший экземпляр \"{{name}}\"? Если он снова отправил отчет, он не будет удален.",
"Delete stale instances": "Удалить устаревшие экземпляры",
@@ -1777,6 +1795,7 @@
"Disabled": "Отключено",
"Disabled all channels with tag: {{tag}}": "Все каналы с тегом {{tag}} отключены",
"Disabled channels with tag {{tag}}": "Отключены каналы с тегом {{tag}}",
"Disabled globally": "Отключено глобально",
"Disabled lanes are omitted on save.": "Отключённые каналы цен не сохраняются.",
"Disabled Reason": "Причина отключения",
"Disabled Time": "Время отключения",
@@ -1824,6 +1843,7 @@
"Displayed": "Отображается",
"Displayed in": "Отображается в",
"Displays the mobile sidebar.": "Отображает мобильную боковую панель.",
"Do not keep sessions": "Не сохранять привязку",
"Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.": "Не доверяйте этой функции слишком сильно. IP может быть подделан. Используйте с nginx, CDN и другими шлюзами.",
"Do not repeat check-in; only once per day": "Не повторяйте отметку; только один раз в день",
"Do not wait one second between polling async tasks for this channel": "Не ждать одну секунду между опросами асинхронных задач для этого канала",
@@ -1936,6 +1956,7 @@
"Edit chat preset": "Редактировать пресет чата",
"Edit discount tier": "Редактировать уровень скидки",
"Edit FAQ": "Редактировать FAQ",
"Enable session affinity": "Включить привязку сессии",
"Edit group": "Редактировать группу",
"Edit group rate limit": "Редактировать лимит скорости группы",
"Edit JSON object directly. Suitable for simple parameter overrides.": "Редактируйте JSON-объект напрямую. Подходит для простых переопределений параметров.",
@@ -2112,6 +2133,7 @@
"Enter password (8-20 characters)": "Введите пароль (8-20 символов)",
"Enter password (8–128 characters)": "Введите пароль (8–128 символов)",
"Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.": "Укажите прежние домены, по одному на строку, без протокола, порта и пути. Разные порты одного домена не требуют добавления совместимых доменов.",
"Excludes the first attempt. Counted per group.": "Без первой попытки, отдельно для каждой группы.",
"Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.": "Введите прежние домены ключей доступа, по одному в строке. Существующие ключи продолжат работать с этими доменами, а новые будут использовать основной домен.",
"Enter quota in {{currency}}": "Введите квоту в {{currency}}",
"Enter quota in tokens": "Введите квоту в токенах",
@@ -2333,6 +2355,7 @@
"Failed to load plugins": "Не удалось загрузить плагины",
"Failed to load profile": "Не удалось загрузить профиль",
"Failed to load redemption codes": "Не удалось загрузить коды активации",
"Failed to load settings": "Не удалось загрузить настройки",
"Failed to load setup data": "Не удалось загрузить данные настройки",
"Failed to load setup status": "Не удалось загрузить статус настройки",
"Failed to load SGLang status": "Не удалось загрузить состояние SGLang",
@@ -2374,6 +2397,7 @@
"Failed to set tag": "Не удалось установить тег",
"Failed to setup 2FA": "Не удалось настроить 2FA",
"Failed to show model in model square": "Не удалось отобразить модель в каталоге",
"Fill a CLI template or add a blank rule.": "Заполните шаблон CLI или добавьте пустое правило.",
"Failed to sign out other sessions": "Не удалось завершить другие сеансы",
"Failed to sign out session": "Не удалось завершить сеанс",
"Failed to start {{provider}} login": "Не удалось начать вход через {{provider}}",
@@ -2517,6 +2541,7 @@
"Fix order": "Исправить порядок",
"Fixed": "Исправлено",
"Fixed abilities: {{success}} succeeded, {{fails}} failed": "Согласованность каналов восстановлена: успешно {{success}}, ошибок {{fails}}",
"Fixed channel constraint": "Ограничение фиксированного канала",
"Fixed fee per request": "Фиксированная плата за запрос",
"Fixed price": "Фиксированная цена",
"Fixed price (USD)": "Фиксированная цена (USD)",
@@ -2637,8 +2662,11 @@
"GitHub rate limit reached. Try again later.": "Достигнут лимит запросов GitHub. Повторите попытку позже.",
"Give the group a recognizable name and optional description.": "Дайте группе узнаваемое имя и необязательное описание.",
"Give this group a recognizable name.": "Дайте этой группе узнаваемое имя.",
"Global and channel settings": "Глобальные настройки и настройки канала",
"Global configuration and administrative tools.": "Глобальная конфигурация и административные инструменты.",
"Global Coverage": "Глобальное покрытие",
"Global default": "Глобальное значение по умолчанию",
"Global default: {{mode}}": "Общий режим: {{mode}}",
"Global Model Configuration": "Глобальная конфигурация модели",
"Global throughput": "Общая пропускная способность",
"Go Back": "Назад",
@@ -2686,6 +2714,7 @@
"Group name cannot be changed when editing.": "Имя группы нельзя изменить при редактировании.",
"Group prices cannot be expanded because this expression is not a standard tiered pricing expression.": "Цены по группам нельзя развернуть, потому что это не стандартное выражение тарифов по уровням.",
"Group Pricing": "Тарификация групп",
"How a session is identified and which channel it keeps.": "Как определяется сессия и какой канал она сохраняет.",
"Group pricing usage guide": "Руководство по групповой тарификации",
"group ratio": "коэффициент группы",
"Group Ratio": "Групповой коэффициент",
@@ -2720,6 +2749,7 @@
"Header Value (supports string or JSON mapping)": "Значение заголовка (строка или JSON-маппинг)",
"header. Anthropic-formatted endpoints accept the": ". Эндпоинты формата Anthropic вместо этого принимают",
"Health": "Здоровье",
"Health check timeout threshold (seconds)": "Порог длительности проверки (секунды)",
"Healthy": "В норме",
"Hidden": "Скрыта",
"Hidden — verify to reveal": "Скрыто — подтвердите, чтобы показать",
@@ -2883,6 +2913,7 @@
"Index URL": "URL индекса",
"Information unavailable": "Информация недоступна",
"Inherit global Auto order": "Наследовать глобальный порядок Auto",
"Inherit global default": "Наследовать общий режим",
"Inherit vendor icon": "Использовать иконку поставщика",
"Inherited": "Наследуется",
"Inherited from {{vendor}}": "От поставщика {{vendor}}",
@@ -2953,6 +2984,7 @@
"Invalid response": "Некорректный ответ",
"Invalid rules JSON format": "Неверный формат JSON правил",
"Invalid status code mapping entries: {{entries}}": "Недопустимые записи маппинга кодов состояния: {{entries}}",
"Invalid status code rules": "Недопустимые правила кодов состояния",
"Invalid status code rules: {{tokens}}": "Недопустимые правила кодов состояния: {{tokens}}",
"Invalid vLLM server address": "Некорректный адрес сервера vLLM",
"Invalidate": "Аннулировать",
@@ -2979,6 +3011,7 @@
"IP Whitelist (supports CIDR)": "Белый список IP (поддерживает CIDR)",
"IP: {{ip}} · Method: {{method}}": "IP: {{ip}} · Способ: {{method}}",
"is less than the configured maximum cache size": "меньше настроенного максимального размера кэша",
"Later requests follow the new channel.": "Последующие запросы используют новый канал.",
"is the default price; ": "— цена по умолчанию; ",
"It seems like the page you're looking for": "Похоже, страница, которую вы ищете",
"Items": "Элементы",
@@ -3018,6 +3051,7 @@
"Keep original value (skip if target exists)": "Сохранить исходное значение (пропустить если цель существует)",
"Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.": "Укажите домены существующих ключей доступа, по одному на строку. Если основной домен изменился с www.example.com на example.com, сохраните здесь www.example.com.",
"Keep the platform ready": "Поддерживайте платформу в готовности",
"Keep the session binding when the channel is unavailable": "Сохранять привязку, если канал недоступен",
"Keep this above 1 minute to avoid heavy database load": "Держите это значение выше 1 минуты, чтобы избежать высокой нагрузки на базу данных",
"Keep this vendor": "Сохранить этого поставщика",
"Keep-alive Ping": "Пинг Keep-alive",
@@ -3174,6 +3208,7 @@
"Logo": "Логотип",
"Logo URL": "URL логотипа",
"Logs": "Журналы",
"Maximum retries": "Максимум повторов",
"Long passwords are unavailable until the password storage upgrade is complete.": "Длинные пароли будут доступны после обновления системы хранения паролей.",
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Найдите правило особого коэффициента для этой группы пользователя и тарифной группы. Если оно есть — используется его коэффициент, иначе базовый коэффициент тарифной группы.",
"Low balance": "Низкий баланс",
@@ -3246,6 +3281,7 @@
"Maximum 1000 characters. Supports Markdown and HTML.": "Максимум 1000 символов. Поддерживает Markdown и HTML.",
"Maximum 200 characters": "Максимум 200 символов",
"Maximum 500 characters. Supports Markdown and HTML.": "Максимум 500 символов. Поддерживает Markdown и HTML.",
"Maximum cached sessions": "Максимум сессий в кеше",
"Maximum check-in quota": "Максимальная квота регистрации",
"Maximum custom groups per token": "Максимум пользовательских групп на токен",
"Maximum input window": "Максимальное окно ввода",
@@ -3430,6 +3466,7 @@
"months": "месяцев",
"Moonshot": "Moonshot",
"More": "Ещё",
"More actions": "Другие действия",
"More Apps": "Еще",
"more mapping": "больше сопоставлений",
"More models ({{count}})": "Другие модели ({{count}})",
@@ -3893,6 +3930,7 @@
"Open in New Tab": "Открыть в новой вкладке",
"Open menu": "Открыть меню",
"Open Query Balance to view the upstream JSON response": "Откройте «Запрос баланса», чтобы просмотреть JSON-ответ поставщика",
"Otherwise the binding is removed.": "Иначе привязка удаляется.",
"Open release": "Открыть выпуск",
"Open source": "Открытый исходный код",
"Open Source": "Открытый исходный код",
@@ -4292,6 +4330,7 @@
"Pre-consumed": "Предоплата",
"Pre-Consumed Quota": "Предварительно потребленная квота",
"Pre-release": "Предварительная версия",
"Prefer the original channel, allow switching": "Предпочитать исходный канал, разрешать смену",
"Preference saved as {{pref}}, but no active subscription. Requests will be rejected.": "Настройка сохранена как {{pref}}, но нет активной подписки. Запросы будут отклонены.",
"Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.": "Настройка сохранена как {{pref}}, но нет активной подписки. Кошелёк будет использоваться автоматически.",
"Preferences": "Настройки",
@@ -4424,6 +4463,8 @@
"Prompt Caching": "Кэширование промптов",
"Prompt Details": "Детали промпта",
"Prompt price ($/1M tokens)": "Цена промпта ($/1 млн токенов)",
"Prompt text filtering is active with the current form values.": "При текущих значениях формы фильтрация текста промптов включена.",
"Prompt text filtering needs both switches enabled and a non-empty keyword list.": "Для фильтрации промптов включите оба переключателя и задайте непустой список ключевых слов.",
"Proprietary": "Проприетарная",
"Protect login and registration with Cloudflare Turnstile": "Защитить вход и регистрацию с помощью Cloudflare Turnstile",
"Provide a JSON object where each key maps to an endpoint definition.": "Предоставьте JSON-объект, в котором каждый ключ соответствует определению конечной точки.",
@@ -4587,6 +4628,7 @@
"Redirecting to payment page...": "Перенаправление на страницу оплаты...",
"Redirecting to sign in in {{seconds}} seconds.": "Переход на страницу входа через {{seconds}} сек.",
"Redirects to {{model}}": "Перенаправляется на {{model}}",
"Reduces cache hit rate": "Снижает долю попаданий в кэш",
"Reduces repeated wording": "Уменьшает повторение формулировок",
"Reference Video": "Эталонное видео",
"Referral link:": "Реферальная ссылка:",
@@ -4706,9 +4748,12 @@
"Request Body Memory Cache": "Кэш памяти тела запроса",
"Request body must be a JSON object.": "Тело запроса должно быть объектом JSON.",
"Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.": "Проброс тела запроса включён. Тело запроса будет отправлено напрямую без конвертации.",
"Request checks": "Проверка запросов",
"Request completed": "Запрос завершён",
"Request conversion": "Преобразование запроса",
"Request Conversion": "Конвертация запроса",
"Request Count": "Количество запросов",
"Request decision flow": "Схема решений по запросу",
"Request error occurred": "Произошла ошибка запроса",
"Request failed": "Запрос не выполнен",
"Request flow": "Поток запросов",
@@ -4724,13 +4769,16 @@
"Request names your users call": "Имена запроса, которые вызывают пользователи",
"Request overrides, routing behavior, and upstream model automation": "Переопределения запросов, маршрутизация и автоматизация upstream-моделей",
"Request Path": "Путь запроса",
"Request policies": "Политики запросов",
"Request processing": "Обработка запросов",
"Request rejected locally": "Запрос отклонён локально",
"Request retry": "Повтор запросов",
"Request rule pricing": "Правила ценообразования по запросу",
"Request rules apply on top of this amount.": "Правила запроса применяются дополнительно к этой сумме.",
"Request simulation": "Моделирование запроса",
"Request success rate sampled over the last 24 hours": "Доля успешных запросов по выборкам за последние 24 часа",
"Request success rate; {{incidents}} incident buckets in the last 24 hours": "Доля успешных запросов; {{incidents}} интервалов с инцидентами за последние 24 часа",
"Request text filtering": "Фильтрация текста запросов",
"Request timed out, please refresh and restart GitHub login": "Время ожидания истекло, обновите страницу и снова запустите вход через GitHub",
"Request-based": "Зависит от запроса",
"Requested items": "Запрошенные элементы",
@@ -4750,15 +4798,18 @@
"Requests will be forwarded to this worker. Trailing slashes are removed automatically.": "Запросы будут перенаправлены этому воркеру. Конечные слеши удаляются автоматически.",
"Requests:": "Запросы:",
"Require email verification for new accounts": "Требовать подтверждение электронной почты для новых учетных записей",
"Retry budget": "Бюджет повторов",
"Require job success before follow-up actions": "Требовать успеха задания перед последующими действиями",
"Require login to view models": "Требовать вход для просмотра моделей",
"Require login to view rankings": "Требовать вход для просмотра рейтингов",
"Require the original channel": "Использовать только исходный канал",
"required": "обязателен",
"Required": "Обязательно",
"Required events:": "Обязательные события:",
"Required provider, authentication, model, and group settings": "Обязательные настройки провайдера, аутентификации, моделей и групп",
"Required to expose MjProxy-style image generation to end users.": "Необходимо для предоставления генерации изображений в стиле MjProxy конечным пользователям.",
"Requires an available channel and access to its group.": "Нужен доступный канал и доступ к его группе.",
"Requires global auto-disable and this channel option.": "Нужно включить автоотключение глобально и для этого канала.",
"Requires upstream WebSocket support": "Требуется поддержка WebSocket провайдером",
"Rerank": "Переранжировать",
"Reroll": "Повторить",
@@ -4816,7 +4867,6 @@
"Response time: {{duration}}": "Время ответа: {{duration}}",
"Response too large": "Ответ слишком большой",
"Responses API Version": "Версия API ответов",
"Responses WebSocket": "Responses WebSocket",
"Restore default pricing": "Восстановить цены по умолчанию",
"Restore defaults": "Сбросить к значениям по умолчанию",
"Restore global Auto": "Восстановить глобальный Auto",
@@ -4831,6 +4881,7 @@
"Retry Chain": "Цепочка повторов",
"Retry Settings": "Настройки повторов",
"Retry Suggestion": "Рекомендация по повтору",
"Rules can inherit or override these defaults.": "Правила могут наследовать или переопределять эти значения.",
"Retry Times": "Количество повторных попыток",
"Return a custom error immediately": "Немедленно вернуть пользовательскую ошибку",
"Return Custom Error": "Вернуть пользовательскую ошибку",
@@ -4904,13 +4955,16 @@
"Rule {{line}} prune_objects is missing conditions": "В правиле {{line}} prune_objects отсутствуют условия",
"Rule {{line}} return_error requires a message field": "В правиле {{line}} return_error требуется поле message",
"Rule Description (optional)": "Описание правила (необязательно)",
"Rule editor mode": "Режим редактирования правил",
"Rule group": "Группа правил",
"Rule override": "Настройка правила",
"rules": "правила",
"Rules": "Правила",
"Rules are checked in order. The first match determines the price.": "Правила проверяются по порядку. Первое совпадение определяет цену.",
"Rules JSON": "Правила JSON",
"Rules JSON must be an array": "JSON правил должен быть массивом",
"Rules match the original model value from the client request body.": "Правила сопоставляются с исходным значением model из тела клиентского запроса.",
"Run background checks using the selected test mode": "Выполнять фоновые проверки в выбранном режиме",
"Run dry run": "Пробный запуск",
"Run GC": "Запустить GC",
"Run tests for the selected models": "Запустить тесты для выбранных моделей",
@@ -4982,6 +5036,8 @@
"Scheduled channel tests": "Запланированные тесты канала",
"Scheduled full test": "Полная проверка по расписанию",
"Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.": "Полная проверка по расписанию проверяет каналы, не отключенные вручную; пассивное восстановление проверяет только автоматически отключенные каналы после сбоев реальных запросов.",
"Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.": "Если автоотключение включено глобально и для канала, превышение этой длительности при периодической или массовой проверке может отключить канал.",
"Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.": "Периодическое восстановление отключено. Массовые проверки могут восстановить автоматически отключённые каналы.",
"scheduling controls": "механизмов управления маршрутизацией",
"Science": "Наука",
"Scope": "Область",
@@ -5095,6 +5151,7 @@
"Select locations": "Выбрать локации",
"Select model": "Выбрать модель",
"Select Model": "Выбрать модель",
"Session defaults": "Настройки сеанса по умолчанию",
"Select model {{model}}": "Выбрать модель {{model}}",
"Select models": "Выбрать модели",
"Select models (empty for allow all)": "Выбрать модели (пусто для разрешения всех)",
@@ -5105,6 +5162,7 @@
"Select or enter color value": "Выбрать или ввести значение цвета",
"Select or enter method identifier": "Выберите или введите идентификатор способа",
"Select or enter model name": "Выберите или введите имя модели",
"Sessions and retries": "Сессии и повторы",
"Select or enter payment type": "Выбрать или ввести тип оплаты",
"Select or enter payment type key": "Выберите или введите ключ типа оплаты",
"Select payment method": "Выберите способ оплаты",
@@ -5167,8 +5225,14 @@
"Server Token": "Токен сервера",
"Service account JSON file(s)": "JSON-файл сервисного аккаунта",
"Session": "Сессия",
"Session behavior": "Поведение сессии",
"Session behavior prevents switching channels": "Настройка сессии запрещает переключение каналов",
"Session expired!": "Сессия истекла!",
"Session expired?": "Сессия истекла?",
"Session rule": "Правило сессии",
"Session rule matched": "Совпало правило сессии",
"Session rules": "Правила сессии",
"Session rules table": "Таблица правил сессий",
"Session signed out": "Сеанс завершён",
"Sessions & Access": "Сеансы и доступ",
"Set": "Установить",
@@ -5321,6 +5385,7 @@
"Source name": "Название источника",
"Source vendors": "Исходные поставщики",
"Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.": "После переноса моделей исходные поставщики будут удалены. Данные целевого поставщика сохраняются.",
"Source: global settings. Changes take effect after saving.": "Источник: глобальные настройки. Изменения вступают в силу после сохранения.",
"sources": "источники",
"Space-separated OAuth scopes": "Области доступа OAuth, разделенные пробелами",
"Spark model version, e.g., v2.1 (version number in API URL)": "Версия модели Spark, например, v2.1 (номер версии в URL API)",
@@ -5370,6 +5435,8 @@
"Status Code": "Код статуса",
"Status Code Mapping": "Сопоставление кодов состояния",
"Status code mapping must use valid HTTP status codes": "Сопоставление кодов состояния должно использовать допустимые HTTP-коды",
"Status is outside the retry rules": "Код состояния не входит в правила повторов",
"Status matches the retry rules": "Код состояния соответствует правилам повторов",
"Status Page Slug": "Slug страницы статуса",
"Status short": "Стат.",
"Status:": "Статус:",
@@ -5391,6 +5458,7 @@
"Stored value is not echoed back for security": "В целях безопасности сохранённое значение не отображается",
"stream": "Поток",
"Stream": "Поток",
"Stream did not complete successfully": "Поток не завершился успешно",
"Stream Mode": "Потоковый режим",
"Stream Status": "Статус потока",
"Stream tokens incrementally as they are generated": "Передавать токены по мере их генерации",
@@ -5432,6 +5500,7 @@
"succeeded": "успешно",
"Success": "Успешно",
"Success rate": "Доля успешных запросов",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Успешные периодические или массовые проверки могут восстановить автоматически отключённые каналы. Отключённые вручную остаются отключёнными.",
"Successfully created {{count}} API Key(s)": "Успешно создано {{count}} API-ключ(а/ей)",
"Successfully created {{count}} redemption codes": "Успешно создано {{count}} кодов активации",
"Successfully deleted {{count}} API key(s)": "Успешно удалено {{count}} API-ключ(а/ей)",
@@ -5471,6 +5540,7 @@
"Switch to JSON": "Переключиться на JSON",
"Switch to Visual": "Переключиться на визуальный режим",
"Switch to visual editor": "Перейти к визуальному редактору",
"Switch to visual mode to add rules or apply templates.": "Перейдите в визуальный режим, чтобы добавить правила или применить шаблоны.",
"Switch to visual pricing?": "Перейти к визуальной настройке цен?",
"Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.": "При переключении выражение будет создано заново из таблицы цен. Исходное форматирование и названия уровней будут заменены. Изменения вступят в силу после сохранения.",
"Sync Endpoint": "Конечная точка синхронизации",
@@ -5500,6 +5570,7 @@
"System Administration": "Администрирование системы",
"System Announcements": "Системные объявления",
"System Behavior": "Поведение системы",
"System constraint": "Системное ограничение",
"System data statistics": "Статистика системных данных",
"System default": "По умолчанию",
"System Info": "Информация о системе",
@@ -5517,6 +5588,7 @@
"System Prompt": "Системное приглашение",
"System Prompt Concatenation": "Конкатенация системных промптов",
"System Prompt Override": "Переопределение системного промпта",
"System retry exclusion": "Системный запрет повторов",
"System settings": "Системные настройки",
"System Settings": "Настройки системы",
"System setup wizard": "Мастер настройки системы",
@@ -5551,6 +5623,7 @@
"Task": "Задача",
"Task billing": "Тарификация задач",
"Task Details": "Сведения о задаче",
"Task failed": "Задача не выполнена",
"Task History": "История задач",
"Task ID": "ID задачи",
"Task ID:": "ID задачи:",
@@ -5659,6 +5732,7 @@
"The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.": "Синхронизация получит отсутствующие модели и поставщиков из выбранного источника. Существующие записи обновляются только после подтверждения конфликтов.",
"The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.": "Система всегда рассчитывает стоимость в USD. Валюта сайта упрощает ввод и пересчёт цен; суммы переводятся в USD по курсу сайта. Переключение валюты не меняет фактическую цену. В исходных выражениях тарификации всегда используется USD.",
"The system currently uses: {{domain}}": "Сейчас система использует: {{domain}}",
"The task was accepted; submission cannot be replayed": "Задача принята; повторная отправка запрещена",
"The Telegram authorization request is invalid or expired.": "Запрос авторизации Telegram недействителен или истёк.",
"The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.": "Имя OAuth-провайдера telegram зарезервировано. Попросите администратора переименовать конфликтующего пользовательского провайдера.",
"The token group that will have a custom ratio": "Группа токенов, которая будет иметь пользовательское соотношение",
@@ -5820,6 +5894,7 @@
"Tiered pricing": "Многоуровневая тарификация",
"tiers": "уровни",
"Time": "Время",
"Time between scheduled channel checks": "Интервал между периодическими проверками каналов",
"Time functions use the timezone written in the expression.": "Функции времени используют часовой пояс, указанный в выражении.",
"Time Granularity": "Гранулярность времени",
"Time range": "Временной диапазон",
@@ -5933,6 +6008,7 @@
"Total {{count}} records": "Всего записей: {{count}}",
"Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.": "Итого = использовано + остаток. Это не начальная квота и не бюджет на период. Изменение остатка меняет итог и процент использования.",
"Total Allocated": "Всего выделено",
"Total attempt budget exhausted": "Общий лимит попыток исчерпан",
"Total check-ins": "Общая проверка",
"Total consumed": "Всего использовано",
"Total consumed quota": "Всего использованной квоты",
@@ -6028,6 +6104,7 @@
"Unbind": "Отвязать",
"Unbind failed": "Не удалось отвязать",
"Unbound {{provider}}": "{{provider}} отвязан",
"Unchanged": "Без изменений",
"Underflow": "Переполнение снизу",
"Underground": "Подземелье",
"Understand how user groups, token groups, ratios, and special rules work together.": "Поймите, как вместе работают группы пользователей, группы токенов, коэффициенты и специальные правила.",
@@ -6083,6 +6160,7 @@
"Update the configuration for this custom OAuth provider.": "Обновить конфигурацию этого пользовательского поставщика OAuth.",
"Update the redemption code by providing necessary info.": "Обновите промокод, предоставив необходимую информацию.",
"Update the reusable bundle below.": "Обновите переиспользуемый бандл ниже.",
"Update the session binding after a successful switch": "Обновлять привязку после успешного переключения",
"Update the user by providing necessary info.": "Обновите пользователя, предоставив необходимую информацию.",
"Update vendor information for {{name}}": "Обновить информацию о поставщике для {{name}}",
"Update your password for account:": "Обновите свой пароль для учетной записи:",
@@ -6148,7 +6226,9 @@
"Upstream prices fetched successfully": "Цены провайдера успешно получены",
"Upstream protocol plan": "Схема протокола поставщика",
"Upstream ratios fetched successfully": "Коэффициенты upstream успешно получены",
"Upstream request failed": "Запрос провайдеру не выполнен",
"Upstream Request ID": "ID вышестоящего запроса",
"Upstream response": "Ответ провайдера",
"Upstream Response": "Ответ Upstream",
"Upstream Response (billing-usage-anthropic-estimated)": "Ответ upstream (billing-usage-anthropic-estimated)",
"Upstream Response (billing-usage-anthropic)": "Ответ upstream (billing-usage-anthropic)",
@@ -6523,6 +6603,7 @@
"with conflicts": "с конфликтами",
"With linked models": "Со связанными моделями",
"with the API key from your token settings.": "на API-ключ из настроек токенов.",
"With these settings, automatic disabling is off for all channels.": "При этих настройках автоотключение не действует ни для одного канала.",
"Without additional conditions, only the type above is used for pruning.": "Без дополнительных условий для очистки используется только тип выше.",
"Without linked models": "Без связанных моделей",
"Worked example": "Разобранный пример",
@@ -6586,6 +6667,14 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Channel error": "Ошибка канала",
"Unrecognized status code": "Нераспознанный код состояния",
"Correct the invalid settings before saving.": "Исправьте некорректные настройки перед сохранением.",
"Upstream connection": "Соединение с вышестоящим сервером",
"Local check": "Локальная проверка",
"Responses WebSocket": "Responses WebSocket",
"Cross-group retry": "Повтор между группами",
"Request policy decisions": "Решения политики запросов"
}
}
+92 -3
View File
@@ -53,6 +53,7 @@
"{{count}} FAQ entries will be removed from the list.": "{{count}} mục FAQ sẽ bị xóa khỏi danh sách.",
"{{count}} hours ago": "{{count}} giờ trước",
"{{count}} incidents": "{{count}} sự cố",
"2xx, 504 and 524 are always excluded.": "2xx, 504 và 524 luôn bị loại trừ.",
"{{count}} incidents in the last 24 hours": "{{count}} sự cố trong 24 giờ qua",
"{{count}} incidents in the last 30 days": "{{count}} sự cố trong 30 ngày qua",
"{{count}} IP(s)": "{{count}} IP",
@@ -208,6 +209,7 @@
"Action": "Hành động",
"Action confirmation": "Xác nhận hành động",
"Actions": "Hành động",
"Actions for {{name}}": "Thao tác cho {{name}}",
"Activate / Roll back": "Kích hoạt / Khôi phục",
"active": "hoạt động",
"Active": "Hoạt động",
@@ -351,6 +353,7 @@
"Advanced text editing": "Chỉnh sửa văn bản nâng cao",
"Aesthetic style": "Phong cách",
"Affected windows:": "Cửa sổ bị ảnh hưởng:",
"Affinity cache settings": "Cài đặt bộ nhớ đệm phiên",
"After clicking the button, you'll be asked to authorize the bot": "Sau khi nhấp vào nút, bạn sẽ được yêu cầu ủy quyền cho bot",
"After conversion": "Sau khi chuyển đổi",
"After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.": "Sau khi chuyển đổi, áp dụng quy tắc tạm trừ và làm tròn của biểu thức. Giữ nguyên đơn giá hiện hành nhưng số tiền làm tròn của từng lần tính phí có thể khác.",
@@ -390,6 +393,7 @@
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "Tất cả tên nhóm được quản lý tại đây. Hệ số áp dụng khi cuộc gọi được tính phí theo nhóm này; hệ số nạp tiền áp dụng cho người dùng thuộc nhóm này.",
"All Groups": "Tất cả các nhóm",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "Tất cả các nhóm dùng chung một bộ tên được quản lý trong bảng nhóm định giá, nhưng một tên có hai vai trò khác nhau: là nhóm người dùng thì mô tả người dùng, là nhóm token thì quyết định định tuyến và tính phí.",
"All models": "Tất cả mô hình",
"All Models": "Tất cả các mẫu",
"All models in use are properly configured.": "Tất cả các mô hình đang được sử dụng đều được cấu hình đúng cách.",
"All Must Match (AND)": "Tất cả phải khớp (AND)",
@@ -559,6 +563,7 @@
"Apply {{field}} for {{name}}": "Áp dụng {{field}} cho {{name}}",
"Apply All Upstream Updates": "Áp dụng Tất cả Cập nhật Upstream",
"Apply changes": "Áp dụng thay đổi",
"Apply disable rules to upstream request errors and scheduled or bulk health checks": "Áp dụng quy tắc vô hiệu hóa cho lỗi thượng nguồn và kiểm tra định kỳ hoặc hàng loạt",
"Apply Filters": "Áp dụng bộ lọc",
"Apply IP Filter to Resolved Domains": "Áp dụng Bộ lọc IP cho Tên miền đã phân giải",
"Apply Overwrite": "Áp dụng Ghi đè",
@@ -609,6 +614,7 @@
"At least one model regex pattern is required": "Cần ít nhất một mẫu regex mô hình",
"At least one valid key source is required": "Cần ít nhất một nguồn khóa hợp lệ",
"Attach": "Đính kèm",
"Attempt": "Lần thử",
"Audio": "Âm thanh",
"Audio and Realtime pricing must be converted manually.": "Cần chuyển đổi giá âm thanh và Realtime thủ công.",
"Audio and text-only requests keep their respective pricing.": "Yêu cầu âm thanh và yêu cầu chỉ có văn bản giữ nguyên cách tính phí tương ứng.",
@@ -670,6 +676,8 @@
"Auto refresh (5s)": "Tự làm mới (5 giây)",
"Auto Sync Upstream Models": "Tự động đồng bộ mô hình nguồn",
"Auto-disable channel": "Tự động tắt kênh",
"Auto-disable disabled": "Tự động vô hiệu hóa đã tắt",
"Auto-disable enabled": "Tự động vô hiệu hóa đã bật",
"Auto-disable rules": "Quy tắc tự động tắt",
"Auto-disable status codes": "Mã trạng thái tự tắt",
"Auto-disable-enabled channels only": "Chỉ kênh đã bật tự động vô hiệu hóa",
@@ -965,9 +973,11 @@
"Channel copied successfully": "Sao chép kênh thành công",
"Channel created successfully": "Tạo kênh thành công",
"Channel deleted successfully": "Xóa kênh thành công",
"Channel disable requested": "Đã yêu cầu vô hiệu hóa kênh",
"Channel disabled successfully": "Kênh đã bị vô hiệu hóa thành công",
"Channel enabled successfully": "Kênh đã được bật thành công",
"Channel Extra Settings": "Cài đặt thêm kênh",
"Channel health": "Tình trạng kênh",
"Channel health checks": "Kiểm tra tình trạng kênh",
"Channel ID": "Mã kênh",
"Channel ID is required": "Cần có ID kênh",
@@ -977,6 +987,9 @@
"Channel Management": "Quản lý kênh",
"Channel models": "Mô hình kênh",
"Channel name is required": "Tên kênh là bắt buộc",
"Channel selected": "Đã chọn kênh",
"Channel selection": "Chọn kênh",
"Channel switching options": "Tùy chọn chuyển kênh",
"Channel test completed": "Kiểm tra kênh hoàn tất",
"Channel test concurrency": "Mức đồng thời khi kiểm tra kênh",
"Channel test concurrency must be between 1 and 32": "Mức đồng thời khi kiểm tra kênh phải từ 1 đến 32",
@@ -994,6 +1007,7 @@
"Channels {{channels}} · Groups {{groups}}": "Kênh {{channels}} · Nhóm {{groups}}",
"Channels and groups": "Kênh và nhóm",
"Channels deleted successfully": "Xóa kênh thành công",
"Channels must also enable Auto Ban before automatic disabling can take effect.": "Từng kênh cũng phải bật tự động vô hiệu hóa để quy tắc chung có hiệu lực.",
"Character chat, storytelling, persona": "Trò chuyện nhân vật, kể chuyện, nhân cách hoá",
"Charge.": "Tính phí.",
"Chart Preferences": "Tùy chọn biểu đồ",
@@ -1031,6 +1045,7 @@
"checkout.session.completed": "thanh toán.phiên.hoàn thành",
"checkout.session.expired": "Phiên thanh toán đã hết hạn.",
"Checks hourly while you are online, including pre-releases.": "Kiểm tra mỗi giờ khi trực tuyến, bao gồm các bản phát hành thử.",
"Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.": "Đối chiếu văn bản trích xuất từ yêu cầu được hỗ trợ với từ khóa, không phân biệt hoa thường. Khi khớp, yêu cầu bị từ chối trước khi gửi đến thượng nguồn và không ảnh hưởng tình trạng kênh. Không kiểm tra hình ảnh, âm thanh hay phản hồi được tạo.",
"Chinese": "Tiếng Trung",
"Choose a complete upstream protocol plan or edit individual route groups.": "Chọn cấu hình giao thức thượng nguồn đầy đủ hoặc chỉnh sửa từng nhóm route.",
"Choose a provider or plugin to configure your channel.": "Chọn nhà cung cấp hoặc plugin để cấu hình kênh.",
@@ -1514,7 +1529,6 @@
"Creem product ID from your Creem dashboard.": "ID sản phẩm Creem từ bảng điều khiển Creem của bạn.",
"Creem products must be a JSON array": "Sản phẩm Creem phải là mảng JSON",
"Cross-group": "Liên nhóm",
"Cross-group retry": "Thử lại liên nhóm",
"Cumulative usage": "Mức sử dụng tích lũy",
"Currency": "Tiền tệ",
"Currency & Display": "Tiền tệ & hiển thị",
@@ -1528,6 +1542,7 @@
"Current email: {{email}}. Enter a new email to change.": "Email hiện tại: {{email}}. Nhập email mới để thay đổi.",
"Current exchange rate: 1 USD = {{rate}} {{currency}}": "Tỷ giá hiện tại: 1 USD = {{rate}} {{currency}}",
"Current key": "Khóa hiện tại",
"Current key disable requested": "Đã yêu cầu vô hiệu hóa khóa hiện tại",
"Current legacy JSON is invalid, cannot append": "JSON định dạng cũ hiện tại không hợp lệ, không thể thêm",
"Current Level Only": "Chỉ cấp hiện tại",
"Current load": "Tải hiện tại",
@@ -1627,6 +1642,7 @@
"Default placeholder": "Biểu tượng mặc định",
"Default range": "Khoảng mặc định",
"Default Responses API version, if empty, will use the API version above": "Phiên bản API phản hồi mặc định, nếu để trống, sẽ sử dụng phiên bản API ở trên",
"Default session lifetime (seconds)": "Thời hạn phiên mặc định (giây)",
"Default system prompt for this channel": "Lời nhắc hệ thống mặc định cho kênh này",
"Default time granularity": "Độ chi tiết thời gian mặc định",
"Default to auto groups": "Mặc định là nhóm tự động",
@@ -1680,10 +1696,12 @@
"Delete plugin version?": "Xóa phiên bản plugin?",
"Delete Provider": "Xóa nhà cung cấp",
"Delete Request Header": "Xóa header yêu cầu",
"Delete Rule": "Xóa quy tắc",
"Delete selected API keys": "Xóa các khóa API đã chọn",
"Delete selected channels": "Xóa các kênh đã chọn",
"Delete selected models": "Xóa các mô hình đã chọn",
"Delete selected redemption codes": "Xóa mã quy đổi đã chọn",
"Delete session rule “{{name}}”? Save your changes to apply the removal.": "Xóa quy tắc phiên “{{name}}”? Lưu thay đổi để áp dụng việc xóa.",
"Delete stale instance": "Xóa phiên bản mất kết nối",
"Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.": "Xóa phiên bản mất kết nối \"{{name}}\"? Nếu phiên bản này đã báo cáo lại, nó sẽ không bị xóa.",
"Delete stale instances": "Xóa các phiên bản mất kết nối",
@@ -1777,6 +1795,7 @@
"Disabled": "Đã tắt",
"Disabled all channels with tag: {{tag}}": "Đã tắt tất cả kênh với nhãn: {{tag}}",
"Disabled channels with tag {{tag}}": "Đã vô hiệu hóa các kênh có thẻ {{tag}}",
"Disabled globally": "Đã tắt toàn cục",
"Disabled lanes are omitted on save.": "Các kênh bị tắt sẽ được bỏ qua khi lưu.",
"Disabled Reason": "Lý do vô hiệu hóa",
"Disabled Time": "Thời gian vô hiệu hóa",
@@ -1824,6 +1843,7 @@
"Displayed": "Đang hiển thị",
"Displayed in": "Hiển thị theo",
"Displays the mobile sidebar.": "Hiển thị thanh bên di động.",
"Do not keep sessions": "Không giữ phiên",
"Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.": "Đừng tin tưởng quá mức vào tính năng này. IP có thể bị giả mạo. Hãy sử dụng cùng với nginx, CDN và các gateway khác.",
"Do not repeat check-in; only once per day": "Không lặp lại check-in; chỉ một lần mỗi ngày",
"Do not wait one second between polling async tasks for this channel": "Không chờ một giây giữa các lần thăm dò tác vụ bất đồng bộ cho kênh này",
@@ -1936,6 +1956,7 @@
"Edit chat preset": "Chỉnh sửa cài đặt trước trò chuyện",
"Edit discount tier": "Chỉnh sửa bậc giảm giá",
"Edit FAQ": "Chỉnh sửa câu hỏi thường gặp",
"Enable session affinity": "Bật duy trì phiên",
"Edit group": "Sửa nhóm",
"Edit group rate limit": "Chỉnh sửa giới hạn tốc độ nhóm",
"Edit JSON object directly. Suitable for simple parameter overrides.": "Chỉnh sửa đối tượng JSON trực tiếp. Phù hợp cho ghi đè tham số đơn giản.",
@@ -2112,6 +2133,7 @@
"Enter password (8-20 characters)": "Nhập mật khẩu (8-20 ký tự)",
"Enter password (8–128 characters)": "Nhập mật khẩu (8–128 ký tự)",
"Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.": "Nhập các tên miền cũ, mỗi dòng một tên miền, không kèm giao thức, cổng hay đường dẫn. Các cổng khác nhau trên cùng tên miền không cần thêm vào danh sách tên miền tương thích.",
"Excludes the first attempt. Counted per group.": "Không tính lần đầu, tính theo từng nhóm.",
"Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.": "Nhập các tên miền khóa truy cập cũ, mỗi dòng một tên miền. Các khóa hiện có vẫn xác minh được với những tên miền này; khóa mới dùng tên miền chính.",
"Enter quota in {{currency}}": "Nhập hạn mức bằng {{currency}}",
"Enter quota in tokens": "Nhập hạn mức bằng token",
@@ -2333,6 +2355,7 @@
"Failed to load plugins": "Không thể tải plugin",
"Failed to load profile": "Không thể tải hồ sơ",
"Failed to load redemption codes": "Không thể tải mã đổi thưởng",
"Failed to load settings": "Không thể tải cài đặt",
"Failed to load setup data": "Không thể tải dữ liệu thiết lập",
"Failed to load setup status": "Không thể tải trạng thái thiết lập",
"Failed to load SGLang status": "Không thể tải trạng thái SGLang",
@@ -2374,6 +2397,7 @@
"Failed to set tag": "Không thể đặt thẻ",
"Failed to setup 2FA": "Không thể thiết lập 2FA",
"Failed to show model in model square": "Không thể hiển thị mô hình trong kho mô hình",
"Fill a CLI template or add a blank rule.": "Điền mẫu CLI hoặc thêm quy tắc trống.",
"Failed to sign out other sessions": "Không thể đăng xuất các phiên khác",
"Failed to sign out session": "Không thể đăng xuất phiên",
"Failed to start {{provider}} login": "Không thể bắt đầu đăng nhập {{provider}}",
@@ -2517,6 +2541,7 @@
"Fix order": "Sửa thứ tự",
"Fixed": "Đã sửa",
"Fixed abilities: {{success}} succeeded, {{fails}} failed": "Đã sửa tính nhất quán kênh: {{success}} thành công, {{fails}} thất bại",
"Fixed channel constraint": "Ràng buộc kênh cố định",
"Fixed fee per request": "Phí cố định mỗi yêu cầu",
"Fixed price": "Giá cố định",
"Fixed price (USD)": "Giá cố định (USD)",
@@ -2637,8 +2662,11 @@
"GitHub rate limit reached. Try again later.": "Đã đạt giới hạn yêu cầu GitHub. Vui lòng thử lại sau.",
"Give the group a recognizable name and optional description.": "Đặt cho nhóm một cái tên dễ nhận biết và mô tả tùy chọn.",
"Give this group a recognizable name.": "Hãy đặt cho nhóm này một cái tên dễ nhận biết.",
"Global and channel settings": "Cài đặt toàn cục và kênh",
"Global configuration and administrative tools.": "Cấu hình toàn cục và công cụ quản trị.",
"Global Coverage": "Phạm vi toàn cầu",
"Global default": "Mặc định toàn cục",
"Global default: {{mode}}": "Mặc định toàn cục: {{mode}}",
"Global Model Configuration": "Cấu hình Mô hình Toàn cầu",
"Global throughput": "Thông lượng toàn hệ thống",
"Go Back": "Quay lại",
@@ -2686,6 +2714,7 @@
"Group name cannot be changed when editing.": "Tên nhóm không thể thay đổi khi chỉnh sửa.",
"Group prices cannot be expanded because this expression is not a standard tiered pricing expression.": "Không thể mở rộng giá theo nhóm vì biểu thức này không phải là biểu thức giá theo bậc tiêu chuẩn.",
"Group Pricing": "Định giá nhóm",
"How a session is identified and which channel it keeps.": "Cách nhận diện phiên và kênh mà phiên giữ lại.",
"Group pricing usage guide": "Hướng dẫn sử dụng định giá theo nhóm",
"group ratio": "tỷ lệ nhóm",
"Group Ratio": "Tỷ lệ nhóm",
@@ -2720,6 +2749,7 @@
"Header Value (supports string or JSON mapping)": "Giá trị header (hỗ trợ chuỗi hoặc ánh xạ JSON)",
"header. Anthropic-formatted endpoints accept the": ". Các endpoint định dạng Anthropic chấp nhận header",
"Health": "Sức khỏe",
"Health check timeout threshold (seconds)": "Ngưỡng thời gian kiểm tra (giây)",
"Healthy": "Bình thường",
"Hidden": "Ẩn",
"Hidden — verify to reveal": "Ẩn — xác minh để hiển thị",
@@ -2883,6 +2913,7 @@
"Index URL": "URL chỉ mục",
"Information unavailable": "Chưa đọc được thông tin",
"Inherit global Auto order": "Kế thừa thứ tự Auto toàn cục",
"Inherit global default": "Kế thừa mặc định toàn cục",
"Inherit vendor icon": "Kế thừa biểu tượng nhà cung cấp",
"Inherited": "Kế thừa",
"Inherited from {{vendor}}": "Kế thừa từ {{vendor}}",
@@ -2953,6 +2984,7 @@
"Invalid response": "Phản hồi không hợp lệ",
"Invalid rules JSON format": "Định dạng JSON quy tắc không hợp lệ",
"Invalid status code mapping entries: {{entries}}": "Mục ánh xạ mã trạng thái không hợp lệ: {{entries}}",
"Invalid status code rules": "Quy tắc mã trạng thái không hợp lệ",
"Invalid status code rules: {{tokens}}": "Quy tắc mã trạng thái không hợp lệ: {{tokens}}",
"Invalid vLLM server address": "Địa chỉ máy chủ vLLM không hợp lệ",
"Invalidate": "Vô hiệu hóa",
@@ -2979,6 +3011,7 @@
"IP Whitelist (supports CIDR)": "Danh sách trắng IP (hỗ trợ CIDR)",
"IP: {{ip}} · Method: {{method}}": "IP: {{ip}} · Phương thức: {{method}}",
"is less than the configured maximum cache size": "nhỏ hơn kích thước bộ nhớ đệm tối đa đã cấu hình",
"Later requests follow the new channel.": "Các yêu cầu sau sẽ dùng kênh mới.",
"is the default price; ": "là giá mặc định; ",
"It seems like the page you're looking for": "Có vẻ như trang bạn đang tìm kiếm",
"Items": "Mục",
@@ -3018,6 +3051,7 @@
"Keep original value (skip if target exists)": "Giữ giá trị gốc (bỏ qua nếu đích đã tồn tại)",
"Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.": "Giữ các tên miền mà khóa truy cập hiện có sử dụng, mỗi dòng một tên miền. Nếu tên miền chính đổi từ www.example.com sang example.com, hãy giữ www.example.com tại đây.",
"Keep the platform ready": "Giữ nền tảng luôn sẵn sàng",
"Keep the session binding when the channel is unavailable": "Giữ liên kết phiên khi kênh không khả dụng",
"Keep this above 1 minute to avoid heavy database load": "Giữ cái này trên 1 phút để tránh tải nặng cơ sở dữ liệu",
"Keep this vendor": "Giữ nhà cung cấp này",
"Keep-alive Ping": "Ping duy trì",
@@ -3174,6 +3208,7 @@
"Logo": "Logo",
"Logo URL": "URL Logo",
"Logs": "Nhật ký",
"Maximum retries": "Số lần thử lại tối đa",
"Long passwords are unavailable until the password storage upgrade is complete.": "Mật khẩu dài chỉ khả dụng sau khi hoàn tất nâng cấp hệ thống lưu trữ mật khẩu.",
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "Tìm quy tắc hệ số đặc biệt khớp với nhóm người dùng và nhóm tính phí này. Nếu có thì dùng hệ số của quy tắc, nếu không thì dùng hệ số cơ bản của nhóm tính phí trong bảng định giá.",
"Low balance": "Số dư thấp",
@@ -3246,6 +3281,7 @@
"Maximum 1000 characters. Supports Markdown and HTML.": "Tối đa 1000 ký tự. Hỗ trợ Markdown và HTML.",
"Maximum 200 characters": "Tối đa 200 ký tự",
"Maximum 500 characters. Supports Markdown and HTML.": "Tối đa 500 ký tự. Hỗ trợ Markdown và HTML.",
"Maximum cached sessions": "Số phiên lưu đệm tối đa",
"Maximum check-in quota": "Hạn ngạch điểm danh tối đa",
"Maximum custom groups per token": "Số nhóm tùy chỉnh tối đa cho mỗi token",
"Maximum input window": "Cửa sổ nhập tối đa",
@@ -3430,6 +3466,7 @@
"months": "tháng",
"Moonshot": "Dự án táo bạo",
"More": "Thêm",
"More actions": "Thao tác khác",
"More Apps": "Thêm",
"more mapping": "thêm lập bản đồ",
"More models ({{count}})": "Mô hình khác ({{count}})",
@@ -3893,6 +3930,7 @@
"Open in New Tab": "Mở trong tab mới",
"Open menu": "Mở menu",
"Open Query Balance to view the upstream JSON response": "Mở “Truy vấn số dư” để xem phản hồi JSON thượng nguồn",
"Otherwise the binding is removed.": "Nếu tắt, liên kết sẽ bị xóa.",
"Open release": "Phát hành mở",
"Open source": "Mã nguồn mở",
"Open Source": "Mã nguồn mở",
@@ -4292,6 +4330,7 @@
"Pre-consumed": "Khấu trừ trước",
"Pre-Consumed Quota": "Hạn mức đã tiêu thụ trước",
"Pre-release": "Bản phát hành thử",
"Prefer the original channel, allow switching": "Ưu tiên kênh cũ, cho phép chuyển kênh",
"Preference saved as {{pref}}, but no active subscription. Requests will be rejected.": "Tùy chọn đã lưu là {{pref}}, nhưng không có gói đăng ký đang hoạt động. Các yêu cầu sẽ bị từ chối.",
"Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.": "Tùy chọn đã lưu là {{pref}}, nhưng không có gói đăng ký đang hoạt động. Ví sẽ được sử dụng tự động.",
"Preferences": "Tùy chọn",
@@ -4424,6 +4463,8 @@
"Prompt Caching": "Bộ đệm lời nhắc",
"Prompt Details": "Chi tiết lời nhắc",
"Prompt price ($/1M tokens)": "Giá prompt ($/1 triệu token)",
"Prompt text filtering is active with the current form values.": "Với giá trị biểu mẫu hiện tại, lọc văn bản lời nhắc đang hoạt động.",
"Prompt text filtering needs both switches enabled and a non-empty keyword list.": "Lọc văn bản lời nhắc cần bật cả hai công tắc và có danh sách từ khóa không trống.",
"Proprietary": "Độc quyền",
"Protect login and registration with Cloudflare Turnstile": "Bảo vệ đăng nhập và đăng ký bằng Cloudflare Turnstile",
"Provide a JSON object where each key maps to an endpoint definition.": "Cung cấp một đối tượng JSON nơi mỗi khóa ánh xạ đến một định nghĩa điểm cuối.",
@@ -4587,6 +4628,7 @@
"Redirecting to payment page...": "Đang chuyển hướng đến trang thanh toán...",
"Redirecting to sign in in {{seconds}} seconds.": "Đang chuyển đến trang đăng nhập sau {{seconds}} giây.",
"Redirects to {{model}}": "Chuyển hướng đến {{model}}",
"Reduces cache hit rate": "Làm giảm tỷ lệ trúng bộ nhớ đệm",
"Reduces repeated wording": "Giảm cách diễn đạt lặp lại",
"Reference Video": "Video tham chiếu",
"Referral link:": "Liên kết giới thiệu:",
@@ -4706,9 +4748,12 @@
"Request Body Memory Cache": "Bộ nhớ đệm RAM nội dung yêu cầu",
"Request body must be a JSON object.": "Nội dung yêu cầu phải là một đối tượng JSON.",
"Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.": "Chuyển tiếp body yêu cầu đã được bật. Body yêu cầu sẽ được gửi trực tiếp mà không chuyển đổi.",
"Request checks": "Kiểm tra yêu cầu",
"Request completed": "Yêu cầu hoàn tất",
"Request conversion": "Chuyển đổi yêu cầu",
"Request Conversion": "Chuyển đổi yêu cầu",
"Request Count": "Number of requests",
"Request decision flow": "Luồng quyết định yêu cầu",
"Request error occurred": "Đã xảy ra lỗi yêu cầu",
"Request failed": "Yêu cầu thất bại",
"Request flow": "Luồng yêu cầu",
@@ -4724,13 +4769,16 @@
"Request names your users call": "Tên yêu cầu mà người dùng gọi",
"Request overrides, routing behavior, and upstream model automation": "Ghi đè yêu cầu, hành vi định tuyến và tự động hóa mô hình upstream",
"Request Path": "Đường dẫn yêu cầu",
"Request policies": "Chính sách yêu cầu",
"Request processing": "Xử lý yêu cầu",
"Request rejected locally": "Yêu cầu bị từ chối cục bộ",
"Request retry": "Thử lại yêu cầu",
"Request rule pricing": "Quy tắc tính giá theo request",
"Request rules apply on top of this amount.": "Các quy tắc yêu cầu được áp dụng thêm trên số tiền này.",
"Request simulation": "Mô phỏng yêu cầu",
"Request success rate sampled over the last 24 hours": "Tỷ lệ yêu cầu thành công được lấy mẫu trong 24 giờ qua",
"Request success rate; {{incidents}} incident buckets in the last 24 hours": "Tỷ lệ yêu cầu thành công; {{incidents}} khoảng có sự cố trong 24 giờ qua",
"Request text filtering": "Lọc văn bản yêu cầu",
"Request timed out, please refresh and restart GitHub login": "Yêu cầu đã hết thời gian chờ, vui lòng làm mới và đăng nhập lại GitHub",
"Request-based": "Theo yêu cầu",
"Requested items": "Số mục yêu cầu",
@@ -4750,15 +4798,18 @@
"Requests will be forwarded to this worker. Trailing slashes are removed automatically.": "Các yêu cầu sẽ được chuyển tiếp đến worker này. Dấu gạch chéo ở cuối được tự động loại bỏ.",
"Requests:": "Yêu cầu:",
"Require email verification for new accounts": "Yêu cầu xác minh email cho tài khoản mới",
"Retry budget": "Ngân sách thử lại",
"Require job success before follow-up actions": "Yêu cầu công việc thành công trước các hành động tiếp theo",
"Require login to view models": "Yêu cầu đăng nhập để xem các mô hình",
"Require login to view rankings": "Yêu cầu đăng nhập để xem bảng xếp hạng",
"Require the original channel": "Bắt buộc dùng kênh cũ",
"required": "bắt buộc",
"Required": "Bắt buộc",
"Required events:": "Sự kiện bắt buộc:",
"Required provider, authentication, model, and group settings": "Thiết lập bắt buộc về nhà cung cấp, xác thực, mô hình và nhóm",
"Required to expose MjProxy-style image generation to end users.": "Cần thiết để cung cấp tính năng tạo hình ảnh kiểu MjProxy cho người dùng cuối.",
"Requires an available channel and access to its group.": "Cần có kênh khả dụng và quyền truy cập nhóm tương ứng.",
"Requires global auto-disable and this channel option.": "Cần bật tự động vô hiệu hóa cả toàn cục lẫn kênh này.",
"Requires upstream WebSocket support": "Thượng nguồn phải hỗ trợ WebSocket",
"Rerank": "Re-rank",
"Reroll": "Quay lại",
@@ -4816,7 +4867,6 @@
"Response time: {{duration}}": "Thời gian phản hồi: {{duration}}",
"Response too large": "Phản hồi quá lớn",
"Responses API Version": "Phiên bản API Phản hồi",
"Responses WebSocket": "Responses WebSocket",
"Restore default pricing": "Khôi phục giá mặc định",
"Restore defaults": "Khôi phục mặc định",
"Restore global Auto": "Khôi phục Auto toàn cục",
@@ -4831,6 +4881,7 @@
"Retry Chain": "Chuỗi thử lại",
"Retry Settings": "Cài đặt thử lại",
"Retry Suggestion": "Gợi ý thử lại",
"Rules can inherit or override these defaults.": "Quy tắc có thể kế thừa hoặc ghi đè các mặc định này.",
"Retry Times": "Số lần thử lại",
"Return a custom error immediately": "Trả về lỗi tùy chỉnh ngay lập tức",
"Return Custom Error": "Trả lỗi tùy chỉnh",
@@ -4904,13 +4955,16 @@
"Rule {{line}} prune_objects is missing conditions": "prune_objects của quy tắc {{line}} thiếu điều kiện",
"Rule {{line}} return_error requires a message field": "return_error của quy tắc {{line}} cần trường message",
"Rule Description (optional)": "Mô tả quy tắc (tùy chọn)",
"Rule editor mode": "Chế độ sửa quy tắc",
"Rule group": "Nhóm quy tắc",
"Rule override": "Thiết lập riêng của quy tắc",
"rules": "quy tắc",
"Rules": "Quy tắc",
"Rules are checked in order. The first match determines the price.": "Các quy tắc được xét theo thứ tự. Quy tắc khớp đầu tiên quyết định giá.",
"Rules JSON": "JSON quy tắc",
"Rules JSON must be an array": "JSON quy tắc phải là một mảng",
"Rules match the original model value from the client request body.": "Quy tắc khớp với giá trị model gốc trong thân yêu cầu của client.",
"Run background checks using the selected test mode": "Chạy kiểm tra nền theo chế độ đã chọn",
"Run dry run": "Chạy thử",
"Run GC": "Chạy GC",
"Run tests for the selected models": "Chạy kiểm thử cho các mô hình đã chọn",
@@ -4982,6 +5036,8 @@
"Scheduled channel tests": "Kiểm tra kênh theo lịch trình",
"Scheduled full test": "Kiểm tra toàn bộ theo lịch",
"Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.": "Kiểm tra toàn bộ theo lịch sẽ dò các kênh không bị vô hiệu hóa thủ công; khôi phục thụ động chỉ kiểm tra các kênh bị tự động vô hiệu hóa sau lỗi từ yêu cầu thực tế.",
"Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.": "Nếu bật tự động vô hiệu hóa cả ở cấp chung và cấp kênh, kiểm tra định kỳ hoặc hàng loạt vượt thời gian này có thể vô hiệu hóa kênh.",
"Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.": "Khôi phục định kỳ đang tắt. Kiểm tra hàng loạt vẫn có thể bật lại các kênh bị tự động vô hiệu hóa.",
"scheduling controls": "điều khiển điều phối",
"Science": "Khoa học",
"Scope": "Phạm vi",
@@ -5095,6 +5151,7 @@
"Select locations": "Chọn vị trí",
"Select model": "Chọn mô hình",
"Select Model": "Chọn mẫu",
"Session defaults": "Mặc định phiên",
"Select model {{model}}": "Chọn mô hình {{model}}",
"Select models": "Chọn các mô hình",
"Select models (empty for allow all)": "Chọn model (để trống nếu muốn cho",
@@ -5105,6 +5162,7 @@
"Select or enter color value": "Chọn hoặc nhập giá trị màu",
"Select or enter method identifier": "Chọn hoặc nhập mã định danh phương thức",
"Select or enter model name": "Chọn hoặc nhập tên mô hình",
"Sessions and retries": "Phiên và thử lại",
"Select or enter payment type": "Chọn hoặc nhập loại thanh toán",
"Select or enter payment type key": "Chọn hoặc nhập khóa loại thanh toán",
"Select payment method": "Chọn phương thức thanh toán",
@@ -5167,8 +5225,14 @@
"Server Token": "Mã thông báo máy chủ",
"Service account JSON file(s)": "Tệp JSON tài khoản dịch vụ",
"Session": "Phiên",
"Session behavior": "Giữ phiên",
"Session behavior prevents switching channels": "Cài đặt duy trì phiên ngăn việc chuyển kênh",
"Session expired!": "Phiên hết hạn!",
"Session expired?": "Phiên đã hết hạn?",
"Session rule": "Quy tắc phiên",
"Session rule matched": "Khớp quy tắc phiên",
"Session rules": "Quy tắc phiên",
"Session rules table": "Bảng quy tắc phiên",
"Session signed out": "Đã đăng xuất phiên",
"Sessions & Access": "Phiên và truy cập",
"Set": "Đặt",
@@ -5321,6 +5385,7 @@
"Source name": "Tên nguồn",
"Source vendors": "Nhà cung cấp nguồn",
"Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.": "Nhà cung cấp nguồn sẽ bị xóa sau khi chuyển mô hình. Thông tin nhà cung cấp đích được giữ nguyên.",
"Source: global settings. Changes take effect after saving.": "Nguồn: cài đặt chung. Thay đổi có hiệu lực sau khi lưu.",
"sources": "nguồn",
"Space-separated OAuth scopes": "Phạm vi OAuth phân cách bằng dấu cách",
"Spark model version, e.g., v2.1 (version number in API URL)": "Phiên bản mô hình Spark, ví dụ: v2.1 (số phiên bản trong URL API)",
@@ -5370,6 +5435,8 @@
"Status Code": "Mã trạng thái",
"Status Code Mapping": "Ánh xạ mã trạng thái",
"Status code mapping must use valid HTTP status codes": "Ánh xạ mã trạng thái phải dùng mã trạng thái HTTP hợp lệ",
"Status is outside the retry rules": "Mã trạng thái ngoài quy tắc thử lại",
"Status matches the retry rules": "Mã trạng thái khớp quy tắc thử lại",
"Status Page Slug": "Đường dẫn phụ trang trạng thái",
"Status short": "TT",
"Status:": "Trạng thái:",
@@ -5391,6 +5458,7 @@
"Stored value is not echoed back for security": "Vì bảo mật, giá trị đã lưu không được hiển thị lại",
"stream": "dòng",
"Stream": "Luồng",
"Stream did not complete successfully": "Luồng không hoàn tất thành công",
"Stream Mode": "Chế độ streaming",
"Stream Status": "Trạng thái luồng",
"Stream tokens incrementally as they are generated": "Truyền dần token khi được tạo",
@@ -5432,6 +5500,7 @@
"succeeded": "thành công",
"Success": "Thành công",
"Success rate": "Tỷ lệ thành công",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "Kiểm tra định kỳ hoặc hàng loạt thành công có thể khôi phục kênh bị tự động vô hiệu hóa. Kênh tắt thủ công vẫn bị tắt.",
"Successfully created {{count}} API Key(s)": "Đã tạo thành công {{count}} khóa API",
"Successfully created {{count}} redemption codes": "Đã tạo thành công {{count}} mã đổi thưởng",
"Successfully deleted {{count}} API key(s)": "Đã xóa thành công {{count}} khóa API",
@@ -5471,6 +5540,7 @@
"Switch to JSON": "Chuyển sang JSON",
"Switch to Visual": "Chuyển sang Trực quan",
"Switch to visual editor": "Chuyển sang trình sửa trực quan",
"Switch to visual mode to add rules or apply templates.": "Chuyển sang chế độ trực quan để thêm quy tắc hoặc áp dụng mẫu.",
"Switch to visual pricing?": "Chuyển sang định giá trực quan?",
"Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.": "Khi chuyển, biểu thức sẽ được tạo lại từ bảng giá, thay thế định dạng và tên bậc ban đầu. Thay đổi chỉ có hiệu lực sau khi lưu.",
"Sync Endpoint": "Điểm cuối đồng bộ",
@@ -5500,6 +5570,7 @@
"System Administration": "Quản trị hệ thống",
"System Announcements": "Thông báo hệ thống",
"System Behavior": "Hành vi hệ thống",
"System constraint": "Ràng buộc hệ thống",
"System data statistics": "Thống kê dữ liệu hệ thống",
"System default": "Mặc định hệ thống",
"System Info": "Thông tin hệ thống",
@@ -5517,6 +5588,7 @@
"System Prompt": "Lời nhắc hệ thống",
"System Prompt Concatenation": "Ghép nối Lời nhắc Hệ thống",
"System Prompt Override": "Ghi đè prompt hệ thống",
"System retry exclusion": "Trường hợp hệ thống không cho thử lại",
"System settings": "Cài đặt hệ thống",
"System Settings": "Cài đặt hệ thống",
"System setup wizard": "Trình hướng dẫn thiết lập hệ thống",
@@ -5551,6 +5623,7 @@
"Task": "Nhiệm vụ",
"Task billing": "Tính phí tác vụ",
"Task Details": "Chi tiết tác vụ",
"Task failed": "Tác vụ thất bại",
"Task History": "Lịch sử tác vụ",
"Task ID": "Mã nhiệm vụ",
"Task ID:": "ID nhiệm vụ:",
@@ -5659,6 +5732,7 @@
"The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.": "Đồng bộ hóa sẽ tìm nạp các mẫu và nhà cung cấp còn thiếu từ nguồn đã chọn. Các bản ghi hiện có chỉ được cập nhật khi bạn chấp thuận các xung đột.",
"The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.": "Hệ thống luôn tính phí bằng USD. Tiền tệ trang web giúp nhập và quy đổi giá thuận tiện hơn; số tiền được quy đổi sang USD theo tỷ giá của trang web. Đổi tiền tệ không làm thay đổi giá thực tế. Biểu thức tính phí gốc luôn dùng USD.",
"The system currently uses: {{domain}}": "Hệ thống hiện đang dùng: {{domain}}",
"The task was accepted; submission cannot be replayed": "Tác vụ đã nhận; không thể gửi lại",
"The Telegram authorization request is invalid or expired.": "Yêu cầu ủy quyền Telegram không hợp lệ hoặc đã hết hạn.",
"The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.": "Tên nhà cung cấp OAuth telegram đã được dành riêng. Hãy nhờ quản trị viên đổi tên nhà cung cấp tùy chỉnh bị trùng.",
"The token group that will have a custom ratio": "The token group will have a custom ratio.",
@@ -5820,6 +5894,7 @@
"Tiered pricing": "Định giá theo tầng",
"tiers": "tầng",
"Time": "Thời gian",
"Time between scheduled channel checks": "Khoảng thời gian giữa các lần kiểm tra kênh định kỳ",
"Time functions use the timezone written in the expression.": "Các hàm thời gian sử dụng múi giờ được chỉ định trong biểu thức.",
"Time Granularity": "Độ chi tiết thời gian",
"Time range": "Khoảng thời gian",
@@ -5933,6 +6008,7 @@
"Total {{count}} records": "Tổng cộng {{count}} bản ghi",
"Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.": "Tổng = đã dùng + còn lại, không phải hạn mức ban đầu hay ngân sách định kỳ. Thay đổi phần còn lại sẽ thay đổi tổng và tỷ lệ đã dùng.",
"Total Allocated": "Tổng phân bổ",
"Total attempt budget exhausted": "Đã hết tổng số lần thử",
"Total check-ins": "Tổng số lần điểm danh",
"Total consumed": "Tổng tiêu thụ",
"Total consumed quota": "Tổng hạn ngạch đã tiêu thụ",
@@ -6028,6 +6104,7 @@
"Unbind": "Hủy liên kết",
"Unbind failed": "Hủy liên kết thất bại",
"Unbound {{provider}}": "Đã hủy liên kết {{provider}}",
"Unchanged": "Không đổi",
"Underflow": "Tràn dưới",
"Underground": "Underground",
"Understand how user groups, token groups, ratios, and special rules work together.": "Hiểu cách nhóm người dùng, nhóm token, tỷ lệ và quy tắc đặc biệt hoạt động cùng nhau.",
@@ -6083,6 +6160,7 @@
"Update the configuration for this custom OAuth provider.": "Cập nhật cấu hình cho nhà cung cấp OAuth tùy chỉnh này.",
"Update the redemption code by providing necessary info.": "Cập nhật mã đổi thưởng bằng cách cung cấp thông tin cần thiết.",
"Update the reusable bundle below.": "Cập nhật gói có thể tái sử dụng bên dưới.",
"Update the session binding after a successful switch": "Cập nhật liên kết phiên sau khi chuyển thành công",
"Update the user by providing necessary info.": "Cập nhật cho người dùng bằng cách cung cấp thông tin cần thiết.",
"Update vendor information for {{name}}": "Cập nhật thông tin nhà cung cấp cho {{name}}",
"Update your password for account:": "Cập nhật mật khẩu của bạn cho tài khoản:",
@@ -6148,7 +6226,9 @@
"Upstream prices fetched successfully": "Lấy giá upstream thành công",
"Upstream protocol plan": "Cấu hình giao thức thượng nguồn",
"Upstream ratios fetched successfully": "Đã lấy tỷ lệ upstream thành công",
"Upstream request failed": "Yêu cầu lên nguồn thất bại",
"Upstream Request ID": "ID yêu cầu thượng nguồn",
"Upstream response": "Phản hồi nguồn",
"Upstream Response": "Upstream feedback",
"Upstream Response (billing-usage-anthropic-estimated)": "Phản hồi upstream (billing-usage-anthropic-estimated)",
"Upstream Response (billing-usage-anthropic)": "Phản hồi upstream (billing-usage-anthropic)",
@@ -6523,6 +6603,7 @@
"with conflicts": "với các xung đột",
"With linked models": "Có mô hình liên kết",
"with the API key from your token settings.": "bằng API key từ trang Tokens của bạn.",
"With these settings, automatic disabling is off for all channels.": "Với cài đặt này, tự động vô hiệu hóa không có hiệu lực với bất kỳ kênh nào.",
"Without additional conditions, only the type above is used for pruning.": "Không có điều kiện bổ sung, chỉ type ở trên được sử dụng để dọn dẹp.",
"Without linked models": "Không có mô hình liên kết",
"Worked example": "Ví dụ minh họa",
@@ -6586,6 +6667,14 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Channel error": "Lỗi kênh",
"Unrecognized status code": "Mã trạng thái không xác định",
"Correct the invalid settings before saving.": "Hãy sửa các cài đặt không hợp lệ trước khi lưu.",
"Upstream connection": "Kết nối thượng nguồn",
"Local check": "Kiểm tra cục bộ",
"Responses WebSocket": "Responses WebSocket",
"Cross-group retry": "Thử lại liên nhóm",
"Request policy decisions": "Quyết định chính sách yêu cầu"
}
}
+92 -3
View File
@@ -53,6 +53,7 @@
"{{count}} FAQ entries will be removed from the list.": "將從列表中移除 {{count}} 個 FAQ 條目。",
"{{count}} hours ago": "{{count}} 小時前",
"{{count}} incidents": "{{count}} 宗事件",
"2xx, 504 and 524 are always excluded.": "2xx、504、524 一律排除。",
"{{count}} incidents in the last 24 hours": "最近 24 小時 {{count}} 個異常桶",
"{{count}} incidents in the last 30 days": "最近 30 天 {{count}} 宗事件",
"{{count}} IP(s)": "{{count}} 個 IP",
@@ -208,6 +209,7 @@
"Action": "操作",
"Action confirmation": "操作確認",
"Actions": "操作",
"Actions for {{name}}": "{{name}} 的操作",
"Activate / Roll back": "激活 / 回滚",
"active": "活躍",
"Active": "生效",
@@ -351,6 +353,7 @@
"Advanced text editing": "進階文字編輯",
"Aesthetic style": "畫風",
"Affected windows:": "影響窗口:",
"Affinity cache settings": "工作階段快取設定",
"After clicking the button, you'll be asked to authorize the bot": "點擊按鈕後,您將被要求授權機器人",
"After conversion": "轉換後",
"After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.": "轉換後採用計費運算式的預扣與捨入規則。保留目前生效單價,單筆捨入後的費用可能不同。",
@@ -390,6 +393,7 @@
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "所有分組名稱都在這裡管理。倍率在呼叫按該分組收費時生效;儲值倍率對所屬該分組的用戶生效。",
"All Groups": "所有分組",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "所有分組共用定價分組表中的同一批名稱,但同一個名稱有兩種角色:作為用戶分組表示用戶身份,作為令牌分組決定路由和收費。",
"All models": "所有模型",
"All Models": "所有模型",
"All models in use are properly configured.": "所有正在使用的模型都已正確設定。",
"All Must Match (AND)": "全部滿足(AND)",
@@ -559,6 +563,7 @@
"Apply {{field}} for {{name}}": "為 {{name}} 套用{{field}}",
"Apply All Upstream Updates": "套用所有上游更新",
"Apply changes": "套用變更",
"Apply disable rules to upstream request errors and scheduled or bulk health checks": "將停用規則套用於上游請求錯誤,以及定時或批次健康檢查",
"Apply Filters": "套用篩選器",
"Apply IP Filter to Resolved Domains": "對已解析的網域套用 IP 篩選器",
"Apply Overwrite": "套用覆蓋",
@@ -609,6 +614,7 @@
"At least one model regex pattern is required": "至少需要一個模型正則匹配模式",
"At least one valid key source is required": "至少需要一個有效的金鑰來源",
"Attach": "附加",
"Attempt": "嘗試",
"Audio": "音頻",
"Audio and Realtime pricing must be converted manually.": "音訊及 Realtime 定價需手動轉換。",
"Audio and text-only requests keep their respective pricing.": "音訊請求和純文字請求分別沿用原計費規則。",
@@ -670,6 +676,8 @@
"Auto refresh (5s)": "自動重新整理(5秒)",
"Auto Sync Upstream Models": "自動同步上游模型",
"Auto-disable channel": "異常自動停用",
"Auto-disable disabled": "不參與自動停用",
"Auto-disable enabled": "參與自動停用",
"Auto-disable rules": "自動停用規則",
"Auto-disable status codes": "自動停用狀態碼",
"Auto-disable-enabled channels only": "僅測試已啟用自動停用的渠道",
@@ -965,9 +973,11 @@
"Channel copied successfully": "渠道複製成功",
"Channel created successfully": "渠道建立成功",
"Channel deleted successfully": "渠道刪除成功",
"Channel disable requested": "已要求停用通道",
"Channel disabled successfully": "渠道停用成功",
"Channel enabled successfully": "渠道啟用成功",
"Channel Extra Settings": "渠道額外設定",
"Channel health": "渠道健康",
"Channel health checks": "渠道健康檢查",
"Channel ID": "渠道 ID",
"Channel ID is required": "缺少渠道 ID",
@@ -977,6 +987,9 @@
"Channel Management": "渠道管理",
"Channel models": "渠道模型",
"Channel name is required": "渠道名稱是必填的",
"Channel selected": "選擇通道",
"Channel selection": "通道選擇",
"Channel switching options": "渠道切換子選項",
"Channel test completed": "渠道測試完成",
"Channel test concurrency": "渠道測試並行數",
"Channel test concurrency must be between 1 and 32": "渠道測試並行數必須介於 1 到 32 之間",
@@ -994,6 +1007,7 @@
"Channels {{channels}} · Groups {{groups}}": "渠道 {{channels}} · 群組 {{groups}}",
"Channels and groups": "渠道與分組",
"Channels deleted successfully": "渠道刪除成功",
"Channels must also enable Auto Ban before automatic disabling can take effect.": "各渠道還需開啟「自動停用」,全域停用規則才會對其生效。",
"Character chat, storytelling, persona": "角色對話、劇情創作、人設扮演",
"Charge.": "扣費。",
"Chart Preferences": "圖表偏好設定",
@@ -1031,6 +1045,7 @@
"checkout.session.completed": "checkout.session.completed",
"checkout.session.expired": "checkout.session.expired",
"Checks hourly while you are online, including pre-releases.": "連線時每小時檢查一次,包含預先發行版本。",
"Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.": "對支援的請求中擷取的文字進行關鍵詞比對,不區分大小寫。符合時在傳送上游前拒絕請求,不影響渠道健康狀態。不檢查圖片、音訊或產生的回應內容。",
"Chinese": "中文",
"Choose a complete upstream protocol plan or edit individual route groups.": "選擇完整的上游協議方案,或逐組編輯路由。",
"Choose a provider or plugin to configure your channel.": "選擇供應商或外掛,開始設定通道。",
@@ -1514,7 +1529,6 @@
"Creem product ID from your Creem dashboard.": "從您的 Creem 儀表板獲取 Creem 產品 ID。",
"Creem products must be a JSON array": "Creem 產品必須是 JSON 陣列",
"Cross-group": "跨分組",
"Cross-group retry": "跨分組重試",
"Cumulative usage": "累計用量",
"Currency": "貨幣",
"Currency & Display": "貨幣與展示",
@@ -1528,6 +1542,7 @@
"Current email: {{email}}. Enter a new email to change.": "目前電郵:{{email}}。輸入新電郵以更改。",
"Current exchange rate: 1 USD = {{rate}} {{currency}}": "目前匯率:1 USD = {{rate}} {{currency}}",
"Current key": "目前金鑰",
"Current key disable requested": "已要求停用目前金鑰",
"Current legacy JSON is invalid, cannot append": "目前舊格式 JSON 不合法,無法追加模板",
"Current Level Only": "僅目前層",
"Current load": "目前負載",
@@ -1627,6 +1642,7 @@
"Default placeholder": "預設佔位圖示",
"Default range": "預設範圍",
"Default Responses API version, if empty, will use the API version above": "預設回應 API 版本,如果為空,將使用上面的 API 版本",
"Default session lifetime (seconds)": "預設工作階段有效期(秒)",
"Default system prompt for this channel": "此渠道的預設系統提示",
"Default time granularity": "預設時間粒度",
"Default to auto groups": "預設使用自動分組",
@@ -1680,10 +1696,12 @@
"Delete plugin version?": "刪除外掛版本?",
"Delete Provider": "刪除供應商",
"Delete Request Header": "刪除請求頭",
"Delete Rule": "刪除規則",
"Delete selected API keys": "刪除選定的 API 金鑰",
"Delete selected channels": "刪除所選渠道",
"Delete selected models": "刪除選定的模型",
"Delete selected redemption codes": "刪除選取的兌換碼",
"Delete session rule “{{name}}”? Save your changes to apply the removal.": "刪除工作階段規則「{{name}}」?儲存變更後生效。",
"Delete stale instance": "刪除失聯實例",
"Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.": "刪除失聯實例「{{name}}」?如果它已重新上報,將不會被刪除。",
"Delete stale instances": "刪除失聯實例",
@@ -1777,6 +1795,7 @@
"Disabled": "已停用",
"Disabled all channels with tag: {{tag}}": "已停用標籤「{{tag}}」下的所有渠道",
"Disabled channels with tag {{tag}}": "停用標籤為 {{tag}} 的渠道",
"Disabled globally": "全域已停用",
"Disabled lanes are omitted on save.": "關閉的價格通道儲存時會被省略。",
"Disabled Reason": "停用原因",
"Disabled Time": "停用時間",
@@ -1824,6 +1843,7 @@
"Displayed": "正常顯示",
"Displayed in": "顯示單位",
"Displays the mobile sidebar.": "顯示流動側邊欄。",
"Do not keep sessions": "不保持",
"Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.": "請勿過度信任此功能,IP 可能被偽造,請配合 nginx 和 cdn 等閘道使用",
"Do not repeat check-in; only once per day": "請勿重複簽到;每天僅一次",
"Do not wait one second between polling async tasks for this channel": "該渠道輪詢異步任務時不等待一秒",
@@ -1936,6 +1956,7 @@
"Edit chat preset": "編輯聊天預設",
"Edit discount tier": "編輯折扣檔位",
"Edit FAQ": "編輯常見問題",
"Enable session affinity": "啟用工作階段保持",
"Edit group": "編輯分組",
"Edit group rate limit": "編輯組速率限制",
"Edit JSON object directly. Suitable for simple parameter overrides.": "直接編輯 JSON 物件。適合簡單覆蓋參數的場景。",
@@ -2112,6 +2133,7 @@
"Enter password (8-20 characters)": "輸入密碼(8-20 個字元)",
"Enter password (8–128 characters)": "輸入密碼(8–128 個字元)",
"Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.": "每行填寫一個舊網域,不包含通訊協定、連接埠或路徑。同一網域的不同連接埠無須加入相容清單。",
"Excludes the first attempt. Counted per group.": "不含首次,依分組計算。",
"Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.": "每行填寫一個舊通行金鑰網域。現有通行金鑰仍可透過這些網域驗證,新通行金鑰使用主要網域。",
"Enter quota in {{currency}}": "輸入 {{currency}} 額度",
"Enter quota in tokens": "輸入令牌配額",
@@ -2333,6 +2355,7 @@
"Failed to load plugins": "載入外掛失敗",
"Failed to load profile": "載入個人資料失敗",
"Failed to load redemption codes": "載入兌換碼失敗",
"Failed to load settings": "載入設定失敗",
"Failed to load setup data": "無法載入設定數據",
"Failed to load setup status": "無法載入設定狀態",
"Failed to load SGLang status": "載入 SGLang 狀態失敗",
@@ -2374,6 +2397,7 @@
"Failed to set tag": "設定標籤失敗",
"Failed to setup 2FA": "設定 2FA 失敗",
"Failed to show model in model square": "在模型廣場顯示失敗",
"Fill a CLI template or add a blank rule.": "填充 CLI 範本,或新增空白規則。",
"Failed to sign out other sessions": "登出其他工作階段失敗",
"Failed to sign out session": "登出工作階段失敗",
"Failed to start {{provider}} login": "啟動 {{provider}} 登入失敗",
@@ -2517,6 +2541,7 @@
"Fix order": "修復順序",
"Fixed": "修復",
"Fixed abilities: {{success}} succeeded, {{fails}} failed": "渠道一致性修復完成:{{success}} 個成功,{{fails}} 個失敗",
"Fixed channel constraint": "固定通道限制",
"Fixed fee per request": "每次請求固定費用",
"Fixed price": "固定價格",
"Fixed price (USD)": "固定價格 (USD)",
@@ -2637,8 +2662,11 @@
"GitHub rate limit reached. Try again later.": "已達到 GitHub 請求限制,請稍後重試。",
"Give the group a recognizable name and optional description.": "為該分組提供一個可識別的名稱和可選的描述。",
"Give this group a recognizable name.": "為此分組提供一個可識別的名稱。",
"Global and channel settings": "全域與通道設定",
"Global configuration and administrative tools.": "全局設定和管理工具。",
"Global Coverage": "全球覆蓋",
"Global default": "全域預設",
"Global default: {{mode}}": "全域預設:{{mode}}",
"Global Model Configuration": "全局模型設定",
"Global throughput": "全局吞吐量",
"Go Back": "返回",
@@ -2686,6 +2714,7 @@
"Group name cannot be changed when editing.": "編輯時無法更改組名稱。",
"Group prices cannot be expanded because this expression is not a standard tiered pricing expression.": "該表達式不是標準分檔收費表達式,無法展開分組價格。",
"Group Pricing": "分組定價",
"How a session is identified and which channel it keeps.": "定義如何識別工作階段及其使用的通道。",
"Group pricing usage guide": "分組定價使用教學",
"group ratio": "分組倍率",
"Group Ratio": "分組倍率",
@@ -2720,6 +2749,7 @@
"Header Value (supports string or JSON mapping)": "請求頭值(支援字串或 JSON 映射)",
"header. Anthropic-formatted endpoints accept the": " 請求頭。Anthropic 格式的端點也接受",
"Health": "健康",
"Health check timeout threshold (seconds)": "健康檢查耗時門檻(秒)",
"Healthy": "正常",
"Hidden": "屏蔽",
"Hidden — verify to reveal": "隱藏 — 驗證以顯示",
@@ -2883,6 +2913,7 @@
"Index URL": "索引 URL",
"Information unavailable": "暫時無法讀取",
"Inherit global Auto order": "繼承全域 Auto 順序",
"Inherit global default": "沿用全域預設",
"Inherit vendor icon": "繼承供應商圖示",
"Inherited": "繼承",
"Inherited from {{vendor}}": "繼承自 {{vendor}}",
@@ -2953,6 +2984,7 @@
"Invalid response": "回應無效",
"Invalid rules JSON format": "規則 JSON 格式不正確",
"Invalid status code mapping entries: {{entries}}": "無效的狀態碼映射條目:{{entries}}",
"Invalid status code rules": "狀態碼規則無效",
"Invalid status code rules: {{tokens}}": "無效的狀態碼規則:{{tokens}}",
"Invalid vLLM server address": "vLLM 服務位址無效",
"Invalidate": "作廢",
@@ -2979,6 +3011,7 @@
"IP Whitelist (supports CIDR)": "IP 白名單(支援 CIDR 表達式)",
"IP: {{ip}} · Method: {{method}}": "IP:{{ip}} · 登入方式:{{method}}",
"is less than the configured maximum cache size": "小於設定的最大緩存大小",
"Later requests follow the new channel.": "後續請求改用新渠道。",
"is the default price; ": "為預設價格;",
"It seems like the page you're looking for": "您要查找的頁面似乎",
"Items": "條目",
@@ -3018,6 +3051,7 @@
"Keep original value (skip if target exists)": "保留原值(目標已有值時不覆蓋)",
"Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.": "每行填寫一個既有通行金鑰使用的網域。例如,主要網域從 www.example.com 改為 example.com 後,應在此保留 www.example.com。",
"Keep the platform ready": "保持平台就緒",
"Keep the session binding when the channel is unavailable": "渠道無法使用時保留工作階段綁定",
"Keep this above 1 minute to avoid heavy database load": "保持此值大於 1 分鐘以避免資料庫負載過重",
"Keep this vendor": "保留此供應商",
"Keep-alive Ping": "保持連線心跳",
@@ -3174,6 +3208,7 @@
"Logo": "徽標",
"Logo URL": "徽標 URL",
"Logs": "日誌",
"Maximum retries": "最多重試次數",
"Long passwords are unavailable until the password storage upgrade is complete.": "密碼儲存升級完成前暫不支援長密碼。",
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "查找匹配「該用戶分組 + 該收費分組」的特殊倍率規則。有就用規則裡的倍率,沒有就用定價分組表中收費分組的基礎倍率。",
"Low balance": "餘額偏低",
@@ -3246,6 +3281,7 @@
"Maximum 1000 characters. Supports Markdown and HTML.": "最多 1000 個字元。支援 Markdown 和 HTML。",
"Maximum 200 characters": "最多 200 個字元",
"Maximum 500 characters. Supports Markdown and HTML.": "最多 500 個字元。支援 Markdown 和 HTML。",
"Maximum cached sessions": "最多快取工作階段數",
"Maximum check-in quota": "簽到最大額度",
"Maximum custom groups per token": "每個令牌的最大自訂分組數",
"Maximum input window": "最大輸入窗口",
@@ -3430,6 +3466,7 @@
"months": "個月",
"Moonshot": "Moonshot",
"More": "更多",
"More actions": "更多操作",
"More Apps": "更多",
"more mapping": "更多映射",
"More models ({{count}})": "更多模型({{count}})",
@@ -3893,6 +3930,7 @@
"Open in New Tab": "在新標籤頁中打開",
"Open menu": "打開選單",
"Open Query Balance to view the upstream JSON response": "請開啟「查詢餘額」檢視上游 JSON 回應",
"Otherwise the binding is removed.": "關閉時清除該綁定。",
"Open release": "打開版本",
"Open source": "開源",
"Open Source": "開源項目",
@@ -4292,6 +4330,7 @@
"Pre-consumed": "預扣費",
"Pre-Consumed Quota": "預消耗配額",
"Pre-release": "預先發行版",
"Prefer the original channel, allow switching": "優先原通道,失敗允許切換",
"Preference saved as {{pref}}, but no active subscription. Requests will be rejected.": "已儲存偏好為{{pref}},目前無生效訂閱,請求將被拒絕",
"Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.": "已儲存偏好為{{pref}},目前無生效訂閱,將自動使用錢包",
"Preferences": "偏好設定",
@@ -4424,6 +4463,8 @@
"Prompt Caching": "提示詞緩存",
"Prompt Details": "提示詞詳情",
"Prompt price ($/1M tokens)": "提示詞價格(美元/100 萬 token)",
"Prompt text filtering is active with the current form values.": "依目前表單設定,提示詞文字過濾已生效。",
"Prompt text filtering needs both switches enabled and a non-empty keyword list.": "提示詞文字過濾需要同時開啟兩個開關,並設定非空的敏感詞清單。",
"Proprietary": "商業閉源",
"Protect login and registration with Cloudflare Turnstile": "使用 Cloudflare Turnstile 保護登入和註冊",
"Provide a JSON object where each key maps to an endpoint definition.": "提供一個 JSON 物件,其中每個鍵映射到一個端點定義。",
@@ -4587,6 +4628,7 @@
"Redirecting to payment page...": "正在重新導向到支付頁面...",
"Redirecting to sign in in {{seconds}} seconds.": "將在 {{seconds}} 秒後跳轉到登入頁。",
"Redirects to {{model}}": "重新導向至 {{model}}",
"Reduces cache hit rate": "會降低快取命中率",
"Reduces repeated wording": "減少重複措辭",
"Reference Video": "參照生影片",
"Referral link:": "推薦連結:",
@@ -4706,9 +4748,12 @@
"Request Body Memory Cache": "請求體記憶體緩存",
"Request body must be a JSON object.": "請求主體必須是 JSON 物件。",
"Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.": "請求體透傳已啟用。請求體將直接傳送到上游,不進行任何轉換。",
"Request checks": "請求檢查",
"Request completed": "請求已完成",
"Request conversion": "請求轉換",
"Request Conversion": "請求轉換",
"Request Count": "請求計數",
"Request decision flow": "請求決策流程",
"Request error occurred": "請求發生錯誤",
"Request failed": "請求失敗",
"Request flow": "請求流",
@@ -4724,13 +4769,16 @@
"Request names your users call": "使用者呼叫的請求模型名稱",
"Request overrides, routing behavior, and upstream model automation": "請求覆蓋、路由行為和上游模型自動化",
"Request Path": "請求路徑",
"Request policies": "請求策略",
"Request processing": "請求處理",
"Request rejected locally": "請求在本機被拒絕",
"Request retry": "請求重試",
"Request rule pricing": "請求規則收費",
"Request rules apply on top of this amount.": "請求規則會在此金額之上繼續套用。",
"Request simulation": "請求模擬",
"Request success rate sampled over the last 24 hours": "最近 24 小時按時間桶採樣的請求成功率",
"Request success rate; {{incidents}} incident buckets in the last 24 hours": "請求成功率;最近 24 小時 {{incidents}} 個異常桶",
"Request text filtering": "請求文字過濾",
"Request timed out, please refresh and restart GitHub login": "請求逾時,請重新整理頁面後重新發起 GitHub 登入",
"Request-based": "含請求條件",
"Requested items": "請求項數",
@@ -4750,15 +4798,18 @@
"Requests will be forwarded to this worker. Trailing slashes are removed automatically.": "請求將被轉發到此 Worker。最後的斜線會自動移除。",
"Requests:": "請求:",
"Require email verification for new accounts": "要求新用戶驗證電郵",
"Retry budget": "重試預算",
"Require job success before follow-up actions": "在後續操作前要求任務成功",
"Require login to view models": "要求登入才能查看模型",
"Require login to view rankings": "要求登入才能查看排行榜",
"Require the original channel": "必須使用原通道",
"required": "必填",
"Required": "必需",
"Required events:": "必需事件:",
"Required provider, authentication, model, and group settings": "必填的供應商、鑒權、模型和分組設定",
"Required to expose MjProxy-style image generation to end users.": "需要向終端用戶開放 MjProxy 風格的圖像生成。",
"Requires an available channel and access to its group.": "仍需有可用渠道,並符合使用者群組存取條件。",
"Requires global auto-disable and this channel option.": "需同時開啟全域自動停用和本通道開關。",
"Requires upstream WebSocket support": "需上游支援 WebSocket",
"Rerank": "重新排序",
"Reroll": "重繪",
@@ -4816,7 +4867,6 @@
"Response time: {{duration}}": "回應時間:{{duration}}",
"Response too large": "回應過大",
"Responses API Version": "回應 API 版本",
"Responses WebSocket": "Responses WebSocket",
"Restore default pricing": "還原預設定價",
"Restore defaults": "恢復預設",
"Restore global Auto": "恢復全域 Auto",
@@ -4831,6 +4881,7 @@
"Retry Chain": "重試鏈路",
"Retry Settings": "重試設定",
"Retry Suggestion": "重試建議",
"Rules can inherit or override these defaults.": "規則可沿用或單獨覆寫。",
"Retry Times": "重試次數",
"Return a custom error immediately": "立即返回自訂錯誤",
"Return Custom Error": "返回自訂錯誤",
@@ -4904,13 +4955,16 @@
"Rule {{line}} prune_objects is missing conditions": "第 {{line}} 條 prune_objects 缺少條件",
"Rule {{line}} return_error requires a message field": "第 {{line}} 條 return_error 需要 message 欄位",
"Rule Description (optional)": "規則描述(可選)",
"Rule editor mode": "規則編輯模式",
"Rule group": "規則組",
"Rule override": "規則獨立設定",
"rules": "規則",
"Rules": "規則",
"Rules are checked in order. The first match determines the price.": "按順序比對規則,首條符合的規則決定價格。",
"Rules JSON": "規則 JSON",
"Rules JSON must be an array": "規則 JSON 必須是陣列",
"Rules match the original model value from the client request body.": "規則匹配客戶端請求體裡的原始 model 值。",
"Run background checks using the selected test mode": "依所選檢查模式在背景執行檢查",
"Run dry run": "執行試跑",
"Run GC": "執行 GC",
"Run tests for the selected models": "執行所選模型的測試",
@@ -4982,6 +5036,8 @@
"Scheduled channel tests": "定期渠道測試",
"Scheduled full test": "定時全量測試",
"Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.": "定時全量測試會探測非手動停用的渠道;僅被動恢復只會在真實請求失敗導致渠道自動停用後檢查這些渠道是否可恢復。",
"Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.": "全域與渠道自動停用均開啟時,定時或批次健康檢查耗時超過此門檻可觸發停用。",
"Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.": "定時恢復未執行,批次測試仍可恢復被自動停用的渠道。",
"scheduling controls": "調度控制能力",
"Science": "科研",
"Scope": "作用域",
@@ -5095,6 +5151,7 @@
"Select locations": "選擇位置",
"Select model": "選擇模型",
"Select Model": "選擇模型",
"Session defaults": "工作階段預設",
"Select model {{model}}": "選擇模型 {{model}}",
"Select models": "選擇模型",
"Select models (empty for allow all)": "選擇模型(留空表示允許所有)",
@@ -5105,6 +5162,7 @@
"Select or enter color value": "選擇或輸入顏色值",
"Select or enter method identifier": "選擇或輸入支付方式標識",
"Select or enter model name": "選擇或輸入模型名稱",
"Sessions and retries": "工作階段與重試",
"Select or enter payment type": "選擇或輸入支付類型",
"Select or enter payment type key": "選擇或輸入支付處理標識",
"Select payment method": "選擇支付方式",
@@ -5167,8 +5225,14 @@
"Server Token": "伺服器令牌",
"Service account JSON file(s)": "服務賬號 JSON 檔案",
"Session": "對話",
"Session behavior": "工作階段保持",
"Session behavior prevents switching channels": "工作階段保持設定禁止切換渠道",
"Session expired!": "對話已過期!",
"Session expired?": "對話已過期?",
"Session rule": "工作階段規則",
"Session rule matched": "命中工作階段規則",
"Session rules": "工作階段規則",
"Session rules table": "工作階段規則表格",
"Session signed out": "已登出此工作階段",
"Sessions & Access": "工作階段與存取",
"Set": "設定",
@@ -5321,6 +5385,7 @@
"Source name": "來源名稱",
"Source vendors": "來源供應商",
"Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.": "模型歸屬轉移後將刪除來源供應商。目標供應商的資料維持原值。",
"Source: global settings. Changes take effect after saving.": "來源:全域設定。修改後儲存生效。",
"sources": "來源",
"Space-separated OAuth scopes": "以空格分隔的OAuth作用域",
"Spark model version, e.g., v2.1 (version number in API URL)": "Spark 模型版本,例如 v2.1(API URL 中的版本號)",
@@ -5370,6 +5435,8 @@
"Status Code": "狀態碼",
"Status Code Mapping": "狀態碼映射",
"Status code mapping must use valid HTTP status codes": "狀態碼映射必須使用有效的 HTTP 狀態碼",
"Status is outside the retry rules": "狀態碼未命中重試規則",
"Status matches the retry rules": "狀態碼命中重試規則",
"Status Page Slug": "狀態頁面 Slug",
"Status short": "狀態",
"Status:": "狀態:",
@@ -5391,6 +5458,7 @@
"Stored value is not echoed back for security": "出於安全考慮,已儲存的值不會回顯",
"stream": "流",
"Stream": "流",
"Stream did not complete successfully": "串流輸出未成功完成",
"Stream Mode": "串流模式",
"Stream Status": "流狀態",
"Stream tokens incrementally as they are generated": "在生成過程中按 token 逐步串流返回",
@@ -5432,6 +5500,7 @@
"succeeded": "已成功",
"Success": "成功",
"Success rate": "成功率",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "定時或批次檢查成功後,可恢復被自動停用的渠道;人工停用的渠道保持停用。",
"Successfully created {{count}} API Key(s)": "成功建立了 {{count}} 個 API 金鑰",
"Successfully created {{count}} redemption codes": "成功建立了 {{count}} 個兌換碼",
"Successfully deleted {{count}} API key(s)": "成功刪除了 {{count}} 個 API 金鑰",
@@ -5471,6 +5540,7 @@
"Switch to JSON": "切換到 JSON",
"Switch to Visual": "切換到可視化",
"Switch to visual editor": "切換至視覺化編輯",
"Switch to visual mode to add rules or apply templates.": "切換至視覺化模式後,可新增規則或套用範本。",
"Switch to visual pricing?": "切換至視覺化定價?",
"Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.": "切換後將根據價格表重新產生運算式,取代原始寫法和級距名稱。變更將在儲存後生效。",
"Sync Endpoint": "同步端點",
@@ -5500,6 +5570,7 @@
"System Administration": "系統管理",
"System Announcements": "系統公告",
"System Behavior": "系統行為",
"System constraint": "系統限制",
"System data statistics": "系統數據統計",
"System default": "系統預設",
"System Info": "系統資訊",
@@ -5517,6 +5588,7 @@
"System Prompt": "系統提示詞",
"System Prompt Concatenation": "系統提示詞連接",
"System Prompt Override": "系統提示覆蓋",
"System retry exclusion": "系統禁止重試的情況",
"System settings": "系統設定",
"System Settings": "系統設定",
"System setup wizard": "系統設定精靈",
@@ -5551,6 +5623,7 @@
"Task": "任務",
"Task billing": "任務計費",
"Task Details": "任務詳情",
"Task failed": "任務失敗",
"Task History": "歷史任務",
"Task ID": "任務 ID",
"Task ID:": "任務 ID:",
@@ -5659,6 +5732,7 @@
"The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.": "同步將從選定的源獲取缺失的模型和供應商。僅在您批准衝突時才會更新現有記錄。",
"The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.": "系統底層統一使用美元計價。選擇站點貨幣是為了方便輸入和換算,金額會按站點匯率轉換為美元。切換貨幣不會改變實際價格;原始計費表達式一律使用美元。",
"The system currently uses: {{domain}}": "系統目前使用:{{domain}}",
"The task was accepted; submission cannot be replayed": "任務已接受,無法重複提交",
"The Telegram authorization request is invalid or expired.": "Telegram 授權要求無效或已過期。",
"The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.": "telegram 是保留的 OAuth 提供方名稱,請聯絡管理員重新命名衝突的自訂提供方。",
"The token group that will have a custom ratio": "將具有自訂比例的令牌分組",
@@ -5820,6 +5894,7 @@
"Tiered pricing": "階梯收費",
"tiers": "檔",
"Time": "時間",
"Time between scheduled channel checks": "定時渠道檢查的執行間隔",
"Time functions use the timezone written in the expression.": "時間函數使用運算式中指定的時區。",
"Time Granularity": "時間粒度",
"Time range": "時間範圍",
@@ -5933,6 +6008,7 @@
"Total {{count}} records": "共 {{count}} 筆記錄",
"Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.": "總額度 = 已用 + 剩餘,並非初始額度或週期預算。修改剩餘額度會改變總額度和已用比例。",
"Total Allocated": "總分配",
"Total attempt budget exhausted": "整次嘗試次數已耗盡",
"Total check-ins": "累計簽到",
"Total consumed": "總消耗",
"Total consumed quota": "總消耗額度",
@@ -6028,6 +6104,7 @@
"Unbind": "解綁",
"Unbind failed": "解綁失敗",
"Unbound {{provider}}": "已解綁 {{provider}}",
"Unchanged": "不變",
"Underflow": "下溢",
"Underground": "暗夜",
"Understand how user groups, token groups, ratios, and special rules work together.": "了解用戶分組、令牌分組、倍率和特殊規則如何共同生效。",
@@ -6083,6 +6160,7 @@
"Update the configuration for this custom OAuth provider.": "更新此自訂 OAuth 供應商的設定。",
"Update the redemption code by providing necessary info.": "透過提供必要資訊更新兌換碼。",
"Update the reusable bundle below.": "更新下面的可重用捆綁包。",
"Update the session binding after a successful switch": "切換成功後更新工作階段綁定",
"Update the user by providing necessary info.": "透過提供必要資訊更新用戶。",
"Update vendor information for {{name}}": "更新 {{name}} 的供應商資訊",
"Update your password for account:": "更新用戶密碼:",
@@ -6148,7 +6226,9 @@
"Upstream prices fetched successfully": "已成功獲取上游價格",
"Upstream protocol plan": "上游協議方案",
"Upstream ratios fetched successfully": "上游比率獲取成功",
"Upstream request failed": "上游請求失敗",
"Upstream Request ID": "上游請求 ID",
"Upstream response": "上游回應",
"Upstream Response": "上游返回",
"Upstream Response (billing-usage-anthropic-estimated)": "上游返回(billing-usage-anthropic-estimated)",
"Upstream Response (billing-usage-anthropic)": "上游返回(billing-usage-anthropic)",
@@ -6523,6 +6603,7 @@
"with conflicts": "有衝突",
"With linked models": "有關聯模型",
"with the API key from your token settings.": "替換為令牌設定中的 API Key。",
"With these settings, automatic disabling is off for all channels.": "依目前設定,所有渠道的自動停用均不生效。",
"Without additional conditions, only the type above is used for pruning.": "未新增附加條件時,僅使用上方 type 進行清理。",
"Without linked models": "無關聯模型",
"Worked example": "完整示例",
@@ -6586,6 +6667,14 @@
"Zhipu": "智譜",
"Zhipu GLM": "智譜GLM",
"Zhipu V4": "智譜 V4",
"Zoom": "縮放"
"Zoom": "縮放",
"Channel error": "通道錯誤",
"Unrecognized status code": "無法識別的狀態碼",
"Correct the invalid settings before saving.": "請修正無效設定後再儲存。",
"Upstream connection": "上游連線",
"Local check": "本地檢查",
"Responses WebSocket": "Responses WebSocket",
"Cross-group retry": "跨分組重試",
"Request policy decisions": "請求策略決策"
}
}
+92 -3
View File
@@ -53,6 +53,7 @@
"{{count}} FAQ entries will be removed from the list.": "将从列表中移除 {{count}} 个 FAQ 条目。",
"{{count}} hours ago": "{{count}} 小时前",
"{{count}} incidents": "{{count}} 起事件",
"2xx, 504 and 524 are always excluded.": "2xx、504、524 始终排除。",
"{{count}} incidents in the last 24 hours": "最近 24 小时 {{count}} 个异常桶",
"{{count}} incidents in the last 30 days": "最近 30 天 {{count}} 起事件",
"{{count}} IP(s)": "{{count}} 个 IP",
@@ -208,6 +209,7 @@
"Action": "操作",
"Action confirmation": "操作确认",
"Actions": "操作",
"Actions for {{name}}": "{{name}} 的操作",
"Activate / Roll back": "激活 / 回滚",
"active": "活跃",
"Active": "生效",
@@ -351,6 +353,7 @@
"Advanced text editing": "高级文本编辑",
"Aesthetic style": "画风",
"Affected windows:": "影响窗口:",
"Affinity cache settings": "会话缓存设置",
"After clicking the button, you'll be asked to authorize the bot": "点击按钮后,您将被要求授权机器人",
"After conversion": "迁移后",
"After conversion, expression reservation and rounding rules apply. Effective unit prices are preserved; individual rounded charges may differ.": "转换后采用计费表达式的预扣与舍入规则。保留当前生效单价,单笔舍入后的费用可能不同。",
@@ -390,6 +393,7 @@
"All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.": "所有分组名称都在这里管理。倍率在调用按该分组计费时生效;充值倍率对所属该分组的用户生效。",
"All Groups": "所有分组",
"All groups share one pool of names managed in the pricing group table, but a name plays two different roles: as a user group it describes the user, as a token group it decides routing and billing.": "所有分组共用定价分组表中的同一批名称,但同一个名称有两种角色:作为用户分组表示用户身份,作为令牌分组决定路由和计费。",
"All models": "所有模型",
"All Models": "所有模型",
"All models in use are properly configured.": "所有正在使用的模型都已正确配置。",
"All Must Match (AND)": "全部满足(AND)",
@@ -559,6 +563,7 @@
"Apply {{field}} for {{name}}": "为 {{name}} 应用{{field}}",
"Apply All Upstream Updates": "应用所有上游更新",
"Apply changes": "应用更改",
"Apply disable rules to upstream request errors and scheduled or bulk health checks": "将停用规则应用于上游请求错误,以及定时或批量健康检查",
"Apply Filters": "应用筛选器",
"Apply IP Filter to Resolved Domains": "对已解析的域应用 IP 筛选器",
"Apply Overwrite": "应用覆盖",
@@ -609,6 +614,7 @@
"At least one model regex pattern is required": "至少需要一个模型正则匹配模式",
"At least one valid key source is required": "至少需要一个有效的密钥来源",
"Attach": "附加",
"Attempt": "尝试",
"Audio": "音频",
"Audio and Realtime pricing must be converted manually.": "音频及 Realtime 定价需手动转换。",
"Audio and text-only requests keep their respective pricing.": "音频请求和纯文本请求分别沿用原计费规则。",
@@ -670,6 +676,8 @@
"Auto refresh (5s)": "自动刷新(5秒)",
"Auto Sync Upstream Models": "自动同步上游模型",
"Auto-disable channel": "异常自动禁用",
"Auto-disable disabled": "不参与自动停用",
"Auto-disable enabled": "参与自动停用",
"Auto-disable rules": "自动禁用规则",
"Auto-disable status codes": "自动禁用状态码",
"Auto-disable-enabled channels only": "仅测试已开启自动禁用的渠道",
@@ -965,9 +973,11 @@
"Channel copied successfully": "渠道复制成功",
"Channel created successfully": "渠道创建成功",
"Channel deleted successfully": "渠道删除成功",
"Channel disable requested": "已请求停用渠道",
"Channel disabled successfully": "渠道禁用成功",
"Channel enabled successfully": "渠道启用成功",
"Channel Extra Settings": "渠道额外设置",
"Channel health": "渠道健康",
"Channel health checks": "渠道健康检查",
"Channel ID": "渠道 ID",
"Channel ID is required": "缺少渠道 ID",
@@ -977,6 +987,9 @@
"Channel Management": "渠道管理",
"Channel models": "渠道模型",
"Channel name is required": "渠道名称是必填的",
"Channel selected": "选择渠道",
"Channel selection": "渠道选择",
"Channel switching options": "渠道切换子选项",
"Channel test completed": "渠道测试完成",
"Channel test concurrency": "渠道测试并发数",
"Channel test concurrency must be between 1 and 32": "渠道测试并发数必须在 1 到 32 之间",
@@ -994,6 +1007,7 @@
"Channels {{channels}} · Groups {{groups}}": "渠道 {{channels}} · 分组 {{groups}}",
"Channels and groups": "渠道与分组",
"Channels deleted successfully": "渠道删除成功",
"Channels must also enable Auto Ban before automatic disabling can take effect.": "各渠道还需开启“自动禁用”,全局禁用规则才会对其生效。",
"Character chat, storytelling, persona": "角色对话、剧情创作、人设扮演",
"Charge.": "扣费。",
"Chart Preferences": "图表偏好设置",
@@ -1031,6 +1045,7 @@
"checkout.session.completed": "checkout.session.completed",
"checkout.session.expired": "checkout.session.expired",
"Checks hourly while you are online, including pre-releases.": "在线时每小时检查一次,包含预发布版本。",
"Checks text extracted from supported requests against keywords, ignoring case. A match rejects the request before upstream processing and does not affect channel health. Images, audio and generated responses are not checked.": "对支持的请求中提取的文本进行关键词匹配,不区分大小写。命中后在发送上游前拒绝请求,不影响渠道健康状态。不检查图片、音频或生成的响应内容。",
"Chinese": "中文",
"Choose a complete upstream protocol plan or edit individual route groups.": "选择完整的上游协议方案,或逐组编辑路由。",
"Choose a provider or plugin to configure your channel.": "选择提供商或插件,开始配置渠道。",
@@ -1514,7 +1529,6 @@
"Creem product ID from your Creem dashboard.": "从您的 Creem 仪表板获取 Creem 产品 ID。",
"Creem products must be a JSON array": "Creem 产品必须是 JSON 数组",
"Cross-group": "跨分组",
"Cross-group retry": "跨分组重试",
"Cumulative usage": "累计用量",
"Currency": "货币",
"Currency & Display": "货币与展示",
@@ -1528,6 +1542,7 @@
"Current email: {{email}}. Enter a new email to change.": "当前邮箱:{{email}}。输入新邮箱以更改。",
"Current exchange rate: 1 USD = {{rate}} {{currency}}": "当前汇率:1 USD = {{rate}} {{currency}}",
"Current key": "当前密钥",
"Current key disable requested": "已请求停用当前密钥",
"Current legacy JSON is invalid, cannot append": "当前旧格式 JSON 不合法,无法追加模板",
"Current Level Only": "仅当前层",
"Current load": "当前负载",
@@ -1627,6 +1642,7 @@
"Default placeholder": "默认占位图标",
"Default range": "默认范围",
"Default Responses API version, if empty, will use the API version above": "默认响应 API 版本,如果为空,将使用上面的 API 版本",
"Default session lifetime (seconds)": "默认会话有效期(秒)",
"Default system prompt for this channel": "此渠道的默认系统提示",
"Default time granularity": "默认时间粒度",
"Default to auto groups": "默认使用自动分组",
@@ -1680,10 +1696,12 @@
"Delete plugin version?": "删除插件版本?",
"Delete Provider": "删除提供商",
"Delete Request Header": "删除请求头",
"Delete Rule": "删除规则",
"Delete selected API keys": "删除选定的 API 密钥",
"Delete selected channels": "删除所选渠道",
"Delete selected models": "删除选定的模型",
"Delete selected redemption codes": "删除选中的兑换码",
"Delete session rule “{{name}}”? Save your changes to apply the removal.": "删除会话规则“{{name}}”?保存更改后生效。",
"Delete stale instance": "删除失联实例",
"Delete stale instance \"{{name}}\"? If it has reported again, it will not be deleted.": "删除失联实例 \"{{name}}\"?如果它已经重新上报,将不会被删除。",
"Delete stale instances": "删除失联实例",
@@ -1777,6 +1795,7 @@
"Disabled": "已禁用",
"Disabled all channels with tag: {{tag}}": "已禁用标签「{{tag}}」下的所有渠道",
"Disabled channels with tag {{tag}}": "禁用标签为 {{tag}} 的渠道",
"Disabled globally": "全局已禁用",
"Disabled lanes are omitted on save.": "关闭的价格通道保存时会被省略。",
"Disabled Reason": "禁用原因",
"Disabled Time": "禁用时间",
@@ -1824,6 +1843,7 @@
"Displayed": "正常展示",
"Displayed in": "显示单位",
"Displays the mobile sidebar.": "显示移动侧边栏。",
"Do not keep sessions": "不保持",
"Do not over-trust this feature. IP may be spoofed. Please use with nginx, CDN and other gateways.": "请勿过度信任此功能,IP 可能被伪造,请配合 nginx 和 cdn 等网关使用",
"Do not repeat check-in; only once per day": "请勿重复签到;每天仅一次",
"Do not wait one second between polling async tasks for this channel": "该渠道轮询异步任务时不等待一秒",
@@ -1936,6 +1956,7 @@
"Edit chat preset": "编辑聊天预设",
"Edit discount tier": "编辑折扣档位",
"Edit FAQ": "编辑常见问题",
"Enable session affinity": "启用会话保持",
"Edit group": "编辑分组",
"Edit group rate limit": "编辑组速率限制",
"Edit JSON object directly. Suitable for simple parameter overrides.": "直接编辑 JSON 对象。适合简单覆盖参数的场景。",
@@ -2112,6 +2133,7 @@
"Enter password (8-20 characters)": "输入密码(8-20 个字符)",
"Enter password (8–128 characters)": "输入密码(8–128 个字符)",
"Enter previous domains, one per line, without a protocol, port or path. Different ports on the same domain do not need compatible domains.": "每行填写一个旧域名,不包含协议、端口或路径。同一域名的不同端口无需加入兼容列表。",
"Excludes the first attempt. Counted per group.": "不含首次,按分组计算。",
"Enter previous Passkey domains, one per line. Existing Passkeys can still verify with these domains; new Passkeys use the primary domain.": "每行填写一个旧通行密钥域名。已有通行密钥仍可通过这些域名验证,新通行密钥使用主域名。",
"Enter quota in {{currency}}": "输入 {{currency}} 额度",
"Enter quota in tokens": "输入令牌配额",
@@ -2333,6 +2355,7 @@
"Failed to load plugins": "加载插件失败",
"Failed to load profile": "加载个人资料失败",
"Failed to load redemption codes": "加载兑换码失败",
"Failed to load settings": "加载设置失败",
"Failed to load setup data": "无法加载设置数据",
"Failed to load setup status": "无法加载设置状态",
"Failed to load SGLang status": "加载 SGLang 状态失败",
@@ -2374,6 +2397,7 @@
"Failed to set tag": "设置标签失败",
"Failed to setup 2FA": "设置 2FA 失败",
"Failed to show model in model square": "在模型广场显示失败",
"Fill a CLI template or add a blank rule.": "填充 CLI 模板,或添加空白规则。",
"Failed to sign out other sessions": "退出其他登录会话失败",
"Failed to sign out session": "退出登录会话失败",
"Failed to start {{provider}} login": "启动 {{provider}} 登录失败",
@@ -2517,6 +2541,7 @@
"Fix order": "修复顺序",
"Fixed": "修复",
"Fixed abilities: {{success}} succeeded, {{fails}} failed": "渠道一致性修复完成:{{success}} 个成功,{{fails}} 个失败",
"Fixed channel constraint": "固定渠道约束",
"Fixed fee per request": "每次请求固定费用",
"Fixed price": "固定价格",
"Fixed price (USD)": "固定价格 (USD)",
@@ -2637,8 +2662,11 @@
"GitHub rate limit reached. Try again later.": "已达到 GitHub 请求限制,请稍后重试。",
"Give the group a recognizable name and optional description.": "为该分组提供一个可识别的名称和可选的描述。",
"Give this group a recognizable name.": "为此分组提供一个可识别的名称。",
"Global and channel settings": "全局与渠道设置",
"Global configuration and administrative tools.": "全局配置和管理工具。",
"Global Coverage": "全球覆盖",
"Global default": "全局默认",
"Global default: {{mode}}": "全局默认:{{mode}}",
"Global Model Configuration": "全局模型配置",
"Global throughput": "全局吞吐量",
"Go Back": "返回",
@@ -2686,6 +2714,7 @@
"Group name cannot be changed when editing.": "编辑时无法更改组名称。",
"Group prices cannot be expanded because this expression is not a standard tiered pricing expression.": "该表达式不是标准分档计费表达式,无法展开分组价格。",
"Group Pricing": "分组定价",
"How a session is identified and which channel it keeps.": "定义如何识别会话及其使用的渠道。",
"Group pricing usage guide": "分组定价使用教程",
"group ratio": "分组倍率",
"Group Ratio": "分组倍率",
@@ -2720,6 +2749,7 @@
"Header Value (supports string or JSON mapping)": "请求头值(支持字符串或 JSON 映射)",
"header. Anthropic-formatted endpoints accept the": " 请求头。Anthropic 格式的端点也接受",
"Health": "健康",
"Health check timeout threshold (seconds)": "健康检查耗时阈值(秒)",
"Healthy": "正常",
"Hidden": "屏蔽",
"Hidden — verify to reveal": "隐藏 — 验证以显示",
@@ -2883,6 +2913,7 @@
"Index URL": "索引 URL",
"Information unavailable": "暂时无法读取",
"Inherit global Auto order": "继承全局 Auto 顺序",
"Inherit global default": "继承全局默认",
"Inherit vendor icon": "继承供应商图标",
"Inherited": "继承",
"Inherited from {{vendor}}": "继承自 {{vendor}}",
@@ -2953,6 +2984,7 @@
"Invalid response": "响应无效",
"Invalid rules JSON format": "规则 JSON 格式不正确",
"Invalid status code mapping entries: {{entries}}": "无效的状态码映射条目:{{entries}}",
"Invalid status code rules": "状态码规则无效",
"Invalid status code rules: {{tokens}}": "无效的状态码规则:{{tokens}}",
"Invalid vLLM server address": "vLLM 服务地址无效",
"Invalidate": "作废",
@@ -2979,6 +3011,7 @@
"IP Whitelist (supports CIDR)": "IP 白名单(支持 CIDR 表达式)",
"IP: {{ip}} · Method: {{method}}": "IP:{{ip}} · 登录方式:{{method}}",
"is less than the configured maximum cache size": "小于配置的最大缓存大小",
"Later requests follow the new channel.": "后续请求改用新渠道。",
"is the default price; ": "为默认价格;",
"It seems like the page you're looking for": "您要查找的页面似乎",
"Items": "条目",
@@ -3018,6 +3051,7 @@
"Keep original value (skip if target exists)": "保留原值(目标已有值时不覆盖)",
"Keep the domains used by existing Passkeys, one per line. If the primary domain changed from www.example.com to example.com, enter www.example.com here.": "每行填写一个已有通行密钥使用的域名。例如,主域名从 www.example.com 改成 example.com 后,应在这里保留 www.example.com。",
"Keep the platform ready": "保持平台就绪",
"Keep the session binding when the channel is unavailable": "渠道不可用时保留会话绑定",
"Keep this above 1 minute to avoid heavy database load": "保持此值大于 1 分钟以避免数据库负载过重",
"Keep this vendor": "保留此供应商",
"Keep-alive Ping": "保持连接心跳",
@@ -3174,6 +3208,7 @@
"Logo": "徽标",
"Logo URL": "徽标 URL",
"Logs": "日志",
"Maximum retries": "最多重试次数",
"Long passwords are unavailable until the password storage upgrade is complete.": "密码存储升级完成前暂不支持长密码。",
"Look for a special ratio rule matching this user group and this billing group. If one exists, use its ratio. Otherwise use the billing group base ratio from the pricing table.": "查找匹配「该用户分组 + 该计费分组」的特殊倍率规则。有就用规则里的倍率,没有就用定价分组表中计费分组的基础倍率。",
"Low balance": "余额偏低",
@@ -3246,6 +3281,7 @@
"Maximum 1000 characters. Supports Markdown and HTML.": "最多 1000 个字符。支持 Markdown 和 HTML。",
"Maximum 200 characters": "最多 200 个字符",
"Maximum 500 characters. Supports Markdown and HTML.": "最多 500 个字符。支持 Markdown 和 HTML。",
"Maximum cached sessions": "最多缓存会话数",
"Maximum check-in quota": "签到最大额度",
"Maximum custom groups per token": "每个令牌的最大自定义分组数",
"Maximum input window": "最大输入窗口",
@@ -3430,6 +3466,7 @@
"months": "个月",
"Moonshot": "Moonshot",
"More": "更多",
"More actions": "更多操作",
"More Apps": "更多",
"more mapping": "更多映射",
"More models ({{count}})": "更多模型({{count}})",
@@ -3893,6 +3930,7 @@
"Open in New Tab": "在新标签页中打开",
"Open menu": "打开菜单",
"Open Query Balance to view the upstream JSON response": "请打开“查询余额”查看上游 JSON 响应",
"Otherwise the binding is removed.": "关闭时清除该绑定。",
"Open release": "打开版本",
"Open source": "开源",
"Open Source": "开源项目",
@@ -4292,6 +4330,7 @@
"Pre-consumed": "预扣费",
"Pre-Consumed Quota": "预消耗配额",
"Pre-release": "预发布版",
"Prefer the original channel, allow switching": "优先原渠道,失败允许切换",
"Preference saved as {{pref}}, but no active subscription. Requests will be rejected.": "已保存偏好为{{pref}},当前无生效订阅,请求将被拒绝",
"Preference saved as {{pref}}, but no active subscription. Wallet will be used automatically.": "已保存偏好为{{pref}},当前无生效订阅,将自动使用钱包",
"Preferences": "偏好设置",
@@ -4424,6 +4463,8 @@
"Prompt Caching": "提示词缓存",
"Prompt Details": "提示词详情",
"Prompt price ($/1M tokens)": "提示词价格(美元/100 万 token)",
"Prompt text filtering is active with the current form values.": "按当前表单设置,提示词文本过滤已生效。",
"Prompt text filtering needs both switches enabled and a non-empty keyword list.": "提示词文本过滤需要同时开启两个开关,并配置非空的敏感词列表。",
"Proprietary": "商业闭源",
"Protect login and registration with Cloudflare Turnstile": "使用 Cloudflare Turnstile 保护登录和注册",
"Provide a JSON object where each key maps to an endpoint definition.": "提供一个 JSON 对象,其中每个键映射到一个端点定义。",
@@ -4587,6 +4628,7 @@
"Redirecting to payment page...": "正在重定向到支付页面...",
"Redirecting to sign in in {{seconds}} seconds.": "将在 {{seconds}} 秒后跳转到登录页。",
"Redirects to {{model}}": "重定向到 {{model}}",
"Reduces cache hit rate": "会降低缓存命中率",
"Reduces repeated wording": "减少重复措辞",
"Reference Video": "参照生视频",
"Referral link:": "推荐链接:",
@@ -4706,9 +4748,12 @@
"Request Body Memory Cache": "请求体内存缓存",
"Request body must be a JSON object.": "请求体必须是 JSON 对象。",
"Request body pass-through is enabled. The request body will be sent directly to the upstream without any conversion.": "请求体透传已启用。请求体将直接发送到上游,不进行任何转换。",
"Request checks": "请求检查",
"Request completed": "请求已完成",
"Request conversion": "请求转换",
"Request Conversion": "请求转换",
"Request Count": "请求计数",
"Request decision flow": "请求决策流程",
"Request error occurred": "请求发生错误",
"Request failed": "请求失败",
"Request flow": "请求流",
@@ -4724,13 +4769,16 @@
"Request names your users call": "用户调用的请求模型名",
"Request overrides, routing behavior, and upstream model automation": "请求覆盖、路由行为和上游模型自动化",
"Request Path": "请求路径",
"Request policies": "请求策略",
"Request processing": "请求处理",
"Request rejected locally": "请求在本地被拒绝",
"Request retry": "请求重试",
"Request rule pricing": "请求规则计费",
"Request rules apply on top of this amount.": "请求规则会在此金额之上继续应用。",
"Request simulation": "请求模拟",
"Request success rate sampled over the last 24 hours": "最近 24 小时按时间桶采样的请求成功率",
"Request success rate; {{incidents}} incident buckets in the last 24 hours": "请求成功率;最近 24 小时 {{incidents}} 个异常桶",
"Request text filtering": "请求文本过滤",
"Request timed out, please refresh and restart GitHub login": "请求超时,请刷新页面后重新发起 GitHub 登录",
"Request-based": "含请求条件",
"Requested items": "请求项数",
@@ -4750,15 +4798,18 @@
"Requests will be forwarded to this worker. Trailing slashes are removed automatically.": "请求将被转发到此 Worker。末尾的斜杠会自动移除。",
"Requests:": "请求:",
"Require email verification for new accounts": "要求新账户验证邮箱",
"Retry budget": "重试预算",
"Require job success before follow-up actions": "在后续操作前要求任务成功",
"Require login to view models": "要求登录才能查看模型",
"Require login to view rankings": "要求登录才能查看排行榜",
"Require the original channel": "必须使用原渠道",
"required": "必填",
"Required": "必需",
"Required events:": "必需事件:",
"Required provider, authentication, model, and group settings": "必填的供应商、鉴权、模型和分组设置",
"Required to expose MjProxy-style image generation to end users.": "需要向终端用户开放 MjProxy 风格的图像生成。",
"Requires an available channel and access to its group.": "仍需有可用渠道,并满足用户分组访问条件。",
"Requires global auto-disable and this channel option.": "需同时开启全局自动停用和本渠道开关。",
"Requires upstream WebSocket support": "需上游支持 WebSocket",
"Rerank": "重新排序",
"Reroll": "重绘",
@@ -4816,7 +4867,6 @@
"Response time: {{duration}}": "响应时间:{{duration}}",
"Response too large": "响应过大",
"Responses API Version": "响应 API 版本",
"Responses WebSocket": "Responses WebSocket",
"Restore default pricing": "恢复默认定价",
"Restore defaults": "恢复默认",
"Restore global Auto": "恢复全局 Auto",
@@ -4831,6 +4881,7 @@
"Retry Chain": "重试链路",
"Retry Settings": "重试设置",
"Retry Suggestion": "重试建议",
"Rules can inherit or override these defaults.": "规则可继承或单独覆盖。",
"Retry Times": "重试次数",
"Return a custom error immediately": "立即返回自定义错误",
"Return Custom Error": "返回自定义错误",
@@ -4904,13 +4955,16 @@
"Rule {{line}} prune_objects is missing conditions": "第 {{line}} 条 prune_objects 缺少条件",
"Rule {{line}} return_error requires a message field": "第 {{line}} 条 return_error 需要 message 字段",
"Rule Description (optional)": "规则描述(可选)",
"Rule editor mode": "规则编辑模式",
"Rule group": "规则组",
"Rule override": "规则单独设置",
"rules": "规则",
"Rules": "规则",
"Rules are checked in order. The first match determines the price.": "按顺序匹配规则,首条命中的规则决定价格。",
"Rules JSON": "规则 JSON",
"Rules JSON must be an array": "规则 JSON 必须是数组",
"Rules match the original model value from the client request body.": "规则匹配客户端请求体里的原始 model 值。",
"Run background checks using the selected test mode": "按所选检查模式在后台运行检查",
"Run dry run": "运行干跑",
"Run GC": "执行 GC",
"Run tests for the selected models": "运行所选模型的测试",
@@ -4982,6 +5036,8 @@
"Scheduled channel tests": "定期渠道测试",
"Scheduled full test": "定时全量测试",
"Scheduled full test probes non-manually-disabled channels; passive recovery only checks auto-disabled channels after real request failures.": "定时全量测试会探测非手动禁用的渠道;仅被动恢复只会在真实请求失败导致渠道自动禁用后检查这些渠道是否可恢复。",
"Scheduled or bulk health checks can disable a channel when this duration is exceeded, if both global and channel auto-disable are enabled.": "全局和渠道自动停用均开启时,定时或批量健康检查耗时超过此阈值可触发停用。",
"Scheduled recovery is off. Bulk channel tests can still re-enable automatically disabled channels.": "定时恢复未运行,批量测试仍可恢复被自动停用的渠道。",
"scheduling controls": "调度控制能力",
"Science": "科研",
"Scope": "作用域",
@@ -5095,6 +5151,7 @@
"Select locations": "选择位置",
"Select model": "选择模型",
"Select Model": "选择模型",
"Session defaults": "会话默认设置",
"Select model {{model}}": "选择模型 {{model}}",
"Select models": "选择模型",
"Select models (empty for allow all)": "选择模型(留空表示允许所有)",
@@ -5105,6 +5162,7 @@
"Select or enter color value": "选择或输入颜色值",
"Select or enter method identifier": "选择或输入支付方式标识",
"Select or enter model name": "选择或输入模型名称",
"Sessions and retries": "会话与重试",
"Select or enter payment type": "选择或输入支付类型",
"Select or enter payment type key": "选择或输入支付处理标识",
"Select payment method": "选择支付方式",
@@ -5167,8 +5225,14 @@
"Server Token": "服务器 Token",
"Service account JSON file(s)": "服务账号 JSON 文件",
"Session": "会话",
"Session behavior": "会话保持",
"Session behavior prevents switching channels": "会话保持设置阻止切换渠道",
"Session expired!": "会话已过期!",
"Session expired?": "会话已过期?",
"Session rule": "会话规则",
"Session rule matched": "命中会话规则",
"Session rules": "会话规则",
"Session rules table": "会话规则表格",
"Session signed out": "已退出此会话",
"Sessions & Access": "会话与访问",
"Set": "设置",
@@ -5321,6 +5385,7 @@
"Source name": "源名称",
"Source vendors": "来源供应商",
"Source vendors will be deleted after their model assignments are moved. The target vendor’s details are preserved.": "模型归属转移后将删除来源供应商。目标供应商的资料保持原值。",
"Source: global settings. Changes take effect after saving.": "来源:全局设置。修改后保存生效。",
"sources": "来源",
"Space-separated OAuth scopes": "以空格分隔的OAuth作用域",
"Spark model version, e.g., v2.1 (version number in API URL)": "Spark 模型版本,例如 v2.1(API URL 中的版本号)",
@@ -5370,6 +5435,8 @@
"Status Code": "状态码",
"Status Code Mapping": "状态码映射",
"Status code mapping must use valid HTTP status codes": "状态码映射必须使用有效的 HTTP 状态码",
"Status is outside the retry rules": "状态码未命中重试规则",
"Status matches the retry rules": "状态码命中重试规则",
"Status Page Slug": "状态页面 Slug",
"Status short": "状态",
"Status:": "状态:",
@@ -5391,6 +5458,7 @@
"Stored value is not echoed back for security": "出于安全考虑,已存储的值不会回显",
"stream": "流",
"Stream": "流",
"Stream did not complete successfully": "流式输出未成功完成",
"Stream Mode": "流式模式",
"Stream Status": "流状态",
"Stream tokens incrementally as they are generated": "在生成过程中按 token 逐步流式返回",
@@ -5432,6 +5500,7 @@
"succeeded": "已成功",
"Success": "成功",
"Success rate": "成功率",
"Successful scheduled or bulk checks can restore automatically disabled channels. Manually disabled channels stay disabled.": "定时或批量检查成功后,可恢复被自动停用的渠道;人工停用的渠道保持停用。",
"Successfully created {{count}} API Key(s)": "成功创建了 {{count}} 个 API 密钥",
"Successfully created {{count}} redemption codes": "成功创建了 {{count}} 个兑换码",
"Successfully deleted {{count}} API key(s)": "成功删除了 {{count}} 个 API 密钥",
@@ -5471,6 +5540,7 @@
"Switch to JSON": "切换到 JSON",
"Switch to Visual": "切换到可视化",
"Switch to visual editor": "切换到可视化编辑",
"Switch to visual mode to add rules or apply templates.": "切换到可视化模式后,可添加规则或填充模板。",
"Switch to visual pricing?": "切换到可视化定价?",
"Switching regenerates the expression from the price table and replaces its original formatting and tier names. Changes apply only after saving.": "切换后将根据价格表重新生成表达式,替换原始写法和档位名称。更改将在保存后生效。",
"Sync Endpoint": "同步端点",
@@ -5500,6 +5570,7 @@
"System Administration": "系统管理",
"System Announcements": "系统公告",
"System Behavior": "系统行为",
"System constraint": "系统约束",
"System data statistics": "系统数据统计",
"System default": "系统默认",
"System Info": "系统信息",
@@ -5517,6 +5588,7 @@
"System Prompt": "系统提示词",
"System Prompt Concatenation": "系统提示词连接",
"System Prompt Override": "系统提示覆盖",
"System retry exclusion": "系统禁止重试的情况",
"System settings": "系统设置",
"System Settings": "系统设置",
"System setup wizard": "系统设置向导",
@@ -5551,6 +5623,7 @@
"Task": "任务",
"Task billing": "任务计费",
"Task Details": "任务详情",
"Task failed": "任务失败",
"Task History": "历史任务",
"Task ID": "任务 ID",
"Task ID:": "任务 ID:",
@@ -5659,6 +5732,7 @@
"The sync will fetch missing models and vendors from the selected source. Existing records are updated only when you approve conflicts.": "同步将从选定的源获取缺失的模型和供应商。仅在您批准冲突时才会更新现有记录。",
"The system always bills in USD. Site currency makes entering and converting prices easier; amounts are converted to USD using the site exchange rate. Switching currencies does not change the actual price. Raw billing expressions always use USD.": "系统底层统一使用美元计价。选择站点货币是为了方便输入和换算,金额会按站点汇率转换为美元。切换货币不会改变实际价格;原始计费表达式始终使用美元。",
"The system currently uses: {{domain}}": "系统目前使用:{{domain}}",
"The task was accepted; submission cannot be replayed": "任务已接受,不能重复提交",
"The Telegram authorization request is invalid or expired.": "Telegram 授权请求无效或已过期。",
"The telegram OAuth provider name is reserved. Ask your administrator to rename the conflicting custom provider.": "telegram 是保留的 OAuth 提供方名称,请联系管理员重命名冲突的自定义提供方。",
"The token group that will have a custom ratio": "将具有自定义比例的令牌分组",
@@ -5820,6 +5894,7 @@
"Tiered pricing": "阶梯计费",
"tiers": "档",
"Time": "时间",
"Time between scheduled channel checks": "定时渠道检查的执行间隔",
"Time functions use the timezone written in the expression.": "时间函数使用表达式中指定的时区。",
"Time Granularity": "时间粒度",
"Time range": "时间范围",
@@ -5933,6 +6008,7 @@
"Total {{count}} records": "共 {{count}} 条记录",
"Total = used + remaining. It is not an initial allocation or a periodic budget; changing the remaining quota changes the total and percentage.": "总额度 = 已用 + 剩余,并非初始额度或周期预算。修改剩余额度会改变总额度和已用比例。",
"Total Allocated": "总分配",
"Total attempt budget exhausted": "整次尝试次数已耗尽",
"Total check-ins": "累计签到",
"Total consumed": "总消耗",
"Total consumed quota": "总消耗额度",
@@ -6028,6 +6104,7 @@
"Unbind": "解绑",
"Unbind failed": "解绑失败",
"Unbound {{provider}}": "已解绑 {{provider}}",
"Unchanged": "不变",
"Underflow": "下溢",
"Underground": "暗夜",
"Understand how user groups, token groups, ratios, and special rules work together.": "了解用户分组、令牌分组、倍率和特殊规则如何共同生效。",
@@ -6083,6 +6160,7 @@
"Update the configuration for this custom OAuth provider.": "更新此自定义OAuth提供商的配置。",
"Update the redemption code by providing necessary info.": "通过提供必要信息更新兑换码。",
"Update the reusable bundle below.": "更新下面的可重用捆绑包。",
"Update the session binding after a successful switch": "切换成功后更新会话绑定",
"Update the user by providing necessary info.": "通过提供必要信息更新用户。",
"Update vendor information for {{name}}": "更新 {{name}} 的供应商信息",
"Update your password for account:": "更新账户密码:",
@@ -6148,7 +6226,9 @@
"Upstream prices fetched successfully": "已成功获取上游价格",
"Upstream protocol plan": "上游协议方案",
"Upstream ratios fetched successfully": "上游比率获取成功",
"Upstream request failed": "上游请求失败",
"Upstream Request ID": "上游请求 ID",
"Upstream response": "上游响应",
"Upstream Response": "上游返回",
"Upstream Response (billing-usage-anthropic-estimated)": "上游返回(billing-usage-anthropic-estimated)",
"Upstream Response (billing-usage-anthropic)": "上游返回(billing-usage-anthropic)",
@@ -6523,6 +6603,7 @@
"with conflicts": "有冲突",
"With linked models": "有关联模型",
"with the API key from your token settings.": "替换为令牌设置中的 API Key。",
"With these settings, automatic disabling is off for all channels.": "按当前设置,所有渠道的自动停用均不生效。",
"Without additional conditions, only the type above is used for pruning.": "未添加附加条件时,仅使用上方 type 进行清理。",
"Without linked models": "无关联模型",
"Worked example": "完整示例",
@@ -6586,6 +6667,14 @@
"Zhipu": "智谱",
"Zhipu GLM": "智谱GLM",
"Zhipu V4": "智谱 V4",
"Zoom": "缩放"
"Zoom": "缩放",
"Channel error": "渠道错误",
"Unrecognized status code": "无法识别的状态码",
"Correct the invalid settings before saving.": "请修正无效配置后再保存。",
"Upstream connection": "上游连接",
"Local check": "本地检查",
"Responses WebSocket": "Responses WebSocket",
"Cross-group retry": "跨分组重试",
"Request policy decisions": "请求策略决策"
}
}
+46
View File
@@ -66,6 +66,8 @@ import { Route as AuthenticatedSystemSettingsModelsIndexRouteImport } from './ro
import { Route as AuthenticatedSystemSettingsModelsSectionRouteImport } from './routes/_authenticated/system-settings/models/$section'
import { Route as AuthenticatedSystemSettingsOperationsIndexRouteImport } from './routes/_authenticated/system-settings/operations/index'
import { Route as AuthenticatedSystemSettingsOperationsSectionRouteImport } from './routes/_authenticated/system-settings/operations/$section'
import { Route as AuthenticatedSystemSettingsRequestPoliciesIndexRouteImport } from './routes/_authenticated/system-settings/request-policies/index'
import { Route as AuthenticatedSystemSettingsRequestPoliciesSectionRouteImport } from './routes/_authenticated/system-settings/request-policies/$section'
import { Route as AuthenticatedSystemSettingsSecurityIndexRouteImport } from './routes/_authenticated/system-settings/security/index'
import { Route as AuthenticatedSystemSettingsSecuritySectionRouteImport } from './routes/_authenticated/system-settings/security/$section'
import { Route as AuthenticatedSystemSettingsSiteIndexRouteImport } from './routes/_authenticated/system-settings/site/index'
@@ -383,6 +385,18 @@ const AuthenticatedSystemSettingsOperationsSectionRoute =
path: '/operations/$section',
getParentRoute: () => AuthenticatedSystemSettingsRouteRoute,
} as any)
const AuthenticatedSystemSettingsRequestPoliciesIndexRoute =
AuthenticatedSystemSettingsRequestPoliciesIndexRouteImport.update({
id: '/request-policies/',
path: '/request-policies/',
getParentRoute: () => AuthenticatedSystemSettingsRouteRoute,
} as any)
const AuthenticatedSystemSettingsRequestPoliciesSectionRoute =
AuthenticatedSystemSettingsRequestPoliciesSectionRouteImport.update({
id: '/request-policies/$section',
path: '/request-policies/$section',
getParentRoute: () => AuthenticatedSystemSettingsRouteRoute,
} as any)
const AuthenticatedSystemSettingsSecurityIndexRoute =
AuthenticatedSystemSettingsSecurityIndexRouteImport.update({
id: '/security/',
@@ -459,6 +473,7 @@ export interface FileRoutesByFullPath {
'/system-settings/content/$section': typeof AuthenticatedSystemSettingsContentSectionRoute
'/system-settings/models/$section': typeof AuthenticatedSystemSettingsModelsSectionRoute
'/system-settings/operations/$section': typeof AuthenticatedSystemSettingsOperationsSectionRoute
'/system-settings/request-policies/$section': typeof AuthenticatedSystemSettingsRequestPoliciesSectionRoute
'/system-settings/security/$section': typeof AuthenticatedSystemSettingsSecuritySectionRoute
'/system-settings/site/$section': typeof AuthenticatedSystemSettingsSiteSectionRoute
'/system-settings/auth/': typeof AuthenticatedSystemSettingsAuthIndexRoute
@@ -466,6 +481,7 @@ export interface FileRoutesByFullPath {
'/system-settings/content/': typeof AuthenticatedSystemSettingsContentIndexRoute
'/system-settings/models/': typeof AuthenticatedSystemSettingsModelsIndexRoute
'/system-settings/operations/': typeof AuthenticatedSystemSettingsOperationsIndexRoute
'/system-settings/request-policies/': typeof AuthenticatedSystemSettingsRequestPoliciesIndexRoute
'/system-settings/security/': typeof AuthenticatedSystemSettingsSecurityIndexRoute
'/system-settings/site/': typeof AuthenticatedSystemSettingsSiteIndexRoute
}
@@ -519,6 +535,7 @@ export interface FileRoutesByTo {
'/system-settings/content/$section': typeof AuthenticatedSystemSettingsContentSectionRoute
'/system-settings/models/$section': typeof AuthenticatedSystemSettingsModelsSectionRoute
'/system-settings/operations/$section': typeof AuthenticatedSystemSettingsOperationsSectionRoute
'/system-settings/request-policies/$section': typeof AuthenticatedSystemSettingsRequestPoliciesSectionRoute
'/system-settings/security/$section': typeof AuthenticatedSystemSettingsSecuritySectionRoute
'/system-settings/site/$section': typeof AuthenticatedSystemSettingsSiteSectionRoute
'/system-settings/auth': typeof AuthenticatedSystemSettingsAuthIndexRoute
@@ -526,6 +543,7 @@ export interface FileRoutesByTo {
'/system-settings/content': typeof AuthenticatedSystemSettingsContentIndexRoute
'/system-settings/models': typeof AuthenticatedSystemSettingsModelsIndexRoute
'/system-settings/operations': typeof AuthenticatedSystemSettingsOperationsIndexRoute
'/system-settings/request-policies': typeof AuthenticatedSystemSettingsRequestPoliciesIndexRoute
'/system-settings/security': typeof AuthenticatedSystemSettingsSecurityIndexRoute
'/system-settings/site': typeof AuthenticatedSystemSettingsSiteIndexRoute
}
@@ -583,6 +601,7 @@ export interface FileRoutesById {
'/_authenticated/system-settings/content/$section': typeof AuthenticatedSystemSettingsContentSectionRoute
'/_authenticated/system-settings/models/$section': typeof AuthenticatedSystemSettingsModelsSectionRoute
'/_authenticated/system-settings/operations/$section': typeof AuthenticatedSystemSettingsOperationsSectionRoute
'/_authenticated/system-settings/request-policies/$section': typeof AuthenticatedSystemSettingsRequestPoliciesSectionRoute
'/_authenticated/system-settings/security/$section': typeof AuthenticatedSystemSettingsSecuritySectionRoute
'/_authenticated/system-settings/site/$section': typeof AuthenticatedSystemSettingsSiteSectionRoute
'/_authenticated/system-settings/auth/': typeof AuthenticatedSystemSettingsAuthIndexRoute
@@ -590,6 +609,7 @@ export interface FileRoutesById {
'/_authenticated/system-settings/content/': typeof AuthenticatedSystemSettingsContentIndexRoute
'/_authenticated/system-settings/models/': typeof AuthenticatedSystemSettingsModelsIndexRoute
'/_authenticated/system-settings/operations/': typeof AuthenticatedSystemSettingsOperationsIndexRoute
'/_authenticated/system-settings/request-policies/': typeof AuthenticatedSystemSettingsRequestPoliciesIndexRoute
'/_authenticated/system-settings/security/': typeof AuthenticatedSystemSettingsSecurityIndexRoute
'/_authenticated/system-settings/site/': typeof AuthenticatedSystemSettingsSiteIndexRoute
}
@@ -646,6 +666,7 @@ export interface FileRouteTypes {
| '/system-settings/content/$section'
| '/system-settings/models/$section'
| '/system-settings/operations/$section'
| '/system-settings/request-policies/$section'
| '/system-settings/security/$section'
| '/system-settings/site/$section'
| '/system-settings/auth/'
@@ -653,6 +674,7 @@ export interface FileRouteTypes {
| '/system-settings/content/'
| '/system-settings/models/'
| '/system-settings/operations/'
| '/system-settings/request-policies/'
| '/system-settings/security/'
| '/system-settings/site/'
fileRoutesByTo: FileRoutesByTo
@@ -706,6 +728,7 @@ export interface FileRouteTypes {
| '/system-settings/content/$section'
| '/system-settings/models/$section'
| '/system-settings/operations/$section'
| '/system-settings/request-policies/$section'
| '/system-settings/security/$section'
| '/system-settings/site/$section'
| '/system-settings/auth'
@@ -713,6 +736,7 @@ export interface FileRouteTypes {
| '/system-settings/content'
| '/system-settings/models'
| '/system-settings/operations'
| '/system-settings/request-policies'
| '/system-settings/security'
| '/system-settings/site'
id:
@@ -769,6 +793,7 @@ export interface FileRouteTypes {
| '/_authenticated/system-settings/content/$section'
| '/_authenticated/system-settings/models/$section'
| '/_authenticated/system-settings/operations/$section'
| '/_authenticated/system-settings/request-policies/$section'
| '/_authenticated/system-settings/security/$section'
| '/_authenticated/system-settings/site/$section'
| '/_authenticated/system-settings/auth/'
@@ -776,6 +801,7 @@ export interface FileRouteTypes {
| '/_authenticated/system-settings/content/'
| '/_authenticated/system-settings/models/'
| '/_authenticated/system-settings/operations/'
| '/_authenticated/system-settings/request-policies/'
| '/_authenticated/system-settings/security/'
| '/_authenticated/system-settings/site/'
fileRoutesById: FileRoutesById
@@ -1200,6 +1226,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedSystemSettingsOperationsSectionRouteImport
parentRoute: typeof AuthenticatedSystemSettingsRouteRoute
}
'/_authenticated/system-settings/request-policies/': {
id: '/_authenticated/system-settings/request-policies/'
path: '/request-policies'
fullPath: '/system-settings/request-policies/'
preLoaderRoute: typeof AuthenticatedSystemSettingsRequestPoliciesIndexRouteImport
parentRoute: typeof AuthenticatedSystemSettingsRouteRoute
}
'/_authenticated/system-settings/request-policies/$section': {
id: '/_authenticated/system-settings/request-policies/$section'
path: '/request-policies/$section'
fullPath: '/system-settings/request-policies/$section'
preLoaderRoute: typeof AuthenticatedSystemSettingsRequestPoliciesSectionRouteImport
parentRoute: typeof AuthenticatedSystemSettingsRouteRoute
}
'/_authenticated/system-settings/security/': {
id: '/_authenticated/system-settings/security/'
path: '/security'
@@ -1264,6 +1304,7 @@ interface AuthenticatedSystemSettingsRouteRouteChildren {
AuthenticatedSystemSettingsContentSectionRoute: typeof AuthenticatedSystemSettingsContentSectionRoute
AuthenticatedSystemSettingsModelsSectionRoute: typeof AuthenticatedSystemSettingsModelsSectionRoute
AuthenticatedSystemSettingsOperationsSectionRoute: typeof AuthenticatedSystemSettingsOperationsSectionRoute
AuthenticatedSystemSettingsRequestPoliciesSectionRoute: typeof AuthenticatedSystemSettingsRequestPoliciesSectionRoute
AuthenticatedSystemSettingsSecuritySectionRoute: typeof AuthenticatedSystemSettingsSecuritySectionRoute
AuthenticatedSystemSettingsSiteSectionRoute: typeof AuthenticatedSystemSettingsSiteSectionRoute
AuthenticatedSystemSettingsAuthIndexRoute: typeof AuthenticatedSystemSettingsAuthIndexRoute
@@ -1271,6 +1312,7 @@ interface AuthenticatedSystemSettingsRouteRouteChildren {
AuthenticatedSystemSettingsContentIndexRoute: typeof AuthenticatedSystemSettingsContentIndexRoute
AuthenticatedSystemSettingsModelsIndexRoute: typeof AuthenticatedSystemSettingsModelsIndexRoute
AuthenticatedSystemSettingsOperationsIndexRoute: typeof AuthenticatedSystemSettingsOperationsIndexRoute
AuthenticatedSystemSettingsRequestPoliciesIndexRoute: typeof AuthenticatedSystemSettingsRequestPoliciesIndexRoute
AuthenticatedSystemSettingsSecurityIndexRoute: typeof AuthenticatedSystemSettingsSecurityIndexRoute
AuthenticatedSystemSettingsSiteIndexRoute: typeof AuthenticatedSystemSettingsSiteIndexRoute
}
@@ -1289,6 +1331,8 @@ const AuthenticatedSystemSettingsRouteRouteChildren: AuthenticatedSystemSettings
AuthenticatedSystemSettingsModelsSectionRoute,
AuthenticatedSystemSettingsOperationsSectionRoute:
AuthenticatedSystemSettingsOperationsSectionRoute,
AuthenticatedSystemSettingsRequestPoliciesSectionRoute:
AuthenticatedSystemSettingsRequestPoliciesSectionRoute,
AuthenticatedSystemSettingsSecuritySectionRoute:
AuthenticatedSystemSettingsSecuritySectionRoute,
AuthenticatedSystemSettingsSiteSectionRoute:
@@ -1303,6 +1347,8 @@ const AuthenticatedSystemSettingsRouteRouteChildren: AuthenticatedSystemSettings
AuthenticatedSystemSettingsModelsIndexRoute,
AuthenticatedSystemSettingsOperationsIndexRoute:
AuthenticatedSystemSettingsOperationsIndexRoute,
AuthenticatedSystemSettingsRequestPoliciesIndexRoute:
AuthenticatedSystemSettingsRequestPoliciesIndexRoute,
AuthenticatedSystemSettingsSecurityIndexRoute:
AuthenticatedSystemSettingsSecurityIndexRoute,
AuthenticatedSystemSettingsSiteIndexRoute:
@@ -28,6 +28,20 @@ export const Route = createFileRoute(
'/_authenticated/system-settings/models/$section'
)({
beforeLoad: ({ params }) => {
if (params.section === 'channel-affinity') {
throw redirect({
to: '/system-settings/request-policies/$section',
params: { section: 'routing' },
replace: true,
})
}
if (params.section === 'routing-reliability') {
throw redirect({
to: '/system-settings/request-policies/$section',
params: { section: 'routing' },
replace: true,
})
}
const validSections = MODELS_SECTION_IDS as unknown as string[]
if (!validSections.includes(params.section)) {
throw redirect({
@@ -30,8 +30,9 @@ export const Route = createFileRoute(
beforeLoad: ({ params }) => {
if (params.section === 'monitoring') {
throw redirect({
to: '/system-settings/models/$section',
params: { section: 'routing-reliability' },
to: '/system-settings/request-policies/$section',
params: { section: 'health' },
replace: true,
})
}
@@ -0,0 +1,37 @@
/*
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 { createFileRoute, redirect } from '@tanstack/react-router'
import { RequestPolicies } from '@/features/system-settings/request-policies'
import { POLICY_SECTION_IDS } from '@/features/system-settings/request-policies/section-registry'
export const Route = createFileRoute(
'/_authenticated/system-settings/request-policies/$section'
)({
beforeLoad: ({ params }) => {
if (!(POLICY_SECTION_IDS as readonly string[]).includes(params.section)) {
throw redirect({
to: '/system-settings/request-policies/$section',
params: { section: 'routing' },
replace: true,
})
}
},
component: RequestPolicies,
})
@@ -0,0 +1,31 @@
/*
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 { createFileRoute, redirect } from '@tanstack/react-router'
export const Route = createFileRoute(
'/_authenticated/system-settings/request-policies/'
)({
beforeLoad: () => {
throw redirect({
to: '/system-settings/request-policies/$section',
params: { section: 'routing' },
replace: true,
})
},
})
@@ -28,6 +28,13 @@ export const Route = createFileRoute(
'/_authenticated/system-settings/security/$section'
)({
beforeLoad: ({ params }) => {
if (params.section === 'sensitive-words') {
throw redirect({
to: '/system-settings/request-policies/$section',
params: { section: 'filtering' },
replace: true,
})
}
const validSections = SECURITY_SECTION_IDS as unknown as string[]
if (!validSections.includes(params.section)) {
throw redirect({