sync: bring over remaining release/custom-0.1.115 changes

- Extract PublicSettingsInjectionPayload named struct with drift test
- Add channel_monitor_default_interval_seconds to SSR injection
- Add image_output_price to SupportedModelChip
- Simplify AppSidebar buildSelfNavItems (admins see available channels)
- Add gateway WARN logs for 503 no-available-accounts branches
- Wire ChannelMonitorRunner into provideCleanup for graceful shutdown
- Add migrations 130/131 (CC template userid fix + mimicry field cleanup)
- Clean up fork-only features (sora, claude max simulation, client affinity)
- Remove ~320 obsolete i18n keys
- Add codexUsage utility, WechatServiceButton, BulkEditAccountModal
- Tidy go.sum
This commit is contained in:
erio
2026-04-23 20:55:18 +08:00
parent d5dac84e12
commit 748a84d871
76 changed files with 1380 additions and 1699 deletions

View File

@@ -97,6 +97,7 @@ func provideCleanup(
scheduledTestRunner *service.ScheduledTestRunnerService, scheduledTestRunner *service.ScheduledTestRunnerService,
backupSvc *service.BackupService, backupSvc *service.BackupService,
paymentOrderExpiry *service.PaymentOrderExpiryService, paymentOrderExpiry *service.PaymentOrderExpiryService,
channelMonitorRunner *service.ChannelMonitorRunner,
) func() { ) func() {
return func() { return func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -239,6 +240,12 @@ func provideCleanup(
} }
return nil return nil
}}, }},
{"ChannelMonitorRunner", func() error {
if channelMonitorRunner != nil {
channelMonitorRunner.Stop()
}
return nil
}},
} }
infraSteps := []cleanupStep{ infraSteps := []cleanupStep{

View File

@@ -222,7 +222,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelMonitorHandler := admin.NewChannelMonitorHandler(channelMonitorService) channelMonitorHandler := admin.NewChannelMonitorHandler(channelMonitorService)
channelMonitorUserHandler := handler.NewChannelMonitorUserHandler(channelMonitorService, settingService) channelMonitorUserHandler := handler.NewChannelMonitorUserHandler(channelMonitorService, settingService)
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService) channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService)
_ = channelMonitorRunner
registry := payment.ProvideRegistry() registry := payment.ProvideRegistry()
encryptionKey, err := payment.ProvideEncryptionKey(configConfig) encryptionKey, err := payment.ProvideEncryptionKey(configConfig)
if err != nil { if err != nil {
@@ -262,7 +261,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
accountExpiryService := service.ProvideAccountExpiryService(accountRepository) accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository) subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository)
scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig) scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, schedulerSnapshotService, tokenRefreshService, accountExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService) v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, schedulerSnapshotService, tokenRefreshService, accountExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner)
application := &Application{ application := &Application{
Server: httpServer, Server: httpServer,
Cleanup: v, Cleanup: v,
@@ -316,6 +315,7 @@ func provideCleanup(
scheduledTestRunner *service.ScheduledTestRunnerService, scheduledTestRunner *service.ScheduledTestRunnerService,
backupSvc *service.BackupService, backupSvc *service.BackupService,
paymentOrderExpiry *service.PaymentOrderExpiryService, paymentOrderExpiry *service.PaymentOrderExpiryService,
channelMonitorRunner *service.ChannelMonitorRunner,
) func() { ) func() {
return func() { return func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

View File

@@ -76,6 +76,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
nil, // scheduledTestRunner nil, // scheduledTestRunner
nil, // backupSvc nil, // backupSvc
nil, // paymentOrderExpiry nil, // paymentOrderExpiry
nil, // channelMonitorRunner
) )
require.NotPanics(t, func() { require.NotPanics(t, func() {

View File

@@ -53,21 +53,21 @@ type Group struct {
ImagePrice2k *float64 `json:"image_price_2k,omitempty"` ImagePrice2k *float64 `json:"image_price_2k,omitempty"`
// ImagePrice4k holds the value of the "image_price_4k" field. // ImagePrice4k holds the value of the "image_price_4k" field.
ImagePrice4k *float64 `json:"image_price_4k,omitempty"` ImagePrice4k *float64 `json:"image_price_4k,omitempty"`
// 是否仅允许 Claude Code 客户端 // allow Claude Code client only
ClaudeCodeOnly bool `json:"claude_code_only,omitempty"` ClaudeCodeOnly bool `json:"claude_code_only,omitempty"`
// Claude Code 请求降级使用的分组 ID // fallback group for non-Claude-Code requests
FallbackGroupID *int64 `json:"fallback_group_id,omitempty"` FallbackGroupID *int64 `json:"fallback_group_id,omitempty"`
// 无效请求兜底使用的分组 ID // fallback group for invalid request
FallbackGroupIDOnInvalidRequest *int64 `json:"fallback_group_id_on_invalid_request,omitempty"` FallbackGroupIDOnInvalidRequest *int64 `json:"fallback_group_id_on_invalid_request,omitempty"`
// 模型路由配置:模型模式 -> 优先账号ID列表 // model routing config: pattern -> account ids
ModelRouting map[string][]int64 `json:"model_routing,omitempty"` ModelRouting map[string][]int64 `json:"model_routing,omitempty"`
// 是否启用模型路由配置 // whether model routing is enabled
ModelRoutingEnabled bool `json:"model_routing_enabled,omitempty"` ModelRoutingEnabled bool `json:"model_routing_enabled,omitempty"`
// 是否注入 MCP XML 调用协议提示词(仅 antigravity 平台) // whether MCP XML prompt injection is enabled
McpXMLInject bool `json:"mcp_xml_inject,omitempty"` McpXMLInject bool `json:"mcp_xml_inject,omitempty"`
// 支持的模型系列:claude, gemini_text, gemini_image // supported model scopes: claude, gemini_text, gemini_image
SupportedModelScopes []string `json:"supported_model_scopes,omitempty"` SupportedModelScopes []string `json:"supported_model_scopes,omitempty"`
// 分组显示排序,数值越小越靠前 // group display order, lower comes first
SortOrder int `json:"sort_order,omitempty"` SortOrder int `json:"sort_order,omitempty"`
// 是否允许 /v1/messages 调度到此 OpenAI 分组 // 是否允许 /v1/messages 调度到此 OpenAI 分组
AllowMessagesDispatch bool `json:"allow_messages_dispatch,omitempty"` AllowMessagesDispatch bool `json:"allow_messages_dispatch,omitempty"`

View File

@@ -33,8 +33,6 @@ func (Group) Mixin() []ent.Mixin {
func (Group) Fields() []ent.Field { func (Group) Fields() []ent.Field {
return []ent.Field{ return []ent.Field{
// 唯一约束通过部分索引实现WHERE deleted_at IS NULL支持软删除后重用
// 见迁移文件 016_soft_delete_partial_unique_indexes.sql
field.String("name"). field.String("name").
MaxLen(100). MaxLen(100).
NotEmpty(), NotEmpty(),
@@ -51,7 +49,6 @@ func (Group) Fields() []ent.Field {
MaxLen(20). MaxLen(20).
Default(domain.StatusActive), Default(domain.StatusActive),
// Subscription-related fields (added by migration 003)
field.String("platform"). field.String("platform").
MaxLen(50). MaxLen(50).
Default(domain.PlatformAnthropic), Default(domain.PlatformAnthropic),
@@ -73,7 +70,6 @@ func (Group) Fields() []ent.Field {
field.Int("default_validity_days"). field.Int("default_validity_days").
Default(30), Default(30),
// 图片生成计费配置antigravity 和 gemini 平台使用)
field.Float("image_price_1k"). field.Float("image_price_1k").
Optional(). Optional().
Nillable(). Nillable().
@@ -90,42 +86,36 @@ func (Group) Fields() []ent.Field {
// Claude Code 客户端限制 (added by migration 029) // Claude Code 客户端限制 (added by migration 029)
field.Bool("claude_code_only"). field.Bool("claude_code_only").
Default(false). Default(false).
Comment("是否仅允许 Claude Code 客户端"), Comment("allow Claude Code client only"),
field.Int64("fallback_group_id"). field.Int64("fallback_group_id").
Optional(). Optional().
Nillable(). Nillable().
Comment("Claude Code 请求降级使用的分组 ID"), Comment("fallback group for non-Claude-Code requests"),
field.Int64("fallback_group_id_on_invalid_request"). field.Int64("fallback_group_id_on_invalid_request").
Optional(). Optional().
Nillable(). Nillable().
Comment("无效请求兜底使用的分组 ID"), Comment("fallback group for invalid request"),
// 模型路由配置 (added by migration 040)
field.JSON("model_routing", map[string][]int64{}). field.JSON("model_routing", map[string][]int64{}).
Optional(). Optional().
SchemaType(map[string]string{dialect.Postgres: "jsonb"}). SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
Comment("模型路由配置:模型模式 -> 优先账号ID列表"), Comment("model routing config: pattern -> account ids"),
// 模型路由开关 (added by migration 041)
field.Bool("model_routing_enabled"). field.Bool("model_routing_enabled").
Default(false). Default(false).
Comment("是否启用模型路由配置"), Comment("whether model routing is enabled"),
// MCP XML 协议注入开关 (added by migration 042)
field.Bool("mcp_xml_inject"). field.Bool("mcp_xml_inject").
Default(true). Default(true).
Comment("是否注入 MCP XML 调用协议提示词(仅 antigravity 平台)"), Comment("whether MCP XML prompt injection is enabled"),
// 支持的模型系列 (added by migration 046)
field.JSON("supported_model_scopes", []string{}). field.JSON("supported_model_scopes", []string{}).
Default([]string{"claude", "gemini_text", "gemini_image"}). Default([]string{"claude", "gemini_text", "gemini_image"}).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}). SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
Comment("支持的模型系列:claude, gemini_text, gemini_image"), Comment("supported model scopes: claude, gemini_text, gemini_image"),
// 分组排序 (added by migration 052)
field.Int("sort_order"). field.Int("sort_order").
Default(0). Default(0).
Comment("分组显示排序,数值越小越靠前"), Comment("group display order, lower comes first"),
// OpenAI Messages 调度配置 (added by migration 069) // OpenAI Messages 调度配置 (added by migration 069)
field.Bool("allow_messages_dispatch"). field.Bool("allow_messages_dispatch").
@@ -160,14 +150,11 @@ func (Group) Edges() []ent.Edge {
edge.From("allowed_users", User.Type). edge.From("allowed_users", User.Type).
Ref("allowed_groups"). Ref("allowed_groups").
Through("user_allowed_groups", UserAllowedGroup.Type), Through("user_allowed_groups", UserAllowedGroup.Type),
// 注意fallback_group_id 直接作为字段使用,不定义 edge
// 这样允许多个分组指向同一个降级分组M2O 关系)
} }
} }
func (Group) Indexes() []ent.Index { func (Group) Indexes() []ent.Index {
return []ent.Index{ return []ent.Index{
// name 字段已在 Fields() 中声明 Unique(),无需重复索引
index.Fields("status"), index.Fields("status"),
index.Fields("platform"), index.Fields("platform"),
index.Fields("subscription_type"), index.Fields("subscription_type"),

View File

@@ -162,8 +162,6 @@ github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE=
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4= github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=
@@ -183,8 +181,6 @@ github.com/icholy/digest v1.1.0 h1:HfGg9Irj7i+IX1o1QAmPfIBNu/Q5A5Tu3n/MED9k9H4=
github.com/icholy/digest v1.1.0/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y= github.com/icholy/digest v1.1.0/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y=
github.com/imroc/req/v3 v3.57.0 h1:LMTUjNRUybUkTPn8oJDq8Kg3JRBOBTcnDhKu7mzupKI= github.com/imroc/req/v3 v3.57.0 h1:LMTUjNRUybUkTPn8oJDq8Kg3JRBOBTcnDhKu7mzupKI=
github.com/imroc/req/v3 v3.57.0/go.mod h1:JL62ey1nvSLq81HORNcosvlf7SxZStONNqOprg0Pz00= github.com/imroc/req/v3 v3.57.0/go.mod h1:JL62ey1nvSLq81HORNcosvlf7SxZStONNqOprg0Pz00=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
@@ -220,8 +216,6 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM= github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI= github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
@@ -255,8 +249,6 @@ github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
@@ -286,8 +278,6 @@ github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEv
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM= github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
@@ -320,8 +310,6 @@ github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=

View File

@@ -111,7 +111,7 @@ func TestAccountHandlerCreateMixedChannelConflictSimplifiedResponse(t *testing.T
var resp map[string]any var resp map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Equal(t, "mixed_channel_warning", resp["error"]) require.Equal(t, "mixed_channel_warning", resp["error"])
require.Contains(t, resp["message"], "mixed_channel_warning") require.Contains(t, resp["message"], "claude-max")
_, hasDetails := resp["details"] _, hasDetails := resp["details"]
_, hasRequireConfirmation := resp["require_confirmation"] _, hasRequireConfirmation := resp["require_confirmation"]
require.False(t, hasDetails) require.False(t, hasDetails)
@@ -140,7 +140,7 @@ func TestAccountHandlerUpdateMixedChannelConflictSimplifiedResponse(t *testing.T
var resp map[string]any var resp map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Equal(t, "mixed_channel_warning", resp["error"]) require.Equal(t, "mixed_channel_warning", resp["error"])
require.Contains(t, resp["message"], "mixed_channel_warning") require.Contains(t, resp["message"], "claude-max")
_, hasDetails := resp["details"] _, hasDetails := resp["details"]
_, hasRequireConfirmation := resp["require_confirmation"] _, hasRequireConfirmation := resp["require_confirmation"]
require.False(t, hasDetails) require.False(t, hasDetails)

View File

@@ -235,10 +235,8 @@ func (h *SettingHandler) GetSettings(c *gin.Context) {
PaymentCancelRateLimitWindow: paymentCfg.CancelRateLimitWindow, PaymentCancelRateLimitWindow: paymentCfg.CancelRateLimitWindow,
PaymentCancelRateLimitUnit: paymentCfg.CancelRateLimitUnit, PaymentCancelRateLimitUnit: paymentCfg.CancelRateLimitUnit,
PaymentCancelRateLimitMode: paymentCfg.CancelRateLimitMode, PaymentCancelRateLimitMode: paymentCfg.CancelRateLimitMode,
ChannelMonitorEnabled: settings.ChannelMonitorEnabled, ChannelMonitorEnabled: settings.ChannelMonitorEnabled,
ChannelMonitorDefaultIntervalSeconds: settings.ChannelMonitorDefaultIntervalSeconds, ChannelMonitorDefaultIntervalSeconds: settings.ChannelMonitorDefaultIntervalSeconds,
AvailableChannelsEnabled: settings.AvailableChannelsEnabled, AvailableChannelsEnabled: settings.AvailableChannelsEnabled,
} }
response.Success(c, systemSettingsResponseData(payload, authSourceDefaults)) response.Success(c, systemSettingsResponseData(payload, authSourceDefaults))
@@ -1479,10 +1477,8 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
PaymentCancelRateLimitWindow: updatedPaymentCfg.CancelRateLimitWindow, PaymentCancelRateLimitWindow: updatedPaymentCfg.CancelRateLimitWindow,
PaymentCancelRateLimitUnit: updatedPaymentCfg.CancelRateLimitUnit, PaymentCancelRateLimitUnit: updatedPaymentCfg.CancelRateLimitUnit,
PaymentCancelRateLimitMode: updatedPaymentCfg.CancelRateLimitMode, PaymentCancelRateLimitMode: updatedPaymentCfg.CancelRateLimitMode,
ChannelMonitorEnabled: updatedSettings.ChannelMonitorEnabled, ChannelMonitorEnabled: updatedSettings.ChannelMonitorEnabled,
ChannelMonitorDefaultIntervalSeconds: updatedSettings.ChannelMonitorDefaultIntervalSeconds, ChannelMonitorDefaultIntervalSeconds: updatedSettings.ChannelMonitorDefaultIntervalSeconds,
AvailableChannelsEnabled: updatedSettings.AvailableChannelsEnabled, AvailableChannelsEnabled: updatedSettings.AvailableChannelsEnabled,
} }
response.Success(c, systemSettingsResponseData(payload, updatedAuthSourceDefaults)) response.Success(c, systemSettingsResponseData(payload, updatedAuthSourceDefaults))

View File

@@ -0,0 +1,68 @@
package dto
import (
"reflect"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
)
// TestPublicSettingsInjectionPayload_SchemaDoesNotDrift guarantees the SSR
// injection struct exposes every JSON field consumed by the frontend.
//
// Why this test exists: before we extracted a named PublicSettingsInjectionPayload
// type, the inline struct was manually kept in sync with dto.PublicSettings and
// drifted — ChannelMonitorEnabled / AvailableChannelsEnabled were missing, which
// made the frontend read `undefined` on refresh and hide the "可用渠道" menu
// until the async /api/v1/settings/public round-trip finished.
//
// This test compares the two JSON-tag sets and fails if injection is missing
// any field that dto.PublicSettings exposes. Adding a new feature flag with
// only a DTO entry will fail this test until the injection struct is updated.
//
// Intentional exclusions (fields present on dto.PublicSettings that SSR does
// not need to inject) are listed in `dtoOnlyFields` below with a reason.
func TestPublicSettingsInjectionPayload_SchemaDoesNotDrift(t *testing.T) {
injection := jsonTags(reflect.TypeOf(service.PublicSettingsInjectionPayload{}))
dtoKeys := jsonTags(reflect.TypeOf(PublicSettings{}))
// Fields that legitimately live only on the DTO. Keep tiny; document each.
dtoOnlyFields := map[string]string{
// sora_client_enabled is an upstream-only field the fork does not surface.
"sora_client_enabled": "upstream-only field, not used on this fork",
}
var missing []string
for key := range dtoKeys {
if _, ok := injection[key]; ok {
continue
}
if _, allowed := dtoOnlyFields[key]; allowed {
continue
}
missing = append(missing, key)
}
if len(missing) > 0 {
t.Fatalf("service.PublicSettingsInjectionPayload is missing JSON fields present on dto.PublicSettings: %s\n"+
"add the field to PublicSettingsInjectionPayload (and GetPublicSettingsForInjection), or "+
"document the exclusion in dtoOnlyFields with a reason.", strings.Join(missing, ", "))
}
}
func jsonTags(t reflect.Type) map[string]struct{} {
out := make(map[string]struct{})
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
tag := f.Tag.Get("json")
if tag == "" || tag == "-" {
continue
}
name := strings.SplitN(tag, ",", 2)[0]
if name == "" {
continue
}
out[name] = struct{}{}
}
return out
}

View File

@@ -301,6 +301,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制 selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制
if err != nil { if err != nil {
if len(fs.FailedAccountIDs) == 0 { if len(fs.FailedAccountIDs) == 0 {
reqLog.Warn("gateway.select_account_no_available",
zap.String("model", reqModel),
zap.Int64p("group_id", apiKey.GroupID),
zap.String("platform", platform),
zap.Error(err),
)
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts: "+err.Error(), streamStarted) h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts: "+err.Error(), streamStarted)
return return
} }
@@ -344,6 +350,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
accountReleaseFunc := selection.ReleaseFunc accountReleaseFunc := selection.ReleaseFunc
if !selection.Acquired { if !selection.Acquired {
if selection.WaitPlan == nil { if selection.WaitPlan == nil {
reqLog.Warn("gateway.select_account_no_slot_no_wait_plan",
zap.Int64("account_id", account.ID),
zap.String("model", reqModel),
zap.String("platform", platform),
)
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts", streamStarted) h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts", streamStarted)
return return
} }
@@ -525,6 +536,13 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID) selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
if err != nil { if err != nil {
if len(fs.FailedAccountIDs) == 0 { if len(fs.FailedAccountIDs) == 0 {
reqLog.Warn("gateway.select_account_no_available",
zap.String("model", reqModel),
zap.Int64p("group_id", currentAPIKey.GroupID),
zap.String("platform", platform),
zap.Bool("fallback_used", fallbackUsed),
zap.Error(err),
)
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts: "+err.Error(), streamStarted) h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts: "+err.Error(), streamStarted)
return return
} }
@@ -568,6 +586,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
accountReleaseFunc := selection.ReleaseFunc accountReleaseFunc := selection.ReleaseFunc
if !selection.Acquired { if !selection.Acquired {
if selection.WaitPlan == nil { if selection.WaitPlan == nil {
reqLog.Warn("gateway.select_account_no_slot_no_wait_plan",
zap.Int64("account_id", account.ID),
zap.String("model", reqModel),
zap.String("platform", platform),
)
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts", streamStarted) h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error", "No available accounts", streamStarted)
return return
} }

View File

@@ -15,7 +15,6 @@ import (
// Alipay product codes. // Alipay product codes.
const ( const (
alipayProductCodePreCreate = "FACE_TO_FACE_PAYMENT"
alipayProductCodeWapPay = "QUICK_WAP_WAY" alipayProductCodeWapPay = "QUICK_WAP_WAY"
alipayProductCodePagePay = "FAST_INSTANT_TRADE_PAY" alipayProductCodePagePay = "FAST_INSTANT_TRADE_PAY"
) )
@@ -31,9 +30,6 @@ var (
alipayTradeWapPay = func(client *alipay.Client, param alipay.TradeWapPay) (*url.URL, error) { alipayTradeWapPay = func(client *alipay.Client, param alipay.TradeWapPay) (*url.URL, error) {
return client.TradeWapPay(param) return client.TradeWapPay(param)
} }
alipayTradePreCreate = func(ctx context.Context, client *alipay.Client, param alipay.TradePreCreate) (*alipay.TradePreCreateRsp, error) {
return client.TradePreCreate(ctx, param)
}
alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) { alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) {
return client.TradePagePay(param) return client.TradePagePay(param)
} }
@@ -103,13 +99,13 @@ func (a *Alipay) MerchantIdentityMetadata() map[string]string {
return map[string]string{"app_id": appID} return map[string]string{"app_id": appID}
} }
// CreatePayment creates an Alipay payment using the following routing: // CreatePayment creates an Alipay payment using redirect-only flow:
// - Mobile (H5): alipay.trade.wap.pay — browser redirect into Alipay. // - Mobile (H5): alipay.trade.wap.pay — returns a URL the browser jumps to.
// - Desktop: prefer alipay.trade.precreate to get a scan payload directly. // - PC: alipay.trade.page.pay — returns a gateway URL the browser opens in a
// - Desktop fallback: if precreate is unavailable for the merchant, fall back // new window; Alipay's own page then shows login/QR. We intentionally do
// to alipay.trade.page.pay and expose both pay_url and qr_code so the // NOT encode the URL into a QR on the client (it isn't a scannable payload
// frontend can render a QR while still allowing direct page open. // and would produce an invalid scan result).
func (a *Alipay) CreatePayment(ctx context.Context, req payment.CreatePaymentRequest) (*payment.CreatePaymentResponse, error) { func (a *Alipay) CreatePayment(_ context.Context, req payment.CreatePaymentRequest) (*payment.CreatePaymentResponse, error) {
client, err := a.getClient() client, err := a.getClient()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -127,7 +123,7 @@ func (a *Alipay) CreatePayment(ctx context.Context, req payment.CreatePaymentReq
if req.IsMobile { if req.IsMobile {
return a.createWapTrade(client, req, notifyURL, returnURL) return a.createWapTrade(client, req, notifyURL, returnURL)
} }
return a.createDesktopTrade(ctx, client, req, notifyURL, returnURL) return a.createPagePayTrade(client, req, notifyURL, returnURL)
} }
func (a *Alipay) createWapTrade(client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string) (*payment.CreatePaymentResponse, error) { func (a *Alipay) createWapTrade(client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string) (*payment.CreatePaymentResponse, error) {
@@ -149,48 +145,6 @@ func (a *Alipay) createWapTrade(client *alipay.Client, req payment.CreatePayment
}, nil }, nil
} }
func (a *Alipay) createDesktopTrade(ctx context.Context, client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string) (*payment.CreatePaymentResponse, error) {
resp, precreateErr := a.createPrecreateTrade(ctx, client, req, notifyURL)
if precreateErr == nil {
return resp, nil
}
resp, pagePayErr := a.createPagePayTrade(client, req, notifyURL, returnURL)
if pagePayErr == nil {
return resp, nil
}
return nil, fmt.Errorf("alipay desktop payment failed: precreate=%v; pagepay=%w", precreateErr, pagePayErr)
}
func (a *Alipay) createPrecreateTrade(ctx context.Context, client *alipay.Client, req payment.CreatePaymentRequest, notifyURL string) (*payment.CreatePaymentResponse, error) {
param := alipay.TradePreCreate{}
param.OutTradeNo = req.OrderID
param.TotalAmount = req.Amount
param.Subject = req.Subject
param.ProductCode = alipayProductCodePreCreate
param.NotifyURL = notifyURL
rsp, err := alipayTradePreCreate(ctx, client, param)
if err != nil {
return nil, fmt.Errorf("alipay TradePreCreate: %w", err)
}
if rsp == nil {
return nil, fmt.Errorf("alipay TradePreCreate: empty response")
}
if rsp.IsFailure() {
return nil, fmt.Errorf("alipay TradePreCreate failed: %s", rsp.Error.Error())
}
if strings.TrimSpace(rsp.QRCode) == "" {
return nil, fmt.Errorf("alipay TradePreCreate: empty qr_code")
}
return &payment.CreatePaymentResponse{
TradeNo: req.OrderID,
QRCode: rsp.QRCode,
}, nil
}
func (a *Alipay) createPagePayTrade(client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string) (*payment.CreatePaymentResponse, error) { func (a *Alipay) createPagePayTrade(client *alipay.Client, req payment.CreatePaymentRequest, notifyURL, returnURL string) (*payment.CreatePaymentResponse, error) {
param := alipay.TradePagePay{} param := alipay.TradePagePay{}
param.OutTradeNo = req.OrderID param.OutTradeNo = req.OrderID
@@ -207,7 +161,6 @@ func (a *Alipay) createPagePayTrade(client *alipay.Client, req payment.CreatePay
return &payment.CreatePaymentResponse{ return &payment.CreatePaymentResponse{
TradeNo: req.OrderID, TradeNo: req.OrderID,
PayURL: payURL.String(), PayURL: payURL.String(),
QRCode: payURL.String(),
}, nil }, nil
} }
@@ -239,15 +192,7 @@ func (a *Alipay) QueryOrder(ctx context.Context, tradeNo string) (*payment.Query
amount, err := strconv.ParseFloat(result.TotalAmount, 64) amount, err := strconv.ParseFloat(result.TotalAmount, 64)
if err != nil { if err != nil {
amount, err = parseAlipayAmount( return nil, fmt.Errorf("alipay parse amount %q: %w", result.TotalAmount, err)
result.TotalAmount,
result.ReceiptAmount,
result.BuyerPayAmount,
result.InvoiceAmount,
)
if err != nil {
return nil, fmt.Errorf("alipay parse amount: %w", err)
}
} }
return &payment.QueryOrderResponse{ return &payment.QueryOrderResponse{
@@ -283,14 +228,7 @@ func (a *Alipay) VerifyNotification(ctx context.Context, rawBody string, _ map[s
amount, err := strconv.ParseFloat(notification.TotalAmount, 64) amount, err := strconv.ParseFloat(notification.TotalAmount, 64)
if err != nil { if err != nil {
amount, err = parseAlipayAmount( return nil, fmt.Errorf("alipay parse notification amount %q: %w", notification.TotalAmount, err)
notification.TotalAmount,
notification.ReceiptAmount,
notification.BuyerPayAmount,
)
if err != nil {
return nil, fmt.Errorf("alipay parse notification amount: %w", err)
}
} }
metadata := a.MerchantIdentityMetadata() metadata := a.MerchantIdentityMetadata()
@@ -368,20 +306,6 @@ func isTradeNotExist(err error) bool {
return strings.Contains(err.Error(), alipayErrTradeNotExist) return strings.Contains(err.Error(), alipayErrTradeNotExist)
} }
func parseAlipayAmount(values ...string) (float64, error) {
for _, raw := range values {
raw = strings.TrimSpace(raw)
if raw == "" {
continue
}
amount, err := strconv.ParseFloat(raw, 64)
if err == nil {
return amount, nil
}
}
return 0, fmt.Errorf("no valid amount field")
}
// Ensure interface compliance. // Ensure interface compliance.
var ( var (
_ payment.Provider = (*Alipay)(nil) _ payment.Provider = (*Alipay)(nil)

View File

@@ -3,7 +3,6 @@
package provider package provider
import ( import (
"context"
"errors" "errors"
"net/url" "net/url"
"strings" "strings"
@@ -137,22 +136,15 @@ func TestNewAlipay(t *testing.T) {
} }
func TestCreateTradeUsesPagePayForDesktop(t *testing.T) { func TestCreateTradeUsesPagePayForDesktop(t *testing.T) {
origPreCreate := alipayTradePreCreate
origPagePay := alipayTradePagePay origPagePay := alipayTradePagePay
origWapPay := alipayTradeWapPay origWapPay := alipayTradeWapPay
t.Cleanup(func() { t.Cleanup(func() {
alipayTradePreCreate = origPreCreate
alipayTradePagePay = origPagePay alipayTradePagePay = origPagePay
alipayTradeWapPay = origWapPay alipayTradeWapPay = origWapPay
}) })
preCreateCalls := 0
pagePayCalls := 0 pagePayCalls := 0
wapPayCalls := 0 wapPayCalls := 0
alipayTradePreCreate = func(ctx context.Context, client *alipay.Client, param alipay.TradePreCreate) (*alipay.TradePreCreateRsp, error) {
preCreateCalls++
return nil, errors.New("merchant does not have FACE_TO_FACE_PAYMENT")
}
alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) { alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) {
pagePayCalls++ pagePayCalls++
if param.OutTradeNo != "sub2_100" { if param.OutTradeNo != "sub2_100" {
@@ -169,7 +161,7 @@ func TestCreateTradeUsesPagePayForDesktop(t *testing.T) {
} }
provider := &Alipay{} provider := &Alipay{}
resp, err := provider.createDesktopTrade(context.Background(), &alipay.Client{}, payment.CreatePaymentRequest{ resp, err := provider.createPagePayTrade(&alipay.Client{}, payment.CreatePaymentRequest{
OrderID: "sub2_100", OrderID: "sub2_100",
Amount: "88.00", Amount: "88.00",
Subject: "Balance recharge", Subject: "Balance recharge",
@@ -177,9 +169,6 @@ func TestCreateTradeUsesPagePayForDesktop(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
if preCreateCalls != 1 {
t.Fatalf("precreate calls = %d, want 1", preCreateCalls)
}
if pagePayCalls != 1 { if pagePayCalls != 1 {
t.Fatalf("page pay calls = %d, want 1", pagePayCalls) t.Fatalf("page pay calls = %d, want 1", pagePayCalls)
} }
@@ -189,9 +178,6 @@ func TestCreateTradeUsesPagePayForDesktop(t *testing.T) {
if resp.PayURL == "" { if resp.PayURL == "" {
t.Fatal("expected pay_url for desktop page pay") t.Fatal("expected pay_url for desktop page pay")
} }
if resp.QRCode != resp.PayURL {
t.Fatalf("qr_code = %q, want same as pay_url %q", resp.QRCode, resp.PayURL)
}
} }
func TestCreateTradeUsesWapPayForMobile(t *testing.T) { func TestCreateTradeUsesWapPayForMobile(t *testing.T) {
@@ -227,54 +213,6 @@ func TestCreateTradeUsesWapPayForMobile(t *testing.T) {
} }
} }
func TestCreateTradeUsesPrecreateForDesktopWhenAvailable(t *testing.T) {
origPreCreate := alipayTradePreCreate
origPagePay := alipayTradePagePay
t.Cleanup(func() {
alipayTradePreCreate = origPreCreate
alipayTradePagePay = origPagePay
})
preCreateCalls := 0
pagePayCalls := 0
alipayTradePreCreate = func(ctx context.Context, client *alipay.Client, param alipay.TradePreCreate) (*alipay.TradePreCreateRsp, error) {
preCreateCalls++
if param.ProductCode != alipayProductCodePreCreate {
t.Fatalf("product_code = %q, want %q", param.ProductCode, alipayProductCodePreCreate)
}
return &alipay.TradePreCreateRsp{
Error: alipay.Error{Code: alipay.CodeSuccess},
QRCode: "https://qr.alipay.example.com/precreate-token",
}, nil
}
alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) {
pagePayCalls++
return url.Parse("https://openapi.alipay.com/gateway.do?page-pay")
}
provider := &Alipay{}
resp, err := provider.createDesktopTrade(context.Background(), &alipay.Client{}, payment.CreatePaymentRequest{
OrderID: "sub2_102",
Amount: "66.00",
Subject: "Balance recharge",
}, "https://merchant.example.com/api/v1/payment/webhook/alipay", "https://merchant.example.com/payment/result")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if preCreateCalls != 1 {
t.Fatalf("precreate calls = %d, want 1", preCreateCalls)
}
if pagePayCalls != 0 {
t.Fatalf("page pay calls = %d, want 0", pagePayCalls)
}
if resp.QRCode != "https://qr.alipay.example.com/precreate-token" {
t.Fatalf("qr_code = %q", resp.QRCode)
}
if resp.PayURL != "" {
t.Fatalf("pay_url = %q, want empty for precreate", resp.PayURL)
}
}
func TestAlipayMerchantIdentityMetadata(t *testing.T) { func TestAlipayMerchantIdentityMetadata(t *testing.T) {
t.Parallel() t.Parallel()
@@ -289,19 +227,3 @@ func TestAlipayMerchantIdentityMetadata(t *testing.T) {
t.Fatalf("app_id = %q, want %q", metadata["app_id"], "2021001234567890") t.Fatalf("app_id = %q, want %q", metadata["app_id"], "2021001234567890")
} }
} }
func TestParseAlipayAmount(t *testing.T) {
t.Parallel()
amount, err := parseAlipayAmount("", "88.00", "77.00")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if amount != 88 {
t.Fatalf("amount = %v, want 88", amount)
}
if _, err := parseAlipayAmount("", "not-a-number"); err == nil {
t.Fatal("expected error when no valid amount field exists")
}
}

View File

@@ -55,4 +55,9 @@ const (
// ClaudeCodeVersion stores the extracted Claude Code version from User-Agent (e.g. "2.1.22") // ClaudeCodeVersion stores the extracted Claude Code version from User-Agent (e.g. "2.1.22")
ClaudeCodeVersion Key = "ctx_claude_code_version" ClaudeCodeVersion Key = "ctx_claude_code_version"
// IsSignatureRectifyRetry marks a retry request that was produced by the signature rectifier
// (strip or pool-replace). The harvester consults this flag to avoid ingesting signatures
// from retries, which would pollute the pool with signatures we ourselves injected.
IsSignatureRectifyRetry Key = "ctx_is_signature_rectify_retry"
) )

View File

@@ -313,6 +313,31 @@ func (r *accountRepository) ListCRSAccountIDs(ctx context.Context) (map[string]i
return result, nil return result, nil
} }
// CountByTLSFingerprintProfile 按 TLS 指纹模板 ID 聚合绑定账号数。
// 走 108_add_tls_fingerprint_profile_id_index.sql 的表达式索引。
func (r *accountRepository) CountByTLSFingerprintProfile(ctx context.Context) (map[int64]int, error) {
rows, err := r.sql.QueryContext(ctx, `
SELECT (extra->>'tls_fingerprint_profile_id')::bigint AS profile_id, COUNT(*)
FROM accounts
WHERE deleted_at IS NULL AND extra ? 'tls_fingerprint_profile_id'
GROUP BY profile_id`)
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
counts := make(map[int64]int)
for rows.Next() {
var id int64
var n int
if err := rows.Scan(&id, &n); err != nil {
return nil, err
}
counts[id] = n
}
return counts, rows.Err()
}
func (r *accountRepository) Update(ctx context.Context, account *service.Account) error { func (r *accountRepository) Update(ctx context.Context, account *service.Account) error {
if account == nil { if account == nil {
return nil return nil

View File

@@ -9,7 +9,9 @@ import (
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
const stickySessionPrefix = "sticky_session:" const (
stickySessionPrefix = "sticky_session:"
)
type gatewayCache struct { type gatewayCache struct {
rdb *redis.Client rdb *redis.Client
@@ -41,12 +43,6 @@ func (c *gatewayCache) RefreshSessionTTL(ctx context.Context, groupID int64, ses
} }
// DeleteSessionAccountID 删除粘性会话与账号的绑定关系。 // DeleteSessionAccountID 删除粘性会话与账号的绑定关系。
// 当检测到绑定的账号不可用(如状态错误、禁用、不可调度等)时调用,
// 以便下次请求能够重新选择可用账号。
//
// DeleteSessionAccountID removes the sticky session binding for the given session.
// Called when the bound account becomes unavailable (e.g., error status, disabled,
// or unschedulable), allowing subsequent requests to select a new available account.
func (c *gatewayCache) DeleteSessionAccountID(ctx context.Context, groupID int64, sessionHash string) error { func (c *gatewayCache) DeleteSessionAccountID(ctx context.Context, groupID int64, sessionHash string) error {
key := buildSessionKey(groupID, sessionHash) key := buildSessionKey(groupID, sessionHash)
return c.rdb.Del(ctx, key).Err() return c.rdb.Del(ctx, key).Err()

View File

@@ -3080,7 +3080,7 @@ func (r *usageLogRepository) GetGroupStatsWithFilters(ctx context.Context, start
query := ` query := `
SELECT SELECT
COALESCE(ul.group_id, 0) as group_id, COALESCE(ul.group_id, 0) as group_id,
COALESCE(g.name, '') as group_name, COALESCE(g.name, '(无分组)') as group_name,
COUNT(*) as requests, COUNT(*) as requests,
COALESCE(SUM(ul.input_tokens + ul.output_tokens + ul.cache_creation_tokens + ul.cache_read_tokens), 0) as total_tokens, COALESCE(SUM(ul.input_tokens + ul.output_tokens + ul.cache_creation_tokens + ul.cache_read_tokens), 0) as total_tokens,
COALESCE(SUM(ul.total_cost), 0) as cost, COALESCE(SUM(ul.total_cost), 0) as cost,

View File

@@ -54,8 +54,13 @@ func TestAPIContracts(t *testing.T) {
"username": "alice", "username": "alice",
"role": "user", "role": "user",
"balance": 12.5, "balance": 12.5,
"balance_notify_enabled": false,
"balance_notify_extra_emails": null,
"balance_notify_threshold": null,
"balance_notify_threshold_type": "",
"concurrency": 5, "concurrency": 5,
"status": "active", "status": "active",
"total_recharged": 0,
"allowed_groups": null, "allowed_groups": null,
"created_at": "2025-01-02T03:04:05Z", "created_at": "2025-01-02T03:04:05Z",
"updated_at": "2025-01-02T03:04:05Z", "updated_at": "2025-01-02T03:04:05Z",
@@ -764,10 +769,13 @@ func TestAPIContracts(t *testing.T) {
"payment_cancel_rate_limit_unit": "", "payment_cancel_rate_limit_unit": "",
"payment_cancel_rate_limit_window_mode": "", "payment_cancel_rate_limit_window_mode": "",
"balance_low_notify_enabled": false, "balance_low_notify_enabled": false,
"account_quota_notify_enabled": false,
"balance_low_notify_threshold": 0, "balance_low_notify_threshold": 0,
"balance_low_notify_recharge_url": "", "balance_low_notify_recharge_url": "",
"account_quota_notify_enabled": false,
"account_quota_notify_emails": [], "account_quota_notify_emails": [],
"channel_monitor_enabled": true,
"channel_monitor_default_interval_seconds": 60,
"available_channels_enabled": false,
"wechat_connect_enabled": false, "wechat_connect_enabled": false,
"wechat_connect_app_id": "", "wechat_connect_app_id": "",
"wechat_connect_app_secret_configured": false, "wechat_connect_app_secret_configured": false,
@@ -975,7 +983,10 @@ func TestAPIContracts(t *testing.T) {
"auth_source_default_wechat_subscriptions": [], "auth_source_default_wechat_subscriptions": [],
"auth_source_default_wechat_grant_on_signup": false, "auth_source_default_wechat_grant_on_signup": false,
"auth_source_default_wechat_grant_on_first_bind": false, "auth_source_default_wechat_grant_on_first_bind": false,
"force_email_on_third_party_signup": false "force_email_on_third_party_signup": false,
"channel_monitor_enabled": true,
"channel_monitor_default_interval_seconds": 60,
"available_channels_enabled": false
} }
}`, }`,
}, },
@@ -1446,6 +1457,10 @@ func (s *stubAccountRepo) FindByExtraField(ctx context.Context, key string, valu
return nil, errors.New("not implemented") return nil, errors.New("not implemented")
} }
func (s *stubAccountRepo) CountByTLSFingerprintProfile(ctx context.Context) (map[int64]int, error) {
return nil, errors.New("not implemented")
}
func (s *stubAccountRepo) Update(ctx context.Context, account *service.Account) error { func (s *stubAccountRepo) Update(ctx context.Context, account *service.Account) error {
return errors.New("not implemented") return errors.New("not implemented")
} }

View File

@@ -30,6 +30,10 @@ type AccountRepository interface {
GetByCRSAccountID(ctx context.Context, crsAccountID string) (*Account, error) GetByCRSAccountID(ctx context.Context, crsAccountID string) (*Account, error)
// FindByExtraField 根据 extra 字段中的键值对查找账号 // FindByExtraField 根据 extra 字段中的键值对查找账号
FindByExtraField(ctx context.Context, key string, value any) ([]Account, error) FindByExtraField(ctx context.Context, key string, value any) ([]Account, error)
// CountByTLSFingerprintProfile 按 TLS 指纹模板 ID 聚合每个模板当前被多少账号绑定。
// 返回 map[profile_id]count未绑定任何账号的 profile 不出现在 map 中。
// 查询走 108_add_tls_fingerprint_profile_id_index.sql 的表达式索引。
CountByTLSFingerprintProfile(ctx context.Context) (map[int64]int, error)
// ListCRSAccountIDs returns a map of crs_account_id -> local account ID // ListCRSAccountIDs returns a map of crs_account_id -> local account ID
// for all accounts that have been synced from CRS. // for all accounts that have been synced from CRS.
ListCRSAccountIDs(ctx context.Context) (map[string]int64, error) ListCRSAccountIDs(ctx context.Context) (map[string]int64, error)

View File

@@ -58,6 +58,10 @@ func (s *accountRepoStub) FindByExtraField(ctx context.Context, key string, valu
panic("unexpected FindByExtraField call") panic("unexpected FindByExtraField call")
} }
func (s *accountRepoStub) CountByTLSFingerprintProfile(ctx context.Context) (map[int64]int, error) {
panic("unexpected CountByTLSFingerprintProfile call")
}
func (s *accountRepoStub) ListCRSAccountIDs(ctx context.Context) (map[string]int64, error) { func (s *accountRepoStub) ListCRSAccountIDs(ctx context.Context) (map[string]int64, error) {
panic("unexpected ListCRSAccountIDs call") panic("unexpected ListCRSAccountIDs call")
} }

View File

@@ -43,6 +43,16 @@ func (s *accountRepoStubForBulkUpdate) BindGroups(_ context.Context, accountID i
return nil return nil
} }
func (s *accountRepoStubForBulkUpdate) ListByGroup(_ context.Context, groupID int64) ([]Account, error) {
if err, ok := s.listByGroupErr[groupID]; ok {
return nil, err
}
if rows, ok := s.listByGroupData[groupID]; ok {
return rows, nil
}
return nil, nil
}
func (s *accountRepoStubForBulkUpdate) GetByIDs(_ context.Context, ids []int64) ([]*Account, error) { func (s *accountRepoStubForBulkUpdate) GetByIDs(_ context.Context, ids []int64) ([]*Account, error) {
s.getByIDsCalled = true s.getByIDsCalled = true
s.getByIDsIDs = append([]int64{}, ids...) s.getByIDsIDs = append([]int64{}, ids...)
@@ -63,16 +73,6 @@ func (s *accountRepoStubForBulkUpdate) GetByID(_ context.Context, id int64) (*Ac
return nil, errors.New("account not found") return nil, errors.New("account not found")
} }
func (s *accountRepoStubForBulkUpdate) ListByGroup(_ context.Context, groupID int64) ([]Account, error) {
if err, ok := s.listByGroupErr[groupID]; ok {
return nil, err
}
if rows, ok := s.listByGroupData[groupID]; ok {
return rows, nil
}
return nil, nil
}
// TestAdminService_BulkUpdateAccounts_AllSuccessIDs 验证批量更新成功时返回 success_ids/failed_ids。 // TestAdminService_BulkUpdateAccounts_AllSuccessIDs 验证批量更新成功时返回 success_ids/failed_ids。
func TestAdminService_BulkUpdateAccounts_AllSuccessIDs(t *testing.T) { func TestAdminService_BulkUpdateAccounts_AllSuccessIDs(t *testing.T) {
repo := &accountRepoStubForBulkUpdate{} repo := &accountRepoStubForBulkUpdate{}

View File

@@ -170,11 +170,11 @@ func (s *emailCacheStub) SetPasswordResetEmailCooldown(ctx context.Context, emai
return nil return nil
} }
func (s *emailCacheStub) GetNotifyCodeUserRate(ctx context.Context, userID int64) (int64, error) { func (s *emailCacheStub) IncrNotifyCodeUserRate(ctx context.Context, userID int64, window time.Duration) (int64, error) {
return 0, nil return 0, nil
} }
func (s *emailCacheStub) IncrNotifyCodeUserRate(ctx context.Context, userID int64, window time.Duration) (int64, error) { func (s *emailCacheStub) GetNotifyCodeUserRate(ctx context.Context, userID int64) (int64, error) {
return 0, nil return 0, nil
} }

View File

@@ -87,6 +87,7 @@ func (c *stubConcurrencyCacheForTest) GetAccountsLoadBatch(_ context.Context, _
func (c *stubConcurrencyCacheForTest) GetUsersLoadBatch(_ context.Context, _ []UserWithConcurrency) (map[int64]*UserLoadInfo, error) { func (c *stubConcurrencyCacheForTest) GetUsersLoadBatch(_ context.Context, _ []UserWithConcurrency) (map[int64]*UserLoadInfo, error) {
return c.usersLoadBatch, c.usersLoadErr return c.usersLoadBatch, c.usersLoadErr
} }
func (c *stubConcurrencyCacheForTest) CleanupExpiredAccountSlots(_ context.Context, _ int64) error { func (c *stubConcurrencyCacheForTest) CleanupExpiredAccountSlots(_ context.Context, _ int64) error {
return c.cleanupErr return c.cleanupErr
} }

View File

@@ -220,7 +220,7 @@ func TestApplyErrorPassthroughRule_SkipMonitoringSetsContextKey(t *testing.T) {
v, exists := c.Get(OpsSkipPassthroughKey) v, exists := c.Get(OpsSkipPassthroughKey)
assert.True(t, exists, "OpsSkipPassthroughKey should be set when skip_monitoring=true") assert.True(t, exists, "OpsSkipPassthroughKey should be set when skip_monitoring=true")
boolVal, ok := v.(bool) boolVal, ok := v.(bool)
assert.True(t, ok, "value should be bool") assert.True(t, ok, "value should be a bool")
assert.True(t, boolVal) assert.True(t, boolVal)
} }

View File

@@ -110,13 +110,12 @@ func TestCheckErrorPolicy(t *testing.T) {
expected: ErrorPolicyTempUnscheduled, expected: ErrorPolicyTempUnscheduled,
}, },
{ {
// Antigravity 401 不走升级逻辑(由 applyErrorPolicy 的 temp_unschedulable_rules 自行控制), // Gemini OAuth 401 second hit 会升级为 error返回 None交由默认错误逻辑处理
// second hit 仍然返回 TempUnscheduled。 name: "temp_unschedulable_401_second_hit_gemini_escalates",
name: "temp_unschedulable_401_second_hit_antigravity_stays_temp",
account: &Account{ account: &Account{
ID: 15, ID: 15,
Type: AccountTypeOAuth, Type: AccountTypeOAuth,
Platform: PlatformAntigravity, Platform: PlatformGemini, // 非 Antigravity 平台 401 second hit 升级
TempUnschedulableReason: `{"status_code":401,"until_unix":1735689600}`, TempUnschedulableReason: `{"status_code":401,"until_unix":1735689600}`,
Credentials: map[string]any{ Credentials: map[string]any{
"temp_unschedulable_enabled": true, "temp_unschedulable_enabled": true,
@@ -131,7 +130,29 @@ func TestCheckErrorPolicy(t *testing.T) {
}, },
statusCode: 401, statusCode: 401,
body: []byte(`unauthorized`), body: []byte(`unauthorized`),
expected: ErrorPolicyTempUnscheduled, expected: ErrorPolicyNone, // Gemini 401 second hit 升级为 error
},
{
name: "temp_unschedulable_401_antigravity_no_escalation",
account: &Account{
ID: 16,
Type: AccountTypeOAuth,
Platform: PlatformAntigravity, // Antigravity 跳过 401 升级,由 rules 正常处理
TempUnschedulableReason: `{"status_code":401,"until_unix":1735689600}`,
Credentials: map[string]any{
"temp_unschedulable_enabled": true,
"temp_unschedulable_rules": []any{
map[string]any{
"error_code": float64(401),
"keywords": []any{"unauthorized"},
"duration_minutes": float64(10),
},
},
},
},
statusCode: 401,
body: []byte(`unauthorized`),
expected: ErrorPolicyTempUnscheduled, // Antigravity 不升级,继续走规则匹配
}, },
{ {
name: "temp_unschedulable_body_miss_returns_none", name: "temp_unschedulable_body_miss_returns_none",

View File

@@ -143,7 +143,6 @@ func (s *stickyGatewayCacheHotpathStub) RefreshSessionTTL(ctx context.Context, g
func (s *stickyGatewayCacheHotpathStub) DeleteSessionAccountID(ctx context.Context, groupID int64, sessionHash string) error { func (s *stickyGatewayCacheHotpathStub) DeleteSessionAccountID(ctx context.Context, groupID int64, sessionHash string) error {
return nil return nil
} }
func (s *modelsListAccountRepoStub) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]Account, error) { func (s *modelsListAccountRepoStub) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]Account, error) {
s.listByGroupCalls.Add(1) s.listByGroupCalls.Add(1)
if s.err != nil { if s.err != nil {

View File

@@ -82,6 +82,10 @@ func (m *mockAccountRepoForPlatform) FindByExtraField(ctx context.Context, key s
return nil, nil return nil, nil
} }
func (m *mockAccountRepoForPlatform) CountByTLSFingerprintProfile(ctx context.Context) (map[int64]int, error) {
return nil, nil
}
func (m *mockAccountRepoForPlatform) ListCRSAccountIDs(ctx context.Context) (map[string]int64, error) { func (m *mockAccountRepoForPlatform) ListCRSAccountIDs(ctx context.Context) (map[string]int64, error) {
return nil, nil return nil, nil
} }

View File

@@ -71,6 +71,10 @@ func (m *mockAccountRepoForGemini) FindByExtraField(ctx context.Context, key str
return nil, nil return nil, nil
} }
func (m *mockAccountRepoForGemini) CountByTLSFingerprintProfile(ctx context.Context) (map[int64]int, error) {
return nil, nil
}
func (m *mockAccountRepoForGemini) ListCRSAccountIDs(ctx context.Context) (map[string]int64, error) { func (m *mockAccountRepoForGemini) ListCRSAccountIDs(ctx context.Context) (map[string]int64, error) {
return nil, nil return nil, nil
} }

View File

@@ -781,7 +781,7 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatible(account *Acco
if account == nil { if account == nil {
return false return false
} }
if req.RequestedModel != "" && !account.IsModelSupported(req.RequestedModel) { if req.RequestedModel != "" && !account.IsOpenAIPassthroughEnabled() && !account.IsModelSupported(req.RequestedModel) {
return false return false
} }
return account.SupportsOpenAIImageCapability(req.RequiredImageCapability) return account.SupportsOpenAIImageCapability(req.RequiredImageCapability)

View File

@@ -187,13 +187,9 @@ func applyCodexOAuthTransform(reqBody map[string]any, isCodexCLI bool, isCompact
} }
func normalizeCodexModel(model string) string { func normalizeCodexModel(model string) string {
model = strings.TrimSpace(model)
if model == "" { if model == "" {
return "gpt-5.4" return "gpt-5.4"
} }
if isOpenAIImageGenerationModel(model) {
return model
}
modelID := model modelID := model
if strings.Contains(modelID, "/") { if strings.Contains(modelID, "/") {
@@ -235,78 +231,6 @@ func normalizeCodexModel(model string) string {
return "gpt-5.4" return "gpt-5.4"
} }
func hasOpenAIImageGenerationTool(reqBody map[string]any) bool {
rawTools, ok := reqBody["tools"]
if !ok || rawTools == nil {
return false
}
tools, ok := rawTools.([]any)
if !ok {
return false
}
for _, rawTool := range tools {
toolMap, ok := rawTool.(map[string]any)
if !ok {
continue
}
if strings.TrimSpace(firstNonEmptyString(toolMap["type"])) == "image_generation" {
return true
}
}
return false
}
func normalizeOpenAIResponsesImageGenerationTools(reqBody map[string]any) bool {
rawTools, ok := reqBody["tools"]
if !ok || rawTools == nil {
return false
}
tools, ok := rawTools.([]any)
if !ok {
return false
}
modified := false
for _, rawTool := range tools {
toolMap, ok := rawTool.(map[string]any)
if !ok || strings.TrimSpace(firstNonEmptyString(toolMap["type"])) != "image_generation" {
continue
}
if _, ok := toolMap["output_format"]; !ok {
if value := strings.TrimSpace(firstNonEmptyString(toolMap["format"])); value != "" {
toolMap["output_format"] = value
modified = true
}
}
if _, ok := toolMap["output_compression"]; !ok {
if value, exists := toolMap["compression"]; exists && value != nil {
toolMap["output_compression"] = value
modified = true
}
}
if _, ok := toolMap["format"]; ok {
delete(toolMap, "format")
modified = true
}
if _, ok := toolMap["compression"]; ok {
delete(toolMap, "compression")
modified = true
}
}
return modified
}
func validateOpenAIResponsesImageModel(reqBody map[string]any, model string) error {
if !hasOpenAIImageGenerationTool(reqBody) {
return nil
}
model = strings.TrimSpace(model)
if !isOpenAIImageGenerationModel(model) {
return nil
}
return fmt.Errorf("/v1/responses image_generation requests require a Responses-capable text model; image-only model %q is not allowed", model)
}
func normalizeOpenAIModelForUpstream(account *Account, model string) string { func normalizeOpenAIModelForUpstream(account *Account, model string) string {
if account == nil || account.Type == AccountTypeOAuth { if account == nil || account.Type == AccountTypeOAuth {
return normalizeCodexModel(model) return normalizeCodexModel(model)

View File

@@ -217,42 +217,6 @@ func TestApplyCodexOAuthTransform_NormalizeCodexTools_PreservesResponsesFunction
require.Equal(t, "bash", first["name"]) require.Equal(t, "bash", first["name"])
} }
func TestNormalizeOpenAIResponsesImageGenerationTools_RewritesLegacyFields(t *testing.T) {
reqBody := map[string]any{
"tools": []any{
map[string]any{
"type": "image_generation",
"format": "png",
"compression": 60,
},
},
}
modified := normalizeOpenAIResponsesImageGenerationTools(reqBody)
require.True(t, modified)
tools, ok := reqBody["tools"].([]any)
require.True(t, ok)
first, ok := tools[0].(map[string]any)
require.True(t, ok)
require.Equal(t, "png", first["output_format"])
require.Equal(t, 60, first["output_compression"])
_, hasFormat := first["format"]
require.False(t, hasFormat)
_, hasCompression := first["compression"]
require.False(t, hasCompression)
}
func TestValidateOpenAIResponsesImageModel_RejectsImageOnlyModel(t *testing.T) {
err := validateOpenAIResponsesImageModel(map[string]any{
"tools": []any{
map[string]any{"type": "image_generation"},
},
}, "gpt-image-2")
require.ErrorContains(t, err, `/v1/responses image_generation requests require a Responses-capable text model`)
}
func TestApplyCodexOAuthTransform_EmptyInput(t *testing.T) { func TestApplyCodexOAuthTransform_EmptyInput(t *testing.T) {
// 空 input 应保持为空且不触发异常。 // 空 input 应保持为空且不触发异常。

View File

@@ -151,12 +151,15 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
} }
logger.L().Debug("openai chat_completions: model mapping applied", logFields...) logger.L().Debug("openai chat_completions: model mapping applied", logFields...)
if account.Type == AccountTypeOAuth { {
var reqBody map[string]any var reqBody map[string]any
if err := json.Unmarshal(responsesBody, &reqBody); err != nil { if err := json.Unmarshal(responsesBody, &reqBody); err != nil {
return nil, fmt.Errorf("unmarshal for codex transform: %w", err) return nil, fmt.Errorf("unmarshal for codex transform: %w", err)
} }
modified := false
if account.Type == AccountTypeOAuth {
codexResult := applyCodexOAuthTransform(reqBody, false, false) codexResult := applyCodexOAuthTransform(reqBody, false, false)
modified = codexResult.Modified
if codexResult.NormalizedModel != "" { if codexResult.NormalizedModel != "" {
upstreamModel = codexResult.NormalizedModel upstreamModel = codexResult.NormalizedModel
} }
@@ -165,11 +168,23 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
} else if promptCacheKey != "" { } else if promptCacheKey != "" {
reqBody["prompt_cache_key"] = promptCacheKey reqBody["prompt_cache_key"] = promptCacheKey
} }
} else {
// 非 OAuth 账号也需要提取 system 消息并注入 instructions
// 否则上游 GPT-5/Codex 等模型会报 "Instructions are required"。
if extractSystemMessagesFromInput(reqBody) {
modified = true
}
if applyInstructions(reqBody, false) {
modified = true
}
}
if modified {
responsesBody, err = json.Marshal(reqBody) responsesBody, err = json.Marshal(reqBody)
if err != nil { if err != nil {
return nil, fmt.Errorf("remarshal after codex transform: %w", err) return nil, fmt.Errorf("remarshal after codex transform: %w", err)
} }
} }
}
// 5. Get access token // 5. Get access token
token, _, err := s.GetAccessToken(ctx, account) token, _, err := s.GetAccessToken(ctx, account)

View File

@@ -1503,7 +1503,7 @@ func (s *OpenAIGatewayService) SelectAccountWithLoadAwareness(ctx context.Contex
if !acc.IsSchedulable() { if !acc.IsSchedulable() {
continue continue
} }
if requestedModel != "" && !acc.IsModelSupported(requestedModel) { if requestedModel != "" && !acc.IsOpenAIPassthroughEnabled() && !acc.IsModelSupported(requestedModel) {
continue continue
} }
if needsUpstreamCheck && s.isUpstreamModelRestrictedByChannel(ctx, *groupID, acc, requestedModel) { if needsUpstreamCheck && s.isUpstreamModelRestrictedByChannel(ctx, *groupID, acc, requestedModel) {
@@ -1665,7 +1665,7 @@ func (s *OpenAIGatewayService) resolveFreshSchedulableOpenAIAccount(ctx context.
if !fresh.IsSchedulable() || !fresh.IsOpenAI() { if !fresh.IsSchedulable() || !fresh.IsOpenAI() {
return nil return nil
} }
if requestedModel != "" && !fresh.IsModelSupported(requestedModel) { if requestedModel != "" && !fresh.IsOpenAIPassthroughEnabled() && !fresh.IsModelSupported(requestedModel) {
return nil return nil
} }
return fresh return fresh
@@ -1935,12 +1935,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
markPatchSet("instructions", "You are a helpful coding assistant.") markPatchSet("instructions", "You are a helpful coding assistant.")
} }
if normalizeOpenAIResponsesImageGenerationTools(reqBody) {
bodyModified = true
disablePatch()
logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Normalized /responses image_generation tool payload")
}
// 对所有请求执行模型映射(包含 Codex CLI // 对所有请求执行模型映射(包含 Codex CLI
billingModel := account.GetMappedModel(reqModel) billingModel := account.GetMappedModel(reqModel)
if billingModel != reqModel { if billingModel != reqModel {
@@ -1950,26 +1944,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
markPatchSet("model", billingModel) markPatchSet("model", billingModel)
} }
upstreamModel := billingModel upstreamModel := billingModel
if err := validateOpenAIResponsesImageModel(reqBody, upstreamModel); err != nil {
setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "")
c.JSON(http.StatusBadRequest, gin.H{
"error": gin.H{
"type": "invalid_request_error",
"message": err.Error(),
"param": "model",
},
})
return nil, err
}
if hasOpenAIImageGenerationTool(reqBody) {
logger.LegacyPrintf(
"service.openai_gateway",
"[OpenAI] /responses image_generation request inbound_model=%s mapped_model=%s account_type=%s",
reqModel,
upstreamModel,
account.Type,
)
}
// OpenAI OAuth 账号走 ChatGPT internal Codex endpoint需要将模型名规范化为 // OpenAI OAuth 账号走 ChatGPT internal Codex endpoint需要将模型名规范化为
// 上游可识别的 Codex/GPT 系列。API Key 账号则应保留原始/映射后的模型名, // 上游可识别的 Codex/GPT 系列。API Key 账号则应保留原始/映射后的模型名,

View File

@@ -47,9 +47,6 @@ const (
openAIImageBackendUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" openAIImageBackendUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
openAIImageRequirementsDiff = "0fffff" openAIImageRequirementsDiff = "0fffff"
openAIImageLifecycleTimeout = 2 * time.Minute
openAIImageMaxDownloadBytes = 20 << 20 // 20MB per image download
openAIImageMaxUploadPartSize = 20 << 20 // 20MB per multipart upload part
) )
type OpenAIImagesCapability string type OpenAIImagesCapability string
@@ -151,9 +148,6 @@ func (s *OpenAIGatewayService) ParseOpenAIImagesRequest(c *gin.Context, body []b
} }
applyOpenAIImagesDefaults(req) applyOpenAIImagesDefaults(req)
if err := validateOpenAIImagesModel(req.Model); err != nil {
return nil, err
}
req.SizeTier = normalizeOpenAIImageSizeTier(req.Size) req.SizeTier = normalizeOpenAIImageSizeTier(req.Size)
req.RequiredCapability = classifyOpenAIImagesCapability(req) req.RequiredCapability = classifyOpenAIImagesCapability(req)
return req, nil return req, nil
@@ -220,7 +214,7 @@ func parseOpenAIImagesMultipartRequest(body []byte, contentType string, req *Ope
continue continue
} }
data, err := io.ReadAll(io.LimitReader(part, openAIImageMaxUploadPartSize)) data, err := io.ReadAll(part)
_ = part.Close() _ = part.Close()
if err != nil { if err != nil {
return fmt.Errorf("read multipart field %s: %w", name, err) return fmt.Errorf("read multipart field %s: %w", name, err)
@@ -301,21 +295,6 @@ func applyOpenAIImagesDefaults(req *OpenAIImagesRequest) {
req.Model = "gpt-image-2" req.Model = "gpt-image-2"
} }
func isOpenAIImageGenerationModel(model string) bool {
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(model)), "gpt-image-")
}
func validateOpenAIImagesModel(model string) error {
model = strings.TrimSpace(model)
if isOpenAIImageGenerationModel(model) {
return nil
}
if model == "" {
return fmt.Errorf("images endpoint requires an image model")
}
return fmt.Errorf("images endpoint requires an image model, got %q", model)
}
func normalizeOpenAIImagesEndpointPath(path string) string { func normalizeOpenAIImagesEndpointPath(path string) string {
trimmed := strings.TrimSpace(path) trimmed := strings.TrimSpace(path)
switch { switch {
@@ -421,21 +400,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey(
if mapped := strings.TrimSpace(channelMappedModel); mapped != "" { if mapped := strings.TrimSpace(channelMappedModel); mapped != "" {
requestModel = mapped requestModel = mapped
} }
if err := validateOpenAIImagesModel(requestModel); err != nil {
return nil, err
}
upstreamModel := account.GetMappedModel(requestModel) upstreamModel := account.GetMappedModel(requestModel)
if err := validateOpenAIImagesModel(upstreamModel); err != nil {
return nil, err
}
logger.LegacyPrintf(
"service.openai_gateway",
"[OpenAI] Images request routing request_model=%s upstream_model=%s endpoint=%s account_type=%s",
strings.TrimSpace(parsed.Model),
upstreamModel,
parsed.Endpoint,
account.Type,
)
forwardBody, forwardContentType, err := rewriteOpenAIImagesModel(body, parsed.ContentType, upstreamModel) forwardBody, forwardContentType, err := rewriteOpenAIImagesModel(body, parsed.ContentType, upstreamModel)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -794,17 +759,6 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth(
if mapped := strings.TrimSpace(channelMappedModel); mapped != "" { if mapped := strings.TrimSpace(channelMappedModel); mapped != "" {
requestModel = mapped requestModel = mapped
} }
if err := validateOpenAIImagesModel(requestModel); err != nil {
return nil, err
}
logger.LegacyPrintf(
"service.openai_gateway",
"[OpenAI] Images request routing request_model=%s endpoint=%s account_type=%s uploads=%d",
requestModel,
parsed.Endpoint,
account.Type,
len(parsed.Uploads),
)
token, _, err := s.GetAccessToken(ctx, account) token, _, err := s.GetAccessToken(ctx, account)
if err != nil { if err != nil {
@@ -890,18 +844,8 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth(
return nil, err return nil, err
} }
pointerInfos = mergeOpenAIImagePointerInfos(pointerInfos, nil) pointerInfos = mergeOpenAIImagePointerInfos(pointerInfos, nil)
logger.LegacyPrintf(
"service.openai_gateway",
"[OpenAI] Image extraction stream conversation_id=%s total_assets=%d file_service_assets=%d direct_assets=%d",
conversationID,
len(pointerInfos),
countOpenAIFileServicePointerInfos(pointerInfos),
countOpenAIDirectImageAssets(pointerInfos),
)
lifecycleCtx, releaseLifecycleCtx := detachOpenAIImageLifecycleContext(ctx, openAIImageLifecycleTimeout)
defer releaseLifecycleCtx()
if conversationID != "" && !hasOpenAIFileServicePointerInfos(pointerInfos) { if conversationID != "" && !hasOpenAIFileServicePointerInfos(pointerInfos) {
polledPointers, pollErr := pollOpenAIImageConversation(lifecycleCtx, client, headers, conversationID) polledPointers, pollErr := pollOpenAIImageConversation(ctx, client, headers, conversationID)
if pollErr != nil { if pollErr != nil {
return nil, s.wrapOpenAIImageBackendError(ctx, c, account, pollErr) return nil, s.wrapOpenAIImageBackendError(ctx, c, account, pollErr)
} }
@@ -909,11 +853,10 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth(
} }
pointerInfos = preferOpenAIFileServicePointerInfos(pointerInfos) pointerInfos = preferOpenAIFileServicePointerInfos(pointerInfos)
if len(pointerInfos) == 0 { if len(pointerInfos) == 0 {
logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Image extraction yielded no assets conversation_id=%s", conversationID)
return nil, fmt.Errorf("openai image conversation returned no downloadable images") return nil, fmt.Errorf("openai image conversation returned no downloadable images")
} }
responseBody, imageCount, err := buildOpenAIImageResponse(lifecycleCtx, client, headers, conversationID, pointerInfos) responseBody, imageCount, err := buildOpenAIImageResponse(ctx, client, headers, conversationID, pointerInfos)
if err != nil { if err != nil {
return nil, s.wrapOpenAIImageBackendError(ctx, c, account, err) return nil, s.wrapOpenAIImageBackendError(ctx, c, account, err)
} }
@@ -1341,9 +1284,6 @@ func buildOpenAIImageConversationRequest(parsed *OpenAIImagesRequest, parentMess
type openAIImagePointerInfo struct { type openAIImagePointerInfo struct {
Pointer string Pointer string
DownloadURL string
B64JSON string
MimeType string
Prompt string Prompt string
} }
@@ -1396,6 +1336,10 @@ func collectOpenAIImagePointers(body []byte) []openAIImagePointerInfo {
if len(body) == 0 { if len(body) == 0 {
return nil return nil
} }
matches := openAIImagePointerMatches(body)
if len(matches) == 0 {
return nil
}
prompt := "" prompt := ""
for _, path := range []string{ for _, path := range []string{
"message.metadata.dalle.prompt", "message.metadata.dalle.prompt",
@@ -1407,12 +1351,11 @@ func collectOpenAIImagePointers(body []byte) []openAIImagePointerInfo {
break break
} }
} }
matches := openAIImagePointerMatches(body)
out := make([]openAIImagePointerInfo, 0, len(matches)) out := make([]openAIImagePointerInfo, 0, len(matches))
for _, pointer := range matches { for _, pointer := range matches {
out = append(out, openAIImagePointerInfo{Pointer: pointer, Prompt: prompt}) out = append(out, openAIImagePointerInfo{Pointer: pointer, Prompt: prompt})
} }
return mergeOpenAIImagePointerInfos(out, collectOpenAIImageInlineAssets(body, prompt)) return out
} }
func openAIImagePointerMatches(body []byte) []string { func openAIImagePointerMatches(body []byte) []string {
@@ -1451,72 +1394,27 @@ func mergeOpenAIImagePointerInfos(existing []openAIImagePointerInfo, next []open
seen := make(map[string]openAIImagePointerInfo, len(existing)+len(next)) seen := make(map[string]openAIImagePointerInfo, len(existing)+len(next))
out := make([]openAIImagePointerInfo, 0, len(existing)+len(next)) out := make([]openAIImagePointerInfo, 0, len(existing)+len(next))
for _, item := range existing { for _, item := range existing {
if key := item.identityKey(); key != "" { seen[item.Pointer] = item
seen[key] = item
}
out = append(out, item) out = append(out, item)
} }
for _, item := range next { for _, item := range next {
key := item.identityKey() if existingItem, ok := seen[item.Pointer]; ok {
if key == "" { if existingItem.Prompt == "" && item.Prompt != "" {
continue
}
if existingItem, ok := seen[key]; ok {
merged := mergeOpenAIImagePointerInfo(existingItem, item)
if merged != existingItem {
for i := range out { for i := range out {
if out[i].identityKey() == key { if out[i].Pointer == item.Pointer {
out[i] = merged out[i].Prompt = item.Prompt
break break
} }
} }
seen[key] = merged
} }
continue continue
} }
seen[key] = item seen[item.Pointer] = item
out = append(out, item) out = append(out, item)
} }
return out return out
} }
func (i openAIImagePointerInfo) identityKey() string {
switch {
case strings.TrimSpace(i.Pointer) != "":
return "pointer:" + strings.TrimSpace(i.Pointer)
case strings.TrimSpace(i.DownloadURL) != "":
return "download:" + strings.TrimSpace(i.DownloadURL)
case strings.TrimSpace(i.B64JSON) != "":
b64 := strings.TrimSpace(i.B64JSON)
if len(b64) > 64 {
b64 = b64[:64]
}
return "b64:" + b64
default:
return ""
}
}
func mergeOpenAIImagePointerInfo(existing, next openAIImagePointerInfo) openAIImagePointerInfo {
merged := existing
if strings.TrimSpace(merged.Pointer) == "" {
merged.Pointer = next.Pointer
}
if strings.TrimSpace(merged.DownloadURL) == "" {
merged.DownloadURL = next.DownloadURL
}
if strings.TrimSpace(merged.B64JSON) == "" {
merged.B64JSON = next.B64JSON
}
if strings.TrimSpace(merged.MimeType) == "" {
merged.MimeType = next.MimeType
}
if strings.TrimSpace(merged.Prompt) == "" {
merged.Prompt = next.Prompt
}
return merged
}
func hasOpenAIFileServicePointerInfos(items []openAIImagePointerInfo) bool { func hasOpenAIFileServicePointerInfos(items []openAIImagePointerInfo) bool {
for _, item := range items { for _, item := range items {
if strings.HasPrefix(item.Pointer, "file-service://") { if strings.HasPrefix(item.Pointer, "file-service://") {
@@ -1526,26 +1424,6 @@ func hasOpenAIFileServicePointerInfos(items []openAIImagePointerInfo) bool {
return false return false
} }
func countOpenAIFileServicePointerInfos(items []openAIImagePointerInfo) int {
count := 0
for _, item := range items {
if strings.HasPrefix(item.Pointer, "file-service://") {
count++
}
}
return count
}
func countOpenAIDirectImageAssets(items []openAIImagePointerInfo) int {
count := 0
for _, item := range items {
if strings.TrimSpace(item.DownloadURL) != "" || strings.TrimSpace(item.B64JSON) != "" {
count++
}
}
return count
}
func preferOpenAIFileServicePointerInfos(items []openAIImagePointerInfo) []openAIImagePointerInfo { func preferOpenAIFileServicePointerInfos(items []openAIImagePointerInfo) []openAIImagePointerInfo {
if !hasOpenAIFileServicePointerInfos(items) { if !hasOpenAIFileServicePointerInfos(items) {
return items return items
@@ -1713,7 +1591,11 @@ func buildOpenAIImageResponse(
} }
items := make([]responseItem, 0, len(pointers)) items := make([]responseItem, 0, len(pointers))
for _, pointer := range pointers { for _, pointer := range pointers {
data, err := resolveOpenAIImageBytes(ctx, client, headers, conversationID, pointer) downloadURL, err := fetchOpenAIImageDownloadURL(ctx, client, headers, conversationID, pointer.Pointer)
if err != nil {
return nil, 0, err
}
data, err := downloadOpenAIImageBytes(ctx, client, headers, downloadURL)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
@@ -1733,136 +1615,6 @@ func buildOpenAIImageResponse(
return body, len(items), nil return body, len(items), nil
} }
func resolveOpenAIImageBytes(
ctx context.Context,
client *req.Client,
headers http.Header,
conversationID string,
pointer openAIImagePointerInfo,
) ([]byte, error) {
if normalized := normalizeOpenAIImageBase64(pointer.B64JSON); normalized != "" {
return base64.StdEncoding.DecodeString(normalized)
}
if downloadURL := strings.TrimSpace(pointer.DownloadURL); downloadURL != "" {
return downloadOpenAIImageBytes(ctx, client, headers, downloadURL)
}
if strings.TrimSpace(pointer.Pointer) == "" {
return nil, fmt.Errorf("image asset is missing pointer, url, and base64 data")
}
downloadURL, err := fetchOpenAIImageDownloadURL(ctx, client, headers, conversationID, pointer.Pointer)
if err != nil {
return nil, err
}
return downloadOpenAIImageBytes(ctx, client, headers, downloadURL)
}
func normalizeOpenAIImageBase64(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
if strings.HasPrefix(strings.ToLower(raw), "data:") {
if idx := strings.Index(raw, ","); idx >= 0 && idx+1 < len(raw) {
raw = raw[idx+1:]
}
}
raw = strings.TrimSpace(raw)
raw = strings.TrimRight(raw, "=") + strings.Repeat("=", (4-len(raw)%4)%4)
if raw == "" {
return ""
}
if _, err := base64.StdEncoding.DecodeString(raw); err != nil {
return ""
}
return raw
}
func collectOpenAIImageInlineAssets(body []byte, fallbackPrompt string) []openAIImagePointerInfo {
if len(body) == 0 || !gjson.ValidBytes(body) {
return nil
}
var decoded any
if err := json.Unmarshal(body, &decoded); err != nil {
return nil
}
var out []openAIImagePointerInfo
walkOpenAIImageInlineAssets(decoded, strings.TrimSpace(fallbackPrompt), &out)
return out
}
func walkOpenAIImageInlineAssets(node any, prompt string, out *[]openAIImagePointerInfo) {
switch value := node.(type) {
case map[string]any:
localPrompt := prompt
for _, key := range []string{"revised_prompt", "image_gen_title", "prompt"} {
if v, ok := value[key].(string); ok && strings.TrimSpace(v) != "" {
localPrompt = strings.TrimSpace(v)
break
}
}
item := openAIImagePointerInfo{
Prompt: localPrompt,
Pointer: firstNonEmptyString(value["asset_pointer"], value["pointer"]),
DownloadURL: firstNonEmptyString(value["download_url"], value["url"], value["image_url"]),
B64JSON: firstNonEmptyString(value["b64_json"], value["base64"], value["image_base64"]),
MimeType: firstNonEmptyString(value["mime_type"], value["mimeType"], value["content_type"]),
}
switch {
case strings.HasPrefix(strings.TrimSpace(item.Pointer), "file-service://"),
strings.HasPrefix(strings.TrimSpace(item.Pointer), "sediment://"),
isLikelyOpenAIImageDownloadURL(item.DownloadURL),
normalizeOpenAIImageBase64(item.B64JSON) != "":
*out = append(*out, item)
}
for _, child := range value {
walkOpenAIImageInlineAssets(child, localPrompt, out)
}
case []any:
for _, child := range value {
walkOpenAIImageInlineAssets(child, prompt, out)
}
}
}
func firstNonEmptyString(values ...any) string {
for _, value := range values {
if s, ok := value.(string); ok && strings.TrimSpace(s) != "" {
return strings.TrimSpace(s)
}
}
return ""
}
func isLikelyOpenAIImageDownloadURL(raw string) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
return false
}
if strings.HasPrefix(strings.ToLower(raw), "data:image/") {
return true
}
if !strings.HasPrefix(strings.ToLower(raw), "http://") && !strings.HasPrefix(strings.ToLower(raw), "https://") {
return false
}
lower := strings.ToLower(raw)
return strings.Contains(lower, "/download") ||
strings.Contains(lower, ".png") ||
strings.Contains(lower, ".jpg") ||
strings.Contains(lower, ".jpeg") ||
strings.Contains(lower, ".webp")
}
func detachOpenAIImageLifecycleContext(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
base := context.Background()
if ctx != nil {
base = context.WithoutCancel(ctx)
}
if timeout <= 0 {
return base, func() {}
}
return context.WithTimeout(base, timeout)
}
func fetchOpenAIImageDownloadURL( func fetchOpenAIImageDownloadURL(
ctx context.Context, ctx context.Context,
client *req.Client, client *req.Client,
@@ -1954,7 +1706,7 @@ func downloadOpenAIImageBytes(ctx context.Context, client *req.Client, headers h
if resp.StatusCode < 200 || resp.StatusCode >= 300 { if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, newOpenAIImageStatusError(resp, "download image bytes failed") return nil, newOpenAIImageStatusError(resp, "download image bytes failed")
} }
return io.ReadAll(io.LimitReader(resp.Body, openAIImageMaxDownloadBytes)) return io.ReadAll(resp.Body)
} }
func handleOpenAIImageBackendError(resp *req.Response) error { func handleOpenAIImageBackendError(resp *req.Response) error {

View File

@@ -2,7 +2,6 @@ package service
import ( import (
"bytes" "bytes"
"context"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -104,56 +103,3 @@ func TestOpenAIGatewayServiceParseOpenAIImagesRequest_ExplicitSizeRequiresNative
require.NotNil(t, parsed) require.NotNil(t, parsed)
require.Equal(t, OpenAIImagesCapabilityNative, parsed.RequiredCapability) require.Equal(t, OpenAIImagesCapabilityNative, parsed.RequiredCapability)
} }
func TestOpenAIGatewayServiceParseOpenAIImagesRequest_RejectsNonImageModel(t *testing.T) {
gin.SetMode(gin.TestMode)
body := []byte(`{"model":"gpt-5.4","prompt":"draw a cat"}`)
req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = req
svc := &OpenAIGatewayService{}
parsed, err := svc.ParseOpenAIImagesRequest(c, body)
require.Nil(t, parsed)
require.ErrorContains(t, err, `images endpoint requires an image model, got "gpt-5.4"`)
}
func TestCollectOpenAIImagePointers_RecognizesDirectAssets(t *testing.T) {
items := collectOpenAIImagePointers([]byte(`{
"revised_prompt": "cat astronaut",
"parts": [
{"b64_json":"QUJD"},
{"download_url":"https://files.example.com/image.png?sig=1"},
{"asset_pointer":"file-service://file_123"}
]
}`))
require.Len(t, items, 3)
var sawBase64, sawURL, sawPointer bool
for _, item := range items {
if item.B64JSON == "QUJD" {
sawBase64 = true
require.Equal(t, "cat astronaut", item.Prompt)
}
if item.DownloadURL == "https://files.example.com/image.png?sig=1" {
sawURL = true
}
if item.Pointer == "file-service://file_123" {
sawPointer = true
}
}
require.True(t, sawBase64)
require.True(t, sawURL)
require.True(t, sawPointer)
}
func TestResolveOpenAIImageBytes_PrefersInlineBase64(t *testing.T) {
data, err := resolveOpenAIImageBytes(context.Background(), nil, nil, "", openAIImagePointerInfo{
B64JSON: "data:image/png;base64,QUJD",
})
require.NoError(t, err)
require.Equal(t, []byte("ABC"), data)
}

View File

@@ -91,7 +91,6 @@ func TestNormalizeCodexModel(t *testing.T) {
"gpt-5.3-codex-spark-high": "gpt-5.3-codex-spark", "gpt-5.3-codex-spark-high": "gpt-5.3-codex-spark",
"gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex-spark", "gpt-5.3-codex-spark-xhigh": "gpt-5.3-codex-spark",
"gpt-5.3": "gpt-5.3-codex", "gpt-5.3": "gpt-5.3-codex",
"gpt-image-2": "gpt-image-2",
} }
for input, expected := range cases { for input, expected := range cases {

View File

@@ -812,16 +812,6 @@ func (s *PricingService) matchOpenAIModel(model string) *LiteLLMModelPricing {
return openAIGPT54FallbackPricing return openAIGPT54FallbackPricing
} }
if isOpenAIImageGenerationModel(model) {
for _, candidate := range []string{"gpt-image-2", "gpt-image-1.5", "gpt-image-1"} {
if pricing, ok := s.pricingData[candidate]; ok {
logger.LegacyPrintf("service.pricing", "[Pricing] OpenAI image fallback matched %s -> %s", model, candidate)
return pricing
}
}
return nil
}
// 最终回退到 DefaultTestModel // 最终回退到 DefaultTestModel
defaultModel := strings.ToLower(openai.DefaultTestModel) defaultModel := strings.ToLower(openai.DefaultTestModel)
if pricing, ok := s.pricingData[defaultModel]; ok { if pricing, ok := s.pricingData[defaultModel]; ok {

View File

@@ -128,21 +128,6 @@ func TestGetModelPricing_Gpt54NanoUsesDedicatedStaticFallbackWhenRemoteMissing(t
require.Zero(t, got.LongContextInputTokenThreshold) require.Zero(t, got.LongContextInputTokenThreshold)
} }
func TestGetModelPricing_ImageModelDoesNotFallbackToTextModel(t *testing.T) {
imagePricing := &LiteLLMModelPricing{InputCostPerToken: 3}
textPricing := &LiteLLMModelPricing{InputCostPerToken: 9}
svc := &PricingService{
pricingData: map[string]*LiteLLMModelPricing{
"gpt-image-2": imagePricing,
"gpt-5.4": textPricing,
},
}
got := svc.GetModelPricing("gpt-image-3")
require.Same(t, imagePricing, got)
}
func TestParsePricingData_PreservesPriorityAndServiceTierFields(t *testing.T) { func TestParsePricingData_PreservesPriorityAndServiceTierFields(t *testing.T) {
raw := map[string]any{ raw := map[string]any{
"gpt-5.4": map[string]any{ "gpt-5.4": map[string]any{

View File

@@ -73,6 +73,9 @@ func (m *sessionWindowMockRepo) GetByCRSAccountID(context.Context, string) (*Acc
func (m *sessionWindowMockRepo) FindByExtraField(context.Context, string, any) ([]Account, error) { func (m *sessionWindowMockRepo) FindByExtraField(context.Context, string, any) ([]Account, error) {
panic("unexpected") panic("unexpected")
} }
func (m *sessionWindowMockRepo) CountByTLSFingerprintProfile(context.Context) (map[int64]int, error) {
panic("unexpected")
}
func (m *sessionWindowMockRepo) ListCRSAccountIDs(context.Context) (map[string]int64, error) { func (m *sessionWindowMockRepo) ListCRSAccountIDs(context.Context) (map[string]int64, error) {
panic("unexpected") panic("unexpected")
} }

View File

@@ -628,16 +628,20 @@ func (s *SettingService) SetVersion(version string) {
s.version = version s.version = version
} }
// GetPublicSettingsForInjection returns public settings in a format suitable for HTML injection // PublicSettingsInjectionPayload is the JSON shape embedded into HTML as
// This implements the web.PublicSettingsProvider interface // `window.__APP_CONFIG__` so the frontend can hydrate feature flags & site
func (s *SettingService) GetPublicSettingsForInjection(ctx context.Context) (any, error) { // config before the first XHR finishes.
settings, err := s.GetPublicSettings(ctx) //
if err != nil { // INVARIANT: every `json` tag here MUST also exist on handler/dto.PublicSettings.
return nil, err // If you forget a feature-flag field here, the frontend's
} // `cachedPublicSettings.xxx_enabled` will be `undefined` on refresh until the
// async `/api/v1/settings/public` call returns — which causes opt-in menus
// Return a struct that matches the frontend's expected format // (strict `=== true`) to flicker off/on. See
return &struct { // frontend/src/utils/featureFlags.ts for the matching registry.
//
// A unit test diffs this struct's JSON keys against dto.PublicSettings to catch
// drift automatically (see setting_service_injection_test.go).
type PublicSettingsInjectionPayload struct {
RegistrationEnabled bool `json:"registration_enabled"` RegistrationEnabled bool `json:"registration_enabled"`
EmailVerifyEnabled bool `json:"email_verify_enabled"` EmailVerifyEnabled bool `json:"email_verify_enabled"`
RegistrationEmailSuffixWhitelist []string `json:"registration_email_suffix_whitelist"` RegistrationEmailSuffixWhitelist []string `json:"registration_email_suffix_whitelist"`
@@ -646,17 +650,17 @@ func (s *SettingService) GetPublicSettingsForInjection(ctx context.Context) (any
InvitationCodeEnabled bool `json:"invitation_code_enabled"` InvitationCodeEnabled bool `json:"invitation_code_enabled"`
TotpEnabled bool `json:"totp_enabled"` TotpEnabled bool `json:"totp_enabled"`
TurnstileEnabled bool `json:"turnstile_enabled"` TurnstileEnabled bool `json:"turnstile_enabled"`
TurnstileSiteKey string `json:"turnstile_site_key,omitempty"` TurnstileSiteKey string `json:"turnstile_site_key"`
SiteName string `json:"site_name"` SiteName string `json:"site_name"`
SiteLogo string `json:"site_logo,omitempty"` SiteLogo string `json:"site_logo"`
SiteSubtitle string `json:"site_subtitle,omitempty"` SiteSubtitle string `json:"site_subtitle"`
APIBaseURL string `json:"api_base_url,omitempty"` APIBaseURL string `json:"api_base_url"`
ContactInfo string `json:"contact_info,omitempty"` ContactInfo string `json:"contact_info"`
DocURL string `json:"doc_url,omitempty"` DocURL string `json:"doc_url"`
HomeContent string `json:"home_content,omitempty"` HomeContent string `json:"home_content"`
HideCcsImportButton bool `json:"hide_ccs_import_button"` HideCcsImportButton bool `json:"hide_ccs_import_button"`
PurchaseSubscriptionEnabled bool `json:"purchase_subscription_enabled"` PurchaseSubscriptionEnabled bool `json:"purchase_subscription_enabled"`
PurchaseSubscriptionURL string `json:"purchase_subscription_url,omitempty"` PurchaseSubscriptionURL string `json:"purchase_subscription_url"`
TableDefaultPageSize int `json:"table_default_page_size"` TableDefaultPageSize int `json:"table_default_page_size"`
TablePageSizeOptions []int `json:"table_page_size_options"` TablePageSizeOptions []int `json:"table_page_size_options"`
CustomMenuItems json.RawMessage `json:"custom_menu_items"` CustomMenuItems json.RawMessage `json:"custom_menu_items"`
@@ -666,18 +670,34 @@ func (s *SettingService) GetPublicSettingsForInjection(ctx context.Context) (any
WeChatOAuthOpenEnabled bool `json:"wechat_oauth_open_enabled"` WeChatOAuthOpenEnabled bool `json:"wechat_oauth_open_enabled"`
WeChatOAuthMPEnabled bool `json:"wechat_oauth_mp_enabled"` WeChatOAuthMPEnabled bool `json:"wechat_oauth_mp_enabled"`
WeChatOAuthMobileEnabled bool `json:"wechat_oauth_mobile_enabled"` WeChatOAuthMobileEnabled bool `json:"wechat_oauth_mobile_enabled"`
BackendModeEnabled bool `json:"backend_mode_enabled"`
PaymentEnabled bool `json:"payment_enabled"`
OIDCOAuthEnabled bool `json:"oidc_oauth_enabled"` OIDCOAuthEnabled bool `json:"oidc_oauth_enabled"`
OIDCOAuthProviderName string `json:"oidc_oauth_provider_name"` OIDCOAuthProviderName string `json:"oidc_oauth_provider_name"`
Version string `json:"version,omitempty"` BackendModeEnabled bool `json:"backend_mode_enabled"`
PaymentEnabled bool `json:"payment_enabled"`
Version string `json:"version"`
BalanceLowNotifyEnabled bool `json:"balance_low_notify_enabled"` BalanceLowNotifyEnabled bool `json:"balance_low_notify_enabled"`
AccountQuotaNotifyEnabled bool `json:"account_quota_notify_enabled"` AccountQuotaNotifyEnabled bool `json:"account_quota_notify_enabled"`
BalanceLowNotifyThreshold float64 `json:"balance_low_notify_threshold"` BalanceLowNotifyThreshold float64 `json:"balance_low_notify_threshold"`
BalanceLowNotifyRechargeURL string `json:"balance_low_notify_recharge_url"` BalanceLowNotifyRechargeURL string `json:"balance_low_notify_recharge_url"`
// Feature flags — MUST match the opt-in/opt-out registry in
// frontend/src/utils/featureFlags.ts. Missing a field here is the bug
// that hid the "可用渠道" menu on page refresh.
ForceEmailOnThirdPartySignup bool `json:"force_email_on_third_party_signup"`
ChannelMonitorEnabled bool `json:"channel_monitor_enabled"` ChannelMonitorEnabled bool `json:"channel_monitor_enabled"`
ChannelMonitorDefaultIntervalSeconds int `json:"channel_monitor_default_interval_seconds"`
AvailableChannelsEnabled bool `json:"available_channels_enabled"` AvailableChannelsEnabled bool `json:"available_channels_enabled"`
}{ }
// GetPublicSettingsForInjection returns public settings in a format suitable for HTML injection.
// This implements the web.PublicSettingsProvider interface.
func (s *SettingService) GetPublicSettingsForInjection(ctx context.Context) (any, error) {
settings, err := s.GetPublicSettings(ctx)
if err != nil {
return nil, err
}
return &PublicSettingsInjectionPayload{
RegistrationEnabled: settings.RegistrationEnabled, RegistrationEnabled: settings.RegistrationEnabled,
EmailVerifyEnabled: settings.EmailVerifyEnabled, EmailVerifyEnabled: settings.EmailVerifyEnabled,
RegistrationEmailSuffixWhitelist: settings.RegistrationEmailSuffixWhitelist, RegistrationEmailSuffixWhitelist: settings.RegistrationEmailSuffixWhitelist,
@@ -706,16 +726,19 @@ func (s *SettingService) GetPublicSettingsForInjection(ctx context.Context) (any
WeChatOAuthOpenEnabled: settings.WeChatOAuthOpenEnabled, WeChatOAuthOpenEnabled: settings.WeChatOAuthOpenEnabled,
WeChatOAuthMPEnabled: settings.WeChatOAuthMPEnabled, WeChatOAuthMPEnabled: settings.WeChatOAuthMPEnabled,
WeChatOAuthMobileEnabled: settings.WeChatOAuthMobileEnabled, WeChatOAuthMobileEnabled: settings.WeChatOAuthMobileEnabled,
BackendModeEnabled: settings.BackendModeEnabled,
PaymentEnabled: settings.PaymentEnabled,
OIDCOAuthEnabled: settings.OIDCOAuthEnabled, OIDCOAuthEnabled: settings.OIDCOAuthEnabled,
OIDCOAuthProviderName: settings.OIDCOAuthProviderName, OIDCOAuthProviderName: settings.OIDCOAuthProviderName,
BackendModeEnabled: settings.BackendModeEnabled,
PaymentEnabled: settings.PaymentEnabled,
Version: s.version, Version: s.version,
BalanceLowNotifyEnabled: settings.BalanceLowNotifyEnabled, BalanceLowNotifyEnabled: settings.BalanceLowNotifyEnabled,
AccountQuotaNotifyEnabled: settings.AccountQuotaNotifyEnabled, AccountQuotaNotifyEnabled: settings.AccountQuotaNotifyEnabled,
BalanceLowNotifyThreshold: settings.BalanceLowNotifyThreshold, BalanceLowNotifyThreshold: settings.BalanceLowNotifyThreshold,
BalanceLowNotifyRechargeURL: settings.BalanceLowNotifyRechargeURL, BalanceLowNotifyRechargeURL: settings.BalanceLowNotifyRechargeURL,
ForceEmailOnThirdPartySignup: settings.ForceEmailOnThirdPartySignup,
ChannelMonitorEnabled: settings.ChannelMonitorEnabled, ChannelMonitorEnabled: settings.ChannelMonitorEnabled,
ChannelMonitorDefaultIntervalSeconds: settings.ChannelMonitorDefaultIntervalSeconds,
AvailableChannelsEnabled: settings.AvailableChannelsEnabled, AvailableChannelsEnabled: settings.AvailableChannelsEnabled,
}, nil }, nil
} }

View File

@@ -0,0 +1,36 @@
-- Migration: 114_fix_claude_code_template_userid
-- 113 的 seed 使用 legacy 格式的 metadata.user_id但已部署环境此前是手工建的
-- 「Claude Code 伪装」模板(用新版 JSON-string 格式 user_id113 的 ON CONFLICT
-- DO NOTHING 不会覆盖。本 migration 定向修复这一条历史记录及其下游监控快照。
--
-- 安全性WHERE 条件同时匹配 (provider, name) + user_id 以 '{' 开头,
-- 所以:
-- - 用户自己改过 user_id或者 seed 本来就是 legacy→ LIKE 不中,保持原状
-- - 用户改过 template name / provider → WHERE 不中,完全跳过
-- 幂等:第二次跑时 user_id 已经是 legacy 格式LIKE '{%' 不中UPDATE 0 行。
UPDATE channel_monitor_request_templates
SET body_override = jsonb_set(
body_override,
'{metadata,user_id}',
'"user_0000000000000000000000000000000000000000000000000000000000000000_account_00000000-0000-0000-0000-000000000000_session_00000000-0000-0000-0000-000000000000"'::jsonb,
false
),
updated_at = NOW()
WHERE provider = 'anthropic'
AND name = 'Claude Code 伪装'
AND body_override #>> '{metadata,user_id}' LIKE '{%';
-- 同步已应用此模板的监控快照(监控采用 snapshot 语义,只更新那些明显还是 seed 原样的)。
UPDATE channel_monitors m
SET body_override = jsonb_set(
m.body_override,
'{metadata,user_id}',
'"user_0000000000000000000000000000000000000000000000000000000000000000_account_00000000-0000-0000-0000-000000000000_session_00000000-0000-0000-0000-000000000000"'::jsonb,
false
)
FROM channel_monitor_request_templates t
WHERE m.template_id = t.id
AND t.provider = 'anthropic'
AND t.name = 'Claude Code 伪装'
AND m.body_override #>> '{metadata,user_id}' LIKE '{%';

View File

@@ -0,0 +1,40 @@
-- Migration: 115_cleanup_claude_code_mimicry_fields
-- 清理 "Claude Code CLI 模拟套件 (A)" + "Signature Pool (B)" 回滚后遗留的 DB 状态。
--
-- 涉及回滚的功能:
-- - 6d0e0562 feat(fingerprint): Claude Code CLI fingerprint mimicry suite
-- - cfd95669 feat(tls-fingerprint): show binding count + fix randomized fingerprint visibility
-- - 2df77c16/78de54b6/89d14a2 等 Signature Pool 相关 commits
--
-- 需要清理的字段:
-- 1. accounts.extra->>'tls_fingerprint_randomized' — cfd95669 引入的随机指纹标记
-- 2. accounts.extra->>'metadata' (内含 user_id) — sticky session UUID per Claude OAuth account
-- 3. accounts.extra->>'sticky_session_user_id' — sticky session 备用键名(保险)
--
-- 需要清理的索引:
-- - idx_accounts_tls_fp_profile_id — 来自 migration 108加速绑定数聚合查询。
-- 回滚后绑定数 UI 已移除,索引不再被任何查询使用,删除以释放空间。
--
-- 注意:上游已存在的 tls_fingerprint_profile_id / enable_tls_fingerprint 字段保留,
-- 这些是上游 TLS fingerprint profile 功能本身的一部分,不在回滚范围内。
-- 1) 删除 cfd95669 引入的索引
DROP INDEX IF EXISTS idx_accounts_tls_fp_profile_id;
-- 2) 清理 sticky session UUID仅 Claude/Anthropic OAuth/SetupToken 账号会写入此字段)
UPDATE accounts
SET extra = extra - 'metadata'
WHERE deleted_at IS NULL
AND extra ? 'metadata';
-- 3) 清理随机指纹标记
UPDATE accounts
SET extra = extra - 'tls_fingerprint_randomized'
WHERE deleted_at IS NULL
AND extra ? 'tls_fingerprint_randomized';
-- 4) 清理可能残留的 sticky session 备用字段
UPDATE accounts
SET extra = extra - 'sticky_session_user_id'
WHERE deleted_at IS NULL
AND extra ? 'sticky_session_user_id';

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

View File

@@ -36,6 +36,22 @@ class MockResizeObserver {
globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver
// Mock matchMedia (jsdom doesn't implement it).
// Default matches=true so desktop viewport queries pass and components that
// only lazy-load on mobile render content immediately in tests.
if (typeof window !== 'undefined' && !window.matchMedia) {
window.matchMedia = (query: string): MediaQueryList => ({
matches: true,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn()
}) as MediaQueryList
}
// Vue Test Utils 全局配置 // Vue Test Utils 全局配置
config.global.stubs = { config.global.stubs = {
// 可以在这里添加全局 stub // 可以在这里添加全局 stub

View File

@@ -17,7 +17,7 @@ import type {
AdminDataPayload, AdminDataPayload,
AdminDataImportResult, AdminDataImportResult,
CheckMixedChannelRequest, CheckMixedChannelRequest,
CheckMixedChannelResponse CheckMixedChannelResponse,
} from '@/types' } from '@/types'
/** /**
@@ -663,7 +663,7 @@ export const accountsAPI = {
getAntigravityDefaultModelMapping, getAntigravityDefaultModelMapping,
batchClearError, batchClearError,
batchRefresh, batchRefresh,
setPrivacy setPrivacy,
} }
export default accountsAPI export default accountsAPI

View File

@@ -698,6 +698,48 @@
</div> </div>
</div> </div>
<!-- Allow Overages (Antigravity only) -->
<div v-if="allAntigravity" class="border-t border-gray-200 pt-4 dark:border-dark-600">
<div class="flex items-center justify-between">
<div class="flex-1 pr-4">
<label
id="bulk-edit-allow-overages-label"
class="input-label mb-0"
for="bulk-edit-allow-overages-enabled"
>
{{ t('admin.accounts.allowOverages') }}
</label>
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.accounts.allowOveragesTooltip') }}
</p>
</div>
<input
v-model="enableAllowOverages"
id="bulk-edit-allow-overages-enabled"
type="checkbox"
aria-controls="bulk-edit-allow-overages-body"
class="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
/>
</div>
<div v-if="enableAllowOverages" id="bulk-edit-allow-overages-body" class="mt-3">
<button
type="button"
:class="[
'relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2',
allowOverages ? 'bg-primary-600' : 'bg-gray-200 dark:bg-dark-600'
]"
@click="allowOverages = !allowOverages"
>
<span
:class="[
'pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',
allowOverages ? 'translate-x-5' : 'translate-x-0'
]"
/>
</button>
</div>
</div>
<!-- RPM Limit (仅全部为 Anthropic OAuth/SetupToken 时显示) --> <!-- RPM Limit (仅全部为 Anthropic OAuth/SetupToken 时显示) -->
<div v-if="allAnthropicOAuthOrSetupToken" class="border-t border-gray-200 pt-4 dark:border-dark-600"> <div v-if="allAnthropicOAuthOrSetupToken" class="border-t border-gray-200 pt-4 dark:border-dark-600">
<div class="mb-3 flex items-center justify-between"> <div class="mb-3 flex items-center justify-between">
@@ -967,6 +1009,11 @@ const allOpenAIOAuth = computed(() => {
) )
}) })
// 是否全部为 Antigravity 平台allow_overages 仅在此条件下显示)
const allAntigravity = computed(() =>
props.selectedPlatforms.length === 1 && props.selectedPlatforms[0] === 'antigravity'
)
// 是否全部为 Anthropic OAuth/SetupTokenRPM 配置仅在此条件下显示) // 是否全部为 Anthropic OAuth/SetupTokenRPM 配置仅在此条件下显示)
const allAnthropicOAuthOrSetupToken = computed(() => { const allAnthropicOAuthOrSetupToken = computed(() => {
return ( return (
@@ -1013,6 +1060,7 @@ const enableGroups = ref(false)
const enableOpenAIPassthrough = ref(false) const enableOpenAIPassthrough = ref(false)
const enableOpenAIWSMode = ref(false) const enableOpenAIWSMode = ref(false)
const enableRpmLimit = ref(false) const enableRpmLimit = ref(false)
const enableAllowOverages = ref(false)
// State - field values // State - field values
const submitting = ref(false) const submitting = ref(false)
@@ -1040,6 +1088,7 @@ const bulkBaseRpm = ref<number | null>(null)
const bulkRpmStrategy = ref<'tiered' | 'sticky_exempt'>('tiered') const bulkRpmStrategy = ref<'tiered' | 'sticky_exempt'>('tiered')
const bulkRpmStickyBuffer = ref<number | null>(null) const bulkRpmStickyBuffer = ref<number | null>(null)
const userMsgQueueMode = ref<string | null>(null) const userMsgQueueMode = ref<string | null>(null)
const allowOverages = ref(false)
const umqModeOptions = computed(() => [ const umqModeOptions = computed(() => [
{ value: '', label: t('admin.accounts.quotaControl.rpmLimit.umqModeOff') }, { value: '', label: t('admin.accounts.quotaControl.rpmLimit.umqModeOff') },
{ value: 'throttle', label: t('admin.accounts.quotaControl.rpmLimit.umqModeThrottle') }, { value: 'throttle', label: t('admin.accounts.quotaControl.rpmLimit.umqModeThrottle') },
@@ -1281,6 +1330,13 @@ const buildUpdatePayload = (): Record<string, unknown> | null => {
umqExtra.user_msg_queue_enabled = false // 清理旧字段JSONB merge umqExtra.user_msg_queue_enabled = false // 清理旧字段JSONB merge
} }
// Allow overages (Antigravity only)
if (enableAllowOverages.value) {
if (!updates.extra) updates.extra = {}
const overagesExtra = updates.extra as Record<string, unknown>
overagesExtra.allow_overages = allowOverages.value
}
return Object.keys(updates).length > 0 ? updates : null return Object.keys(updates).length > 0 ? updates : null
} }
@@ -1345,6 +1401,7 @@ const handleSubmit = async () => {
enableGroups.value || enableGroups.value ||
enableOpenAIWSMode.value || enableOpenAIWSMode.value ||
enableRpmLimit.value || enableRpmLimit.value ||
enableAllowOverages.value ||
userMsgQueueMode.value !== null userMsgQueueMode.value !== null
if (!hasAnyFieldEnabled) { if (!hasAnyFieldEnabled) {
@@ -1438,6 +1495,7 @@ watch(
enableOpenAIPassthrough.value = false enableOpenAIPassthrough.value = false
enableOpenAIWSMode.value = false enableOpenAIWSMode.value = false
enableRpmLimit.value = false enableRpmLimit.value = false
enableAllowOverages.value = false
// Reset all values // Reset all values
baseUrl.value = '' baseUrl.value = ''
@@ -1461,6 +1519,7 @@ watch(
bulkRpmStrategy.value = 'tiered' bulkRpmStrategy.value = 'tiered'
bulkRpmStickyBuffer.value = null bulkRpmStickyBuffer.value = null
userMsgQueueMode.value = null userMsgQueueMode.value = null
allowOverages.value = false
// Reset mixed channel warning state // Reset mixed channel warning state
showMixedChannelWarning.value = false showMixedChannelWarning.value = false

View File

@@ -3322,7 +3322,12 @@ watch(
if (newVal) { if (newVal) {
// Load TLS fingerprint profiles // Load TLS fingerprint profiles
adminAPI.tlsFingerprintProfiles.list() adminAPI.tlsFingerprintProfiles.list()
.then(profiles => { tlsFingerprintProfiles.value = profiles.map(p => ({ id: p.id, name: p.name })) }) .then(profiles => {
tlsFingerprintProfiles.value = profiles.map(p => ({
id: p.id,
name: p.name,
}))
})
.catch(() => { tlsFingerprintProfiles.value = [] }) .catch(() => { tlsFingerprintProfiles.value = [] })
// Modal opened - fill related models // Modal opened - fill related models
allowedModels.value = [...getModelsByPlatform(form.platform)] allowedModels.value = [...getModelsByPlatform(form.platform)]

View File

@@ -2440,7 +2440,10 @@ watch(
const loadTLSProfiles = async () => { const loadTLSProfiles = async () => {
try { try {
const profiles = await adminAPI.tlsFingerprintProfiles.list() const profiles = await adminAPI.tlsFingerprintProfiles.list()
tlsFingerprintProfiles.value = profiles.map(p => ({ id: p.id, name: p.name })) tlsFingerprintProfiles.value = profiles.map(p => ({
id: p.id,
name: p.name,
}))
} catch { } catch {
tlsFingerprintProfiles.value = [] tlsFingerprintProfiles.value = []
} }
@@ -3309,4 +3312,5 @@ const handleMixedChannelConfirm = async () => {
const handleMixedChannelCancel = () => { const handleMixedChannelCancel = () => {
clearMixedChannelDialog() clearMixedChannelDialog()
} }
</script> </script>

View File

@@ -122,7 +122,7 @@ describe('AccountStatusIndicator', () => {
} }
}) })
expect(wrapper.text()).toContain('account.creditsExhausted') expect(wrapper.text()).toContain('admin.accounts.status.creditsExhausted')
}) })
it('模型限流 + overages 启用 + AICredits key 生效 → 普通限流样式(积分耗尽,无 ⚡)', () => { it('模型限流 + overages 启用 + AICredits key 生效 → 普通限流样式(积分耗尽,无 ⚡)', () => {
@@ -157,6 +157,6 @@ describe('AccountStatusIndicator', () => {
expect(wrapper.text()).toContain('CSon45') expect(wrapper.text()).toContain('CSon45')
expect(wrapper.text()).not.toContain('⚡') expect(wrapper.text()).not.toContain('⚡')
// AICredits 积分耗尽状态应显示 // AICredits 积分耗尽状态应显示
expect(wrapper.text()).toContain('account.creditsExhausted') expect(wrapper.text()).toContain('admin.accounts.status.creditsExhausted')
}) })
}) })

View File

@@ -15,6 +15,10 @@ vi.mock('@/api/admin', () => ({
} }
})) }))
vi.mock('@/utils/usageLoadQueue', () => ({
enqueueUsageRequest: (_account: unknown, fn: () => Promise<unknown>) => fn()
}))
vi.mock('vue-i18n', async () => { vi.mock('vue-i18n', async () => {
const actual = await vi.importActual<typeof import('vue-i18n')>('vue-i18n') const actual = await vi.importActual<typeof import('vue-i18n')>('vue-i18n')
return { return {
@@ -385,6 +389,117 @@ describe('AccountUsageCell', () => {
expect(wrapper.text()).toContain('7d|0|27700') expect(wrapper.text()).toContain('7d|0|27700')
}) })
it('OpenAI OAuth 在 usage 请求失败时仍回退显示本地 codex 快照', async () => {
getUsage.mockRejectedValue(new Error('network error'))
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const wrapper = mount(AccountUsageCell, {
props: {
account: makeAccount({
id: 2004,
platform: 'openai',
type: 'oauth',
extra: {
codex_usage_updated_at: '2099-03-07T10:00:00Z',
codex_5h_used_percent: 12,
codex_5h_reset_at: '2099-03-07T12:00:00Z',
codex_7d_used_percent: 34,
codex_7d_reset_at: '2099-03-13T12:00:00Z'
}
})
},
global: {
stubs: {
UsageProgressBar: {
props: ['label', 'utilization', 'resetsAt', 'windowStats', 'color'],
template: '<div class="usage-bar">{{ label }}|{{ utilization }}|{{ resetsAt }}</div>'
},
AccountQuotaInfo: true
}
}
})
await flushPromises()
expect(getUsage).toHaveBeenCalledWith(2004)
expect(wrapper.text()).toContain('5h|12|2099-03-07T12:00:00.000Z')
expect(wrapper.text()).toContain('7d|34|2099-03-13T12:00:00.000Z')
errorSpy.mockRestore()
})
it('OpenAI OAuth 已限额时首屏优先等待重新查询的 usage而不是先显示旧 codex 快照', async () => {
let resolveUsage: ((value: any) => void) | null = null
getUsage.mockReturnValue(
new Promise((resolve) => {
resolveUsage = resolve
})
)
const wrapper = mount(AccountUsageCell, {
props: {
account: makeAccount({
id: 2005,
platform: 'openai',
type: 'oauth',
rate_limit_reset_at: '2099-03-07T12:00:00Z',
extra: {
codex_5h_used_percent: 0,
codex_5h_reset_at: '2099-03-07T12:00:00Z',
codex_7d_used_percent: 0,
codex_7d_reset_at: '2099-03-13T12:00:00Z'
}
})
},
global: {
stubs: {
UsageProgressBar: {
props: ['label', 'utilization', 'resetsAt', 'windowStats', 'color'],
template: '<div class="usage-bar">{{ label }}|{{ utilization }}|{{ windowStats?.tokens }}</div>'
},
AccountQuotaInfo: true
}
}
})
await Promise.resolve()
expect(getUsage).toHaveBeenCalledWith(2005)
expect(wrapper.text()).not.toContain('5h|0|')
expect(wrapper.text()).not.toContain('7d|0|')
resolveUsage?.({
five_hour: {
utilization: 100,
resets_at: '2026-03-07T12:00:00Z',
remaining_seconds: 3600,
window_stats: {
requests: 211,
tokens: 106540000,
cost: 38.13,
standard_cost: 38.13,
user_cost: 38.13
}
},
seven_day: {
utilization: 100,
resets_at: '2026-03-13T12:00:00Z',
remaining_seconds: 3600,
window_stats: {
requests: 211,
tokens: 106540000,
cost: 38.13,
standard_cost: 38.13,
user_cost: 38.13
}
}
})
await flushPromises()
expect(wrapper.text()).toContain('5h|100|106540000')
expect(wrapper.text()).toContain('7d|100|106540000')
})
it('OpenAI OAuth 在行数据刷新但仍无 codex 快照时会重新拉取 usage', async () => { it('OpenAI OAuth 在行数据刷新但仍无 codex 快照时会重新拉取 usage', async () => {
getUsage getUsage
.mockResolvedValueOnce({ .mockResolvedValueOnce({

View File

@@ -90,6 +90,13 @@
:unit="t(prefixKey('unitPerMillion'))" :unit="t(prefixKey('unitPerMillion'))"
:scale="perMillionScale" :scale="perMillionScale"
/> />
<PricingRow
v-if="model.pricing.image_output_price != null && model.pricing.image_output_price > 0"
:label="t(prefixKey('imageOutputPrice'))"
:value="model.pricing.image_output_price"
:unit="t(prefixKey('unitPerMillion'))"
:scale="perMillionScale"
/>
</template> </template>
<PricingRow <PricingRow

View File

@@ -1,67 +1,21 @@
<script setup lang="ts"> <script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, useTemplateRef, nextTick } from 'vue' import { ref, useTemplateRef, nextTick } from 'vue'
const props = withDefaults(defineProps<{ defineProps<{
content?: string content?: string
trigger?: 'hover' | 'click' }>()
widthClass?: string
}>(), {
trigger: 'hover',
widthClass: 'w-64',
})
const show = ref(false) const show = ref(false)
const triggerRef = useTemplateRef<HTMLElement>('trigger') const triggerRef = useTemplateRef<HTMLElement>('trigger')
const tooltipRef = useTemplateRef<HTMLElement>('tooltip')
const tooltipStyle = ref({ top: '0px', left: '0px' }) const tooltipStyle = ref({ top: '0px', left: '0px' })
function openTooltip() { function onEnter() {
show.value = true show.value = true
nextTick(updatePosition) nextTick(updatePosition)
} }
function closeTooltip() {
show.value = false
}
function onEnter() {
if (props.trigger !== 'hover') return
openTooltip()
}
function onLeave() { function onLeave() {
if (props.trigger !== 'hover') return show.value = false
closeTooltip()
}
function onClick(event: MouseEvent) {
if (props.trigger !== 'click') return
event.stopPropagation()
if (show.value) {
closeTooltip()
return
}
openTooltip()
}
function onDocumentClick(event: MouseEvent) {
if (props.trigger !== 'click' || !show.value) return
const target = event.target as Node | null
if (!target) return
if (triggerRef.value?.contains(target) || tooltipRef.value?.contains(target)) return
closeTooltip()
}
function onDocumentKeydown(event: KeyboardEvent) {
if (props.trigger !== 'click') return
if (event.key === 'Escape') {
closeTooltip()
}
}
function onViewportChange() {
if (!show.value) return
updatePosition()
} }
function updatePosition() { function updatePosition() {
@@ -73,20 +27,6 @@ function updatePosition() {
left: `${rect.left + rect.width / 2 + window.scrollX}px`, left: `${rect.left + rect.width / 2 + window.scrollX}px`,
} }
} }
onMounted(() => {
document.addEventListener('click', onDocumentClick, true)
document.addEventListener('keydown', onDocumentKeydown)
window.addEventListener('resize', onViewportChange)
window.addEventListener('scroll', onViewportChange, true)
})
onBeforeUnmount(() => {
document.removeEventListener('click', onDocumentClick, true)
document.removeEventListener('keydown', onDocumentKeydown)
window.removeEventListener('resize', onViewportChange)
window.removeEventListener('scroll', onViewportChange, true)
})
</script> </script>
<template> <template>
@@ -95,7 +35,6 @@ onBeforeUnmount(() => {
class="group relative ml-1 inline-flex items-center align-middle" class="group relative ml-1 inline-flex items-center align-middle"
@mouseenter="onEnter" @mouseenter="onEnter"
@mouseleave="onLeave" @mouseleave="onLeave"
@click="onClick"
> >
<!-- Trigger Icon --> <!-- Trigger Icon -->
<slot name="trigger"> <slot name="trigger">
@@ -117,26 +56,10 @@ onBeforeUnmount(() => {
<!-- Teleport to body to escape modal overflow clipping --> <!-- Teleport to body to escape modal overflow clipping -->
<Teleport to="body"> <Teleport to="body">
<div <div
ref="tooltip"
v-show="show" v-show="show"
role="tooltip" class="fixed z-[99999] w-64 -translate-x-1/2 -translate-y-full rounded-lg bg-gray-900 p-3 text-xs leading-relaxed text-white shadow-xl ring-1 ring-white/10 dark:bg-gray-800"
:class="[
'fixed z-[99999] -translate-x-1/2 -translate-y-full rounded-lg bg-gray-900 p-3 text-xs leading-relaxed text-white shadow-xl ring-1 ring-white/10 dark:bg-gray-800',
props.widthClass,
]"
:style="{ top: `calc(${tooltipStyle.top} - 8px)`, left: tooltipStyle.left }" :style="{ top: `calc(${tooltipStyle.top} - 8px)`, left: tooltipStyle.left }"
> >
<button
v-if="props.trigger === 'click'"
type="button"
class="absolute right-1.5 top-1.5 rounded p-1 text-gray-300 transition-colors hover:bg-white/10 hover:text-white"
aria-label="Close"
@click.stop="closeTooltip"
>
<svg class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<slot>{{ content }}</slot> <slot>{{ content }}</slot>
<div class="absolute -bottom-1 left-1/2 h-2 w-2 -translate-x-1/2 rotate-45 bg-gray-900 dark:bg-gray-800"></div> <div class="absolute -bottom-1 left-1/2 h-2 w-2 -translate-x-1/2 rotate-45 bg-gray-900 dark:bg-gray-800"></div>
</div> </div>

View File

@@ -0,0 +1,104 @@
<template>
<!-- 悬浮按钮 - 使用主题色 -->
<button
@click="showModal = true"
class="fixed bottom-6 right-6 z-50 flex items-center gap-2 rounded-full bg-gradient-to-r from-primary-500 to-primary-600 px-4 py-3 text-white shadow-lg shadow-primary-500/25 transition-all hover:from-primary-600 hover:to-primary-700 hover:shadow-xl hover:shadow-primary-500/30"
>
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 01.213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.328.328 0 00.186-.059l2.114-1.225a.87.87 0 01.415-.106.807.807 0 01.213.026 10.07 10.07 0 002.696.37c.262 0 .52-.011.776-.028a5.91 5.91 0 01-.193-1.479c0-3.644 3.374-6.6 7.536-6.6.262 0 .52.011.776.028-.628-3.513-4.27-6.472-8.885-6.472zM5.785 5.97a1.1 1.1 0 110 2.2 1.1 1.1 0 010-2.2zm5.813 0a1.1 1.1 0 110 2.2 1.1 1.1 0 010-2.2zm5.192 2.642c-3.703 0-6.71 2.567-6.71 5.73 0 3.163 3.007 5.73 6.71 5.73a7.9 7.9 0 002.126-.288.644.644 0 01.17-.022.69.69 0 01.329.085l1.672.97a.262.262 0 00.147.046c.128 0 .23-.104.23-.233a.403.403 0 00-.038-.168l-.309-1.17a.468.468 0 01.168-.527c1.449-1.065 2.374-2.643 2.374-4.423 0-3.163-3.007-5.73-6.71-5.73h-.159zm-2.434 3.34a.88.88 0 110 1.76.88.88 0 010-1.76zm4.868 0a.88.88 0 110 1.76.88.88 0 010-1.76z"/>
</svg>
<span class="text-sm font-medium">客服</span>
</button>
<!-- 弹窗 -->
<Teleport to="body">
<Transition name="fade">
<div
v-if="showModal"
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4 backdrop-blur-sm"
@click.self="showModal = false"
>
<Transition name="scale">
<div
v-if="showModal"
class="relative w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl dark:bg-dark-700"
>
<!-- 关闭按钮 -->
<button
@click="showModal = false"
class="absolute right-4 top-4 text-gray-400 transition-colors hover:text-gray-600 dark:text-dark-400 dark:hover:text-dark-200"
>
<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- 标题 -->
<div class="mb-4 flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-primary-500 to-primary-600">
<svg class="h-6 w-6 text-white" viewBox="0 0 24 24" fill="currentColor">
<path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 01.213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.328.328 0 00.186-.059l2.114-1.225a.87.87 0 01.415-.106.807.807 0 01.213.026 10.07 10.07 0 002.696.37c.262 0 .52-.011.776-.028a5.91 5.91 0 01-.193-1.479c0-3.644 3.374-6.6 7.536-6.6.262 0 .52.011.776.028-.628-3.513-4.27-6.472-8.885-6.472zM5.785 5.97a1.1 1.1 0 110 2.2 1.1 1.1 0 010-2.2zm5.813 0a1.1 1.1 0 110 2.2 1.1 1.1 0 010-2.2zm5.192 2.642c-3.703 0-6.71 2.567-6.71 5.73 0 3.163 3.007 5.73 6.71 5.73a7.9 7.9 0 002.126-.288.644.644 0 01.17-.022.69.69 0 01.329.085l1.672.97a.262.262 0 00.147.046c.128 0 .23-.104.23-.233a.403.403 0 00-.038-.168l-.309-1.17a.468.468 0 01.168-.527c1.449-1.065 2.374-2.643 2.374-4.423 0-3.163-3.007-5.73-6.71-5.73h-.159zm-2.434 3.34a.88.88 0 110 1.76.88.88 0 010-1.76zm4.868 0a.88.88 0 110 1.76.88.88 0 010-1.76z"/>
</svg>
</div>
<div>
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">联系客服</h3>
<p class="text-sm text-gray-500 dark:text-dark-400">扫码添加好友</p>
</div>
</div>
<!-- 二维码卡片 -->
<div class="mb-4 overflow-hidden rounded-xl border border-primary-100 bg-gradient-to-br from-primary-50 to-white p-3 dark:border-primary-800/30 dark:from-primary-900/10 dark:to-dark-800">
<img
src="/wechat-qr.jpg"
alt="微信二维码"
class="w-full rounded-lg"
/>
</div>
<!-- 提示文字 -->
<div class="text-center">
<p class="mb-2 text-sm font-medium text-primary-600 dark:text-primary-400">
微信扫码添加客服
</p>
<p class="flex items-center justify-center gap-1 text-xs text-gray-500 dark:text-dark-400">
<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
工作时间周一至周五 9:00-18:00
</p>
</div>
</div>
</Transition>
</div>
</Transition>
</Teleport>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const showModal = ref(false)
</script>
<style scoped>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.scale-enter-active,
.scale-leave-active {
transition: all 0.2s ease;
}
.scale-enter-from,
.scale-leave-to {
opacity: 0;
transform: scale(0.95);
}
</style>

View File

@@ -125,7 +125,6 @@
<Icon name="key" size="sm" /> <Icon name="key" size="sm" />
{{ t('nav.apiKeys') }} {{ t('nav.apiKeys') }}
</router-link> </router-link>
<a <a
v-if="authStore.isAdmin" v-if="authStore.isAdmin"
href="https://github.com/Wei-Shaw/sub2api" href="https://github.com/Wei-Shaw/sub2api"
@@ -143,7 +142,6 @@
</svg> </svg>
{{ t('nav.github') }} {{ t('nav.github') }}
</a> </a>
</div> </div>
<!-- Contact Support (only show if configured) --> <!-- Contact Support (only show if configured) -->

View File

@@ -634,18 +634,15 @@ const ChevronDownIcon = {
const flagChannelMonitor = makeSidebarFlag(FeatureFlags.channelMonitor) const flagChannelMonitor = makeSidebarFlag(FeatureFlags.channelMonitor)
const flagPayment = makeSidebarFlag(FeatureFlags.payment) const flagPayment = makeSidebarFlag(FeatureFlags.payment)
const flagAvailableChannels = makeSidebarFlag(FeatureFlags.availableChannels) const flagAvailableChannels = makeSidebarFlag(FeatureFlags.availableChannels)
void flagAvailableChannels
const flagOpsMonitoring = () => adminSettingsStore.opsMonitoringEnabled const flagOpsMonitoring = () => adminSettingsStore.opsMonitoringEnabled
const flagAdminPayment = () => adminSettingsStore.paymentEnabled const flagAdminPayment = () => adminSettingsStore.paymentEnabled
// buildSelfNavItems 构造用户自己的导航项(用户端主菜单和管理员的"我的账户"子菜单共享这组声明)。 // buildSelfNavItems 构造用户自己的导航项(用户端主菜单和管理员的"我的账户"子菜单共享这组声明)。
// withDashboard=true 时包含仪表盘用户端false 时不含(管理员的个人区已经有独立仪表盘入口)。 // withDashboard=true 时包含仪表盘用户端false 时不含(管理员的个人区已经有独立仪表盘入口)。
// includeAvailableChannels=false 时省略"可用渠道"入口——管理员在 admin 区已经有一个显眼入口,
// 重复显示会让管理员同时看到两处"可用渠道"。
// //
// 条目顺序:密钥 → 用量 → 可用渠道 → 渠道状态 → 订阅/支付 → 兑换/资料。 // 条目顺序:密钥 → 用量 → 可用渠道 → 渠道状态 → 订阅/支付 → 兑换/资料。
// 可用渠道紧挨渠道状态之上,让用户"先看自己能用什么、再看对应状态"。 // 可用渠道紧挨渠道状态之上,让用户"先看自己能用什么、再看对应状态"。
function buildSelfNavItems(withDashboard: boolean, includeAvailableChannels = true): NavItem[] { function buildSelfNavItems(withDashboard: boolean): NavItem[] {
const items: NavItem[] = [] const items: NavItem[] = []
if (withDashboard) { if (withDashboard) {
items.push({ path: '/dashboard', label: t('nav.dashboard'), icon: DashboardIcon }) items.push({ path: '/dashboard', label: t('nav.dashboard'), icon: DashboardIcon })
@@ -653,11 +650,7 @@ function buildSelfNavItems(withDashboard: boolean, includeAvailableChannels = tr
items.push( items.push(
{ path: '/keys', label: t('nav.apiKeys'), icon: KeyIcon }, { path: '/keys', label: t('nav.apiKeys'), icon: KeyIcon },
{ path: '/usage', label: t('nav.usage'), icon: ChartIcon, hideInSimpleMode: true }, { path: '/usage', label: t('nav.usage'), icon: ChartIcon, hideInSimpleMode: true },
) { path: '/available-channels', label: t('nav.availableChannels'), icon: ChannelIcon, hideInSimpleMode: true, featureFlag: flagAvailableChannels },
if (includeAvailableChannels) {
items.push({ path: '/available-channels', label: t('nav.availableChannels'), icon: ChannelIcon, hideInSimpleMode: true, featureFlag: flagAvailableChannels })
}
items.push(
{ path: '/monitor', label: t('nav.channelStatus'), icon: SignalIcon, featureFlag: flagChannelMonitor }, { path: '/monitor', label: t('nav.channelStatus'), icon: SignalIcon, featureFlag: flagChannelMonitor },
{ path: '/subscriptions', label: t('nav.mySubscriptions'), icon: CreditCardIcon, hideInSimpleMode: true }, { path: '/subscriptions', label: t('nav.mySubscriptions'), icon: CreditCardIcon, hideInSimpleMode: true },
{ path: '/purchase', label: t('nav.buySubscription'), icon: RechargeSubscriptionIcon, hideInSimpleMode: true, featureFlag: flagPayment }, { path: '/purchase', label: t('nav.buySubscription'), icon: RechargeSubscriptionIcon, hideInSimpleMode: true, featureFlag: flagPayment },
@@ -683,7 +676,9 @@ function finalizeNav(items: NavItem[]): NavItem[] {
// User navigation items (for regular users) // User navigation items (for regular users)
const userNavItems = computed((): NavItem[] => finalizeNav(buildSelfNavItems(true))) const userNavItems = computed((): NavItem[] => finalizeNav(buildSelfNavItems(true)))
// Personal navigation items (for admin's "My Account" section, without Dashboard) // Personal navigation items (for admin's "My Account" section, without Dashboard).
// Admins access 可用渠道 from this section just like regular users — there is no
// separate admin entry, since the page is purely a user-facing view.
const personalNavItems = computed((): NavItem[] => finalizeNav(buildSelfNavItems(false))) const personalNavItems = computed((): NavItem[] => finalizeNav(buildSelfNavItems(false)))
// Custom menu items filtered by visibility // Custom menu items filtered by visibility

View File

@@ -73,42 +73,9 @@
<!-- Config fields --> <!-- Config fields -->
<div class="border-t border-gray-200 pt-4 dark:border-dark-700"> <div class="border-t border-gray-200 pt-4 dark:border-dark-700">
<div class="mb-3 flex items-center gap-2"> <h4 class="mb-3 text-sm font-semibold text-gray-900 dark:text-white">
<h4 class="text-sm font-semibold text-gray-900 dark:text-white">
{{ t('admin.settings.payment.providerConfig') }} {{ t('admin.settings.payment.providerConfig') }}
</h4> </h4>
<HelpTooltip v-if="paymentGuide" trigger="click" width-class="w-80">
<template #trigger>
<button
type="button"
class="inline-flex h-5 w-5 items-center justify-center rounded-full border border-gray-300 text-[11px] font-semibold text-gray-400 transition-colors hover:border-primary-500 hover:text-primary-600 dark:border-dark-500 dark:text-gray-500 dark:hover:border-primary-400 dark:hover:text-primary-400"
:aria-label="t('admin.settings.payment.paymentGuideTrigger')"
:title="t('admin.settings.payment.paymentGuideTrigger')"
>
?
</button>
</template>
<div class="space-y-3">
<p class="font-medium text-white">{{ paymentGuide.summary }}</p>
<div
v-for="item in paymentGuide.items"
:key="item.title"
class="space-y-1.5 border-t border-white/10 pt-2 first:border-t-0 first:pt-0"
>
<p class="font-medium text-white">{{ item.title }}</p>
<p><span class="text-gray-300">{{ t('admin.settings.payment.guideOpenLabel') }}</span>{{ item.open }}</p>
<p><span class="text-gray-300">{{ t('admin.settings.payment.guideCallLabel') }}</span>{{ item.call }}</p>
<p><span class="text-gray-300">{{ t('admin.settings.payment.guideFallbackLabel') }}</span>{{ item.fallback }}</p>
</div>
<p v-if="paymentGuide.note" class="border-t border-white/10 pt-2 text-[11px] text-gray-300">
{{ paymentGuide.note }}
</p>
</div>
</HelpTooltip>
</div>
<p v-if="paymentGuide" class="mb-3 text-xs text-gray-500 dark:text-gray-400">
{{ paymentGuide.summary }}
</p>
<div class="space-y-3"> <div class="space-y-3">
<div v-for="field in resolvedFields" :key="field.key"> <div v-for="field in resolvedFields" :key="field.key">
<label class="input-label"> <label class="input-label">
@@ -253,7 +220,6 @@
import { reactive, computed, ref } from 'vue' import { reactive, computed, ref } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import BaseDialog from '@/components/common/BaseDialog.vue' import BaseDialog from '@/components/common/BaseDialog.vue'
import HelpTooltip from '@/components/common/HelpTooltip.vue'
import Select from '@/components/common/Select.vue' import Select from '@/components/common/Select.vue'
import type { SelectOption } from '@/components/common/Select.vue' import type { SelectOption } from '@/components/common/Select.vue'
import ToggleSwitch from './ToggleSwitch.vue' import ToggleSwitch from './ToggleSwitch.vue'
@@ -297,19 +263,6 @@ const emit = defineEmits<{
const { t } = useI18n() const { t } = useI18n()
interface PaymentGuideItem {
title: string
open: string
call: string
fallback: string
}
interface PaymentGuide {
summary: string
items: PaymentGuideItem[]
note?: string
}
// --- Form state --- // --- Form state ---
const form = reactive({ const form = reactive({
name: '', name: '',
@@ -361,63 +314,6 @@ const resolvedFields = computed(() => {
})) }))
}) })
const paymentGuide = computed<PaymentGuide | null>(() => {
if (form.provider_key === 'alipay') {
return {
summary: t('admin.settings.payment.alipayGuideSummary'),
items: [
{
title: t('admin.settings.payment.alipayGuideFaceToFaceTitle'),
open: t('admin.settings.payment.alipayGuideFaceToFaceOpen'),
call: t('admin.settings.payment.alipayGuideFaceToFaceCall'),
fallback: t('admin.settings.payment.alipayGuideFaceToFaceFallback'),
},
{
title: t('admin.settings.payment.alipayGuidePagePayTitle'),
open: t('admin.settings.payment.alipayGuidePagePayOpen'),
call: t('admin.settings.payment.alipayGuidePagePayCall'),
fallback: t('admin.settings.payment.alipayGuidePagePayFallback'),
},
{
title: t('admin.settings.payment.alipayGuideWapTitle'),
open: t('admin.settings.payment.alipayGuideWapOpen'),
call: t('admin.settings.payment.alipayGuideWapCall'),
fallback: t('admin.settings.payment.alipayGuideWapFallback'),
},
],
}
}
if (form.provider_key === 'wxpay') {
return {
summary: t('admin.settings.payment.wxpayGuideSummary'),
note: t('admin.settings.payment.wxpayGuideNote'),
items: [
{
title: t('admin.settings.payment.wxpayGuideNativeTitle'),
open: t('admin.settings.payment.wxpayGuideNativeOpen'),
call: t('admin.settings.payment.wxpayGuideNativeCall'),
fallback: t('admin.settings.payment.wxpayGuideNativeFallback'),
},
{
title: t('admin.settings.payment.wxpayGuideJsapiTitle'),
open: t('admin.settings.payment.wxpayGuideJsapiOpen'),
call: t('admin.settings.payment.wxpayGuideJsapiCall'),
fallback: t('admin.settings.payment.wxpayGuideJsapiFallback'),
},
{
title: t('admin.settings.payment.wxpayGuideH5Title'),
open: t('admin.settings.payment.wxpayGuideH5Open'),
call: t('admin.settings.payment.wxpayGuideH5Call'),
fallback: t('admin.settings.payment.wxpayGuideH5Fallback'),
},
],
}
}
return null
})
const limitableTypes = computed(() => { const limitableTypes = computed(() => {
// Stripe: single "stripe" entry (one set of shared limits) // Stripe: single "stripe" entry (one set of shared limits)
if (form.provider_key === 'stripe') { if (form.provider_key === 'stripe') {

View File

@@ -84,9 +84,6 @@
</div> </div>
</div> </div>
<p v-if="scanHint" class="text-center text-sm text-gray-500 dark:text-gray-400">{{ scanHint }}</p> <p v-if="scanHint" class="text-center text-sm text-gray-500 dark:text-gray-400">{{ scanHint }}</p>
<button v-if="payUrl" class="btn btn-secondary text-sm" @click="reopenPopup">
{{ t('payment.qr.openPayWindow') }}
</button>
</div> </div>
</div> </div>
<div class="card p-4 text-center"> <div class="card p-4 text-center">

View File

@@ -96,36 +96,4 @@ describe('PaymentStatusPanel', () => {
expect(wrapper.text()).toContain('payment.result.success') expect(wrapper.text()).toContain('payment.result.success')
expect(wrapper.emitted('success')).toHaveLength(1) expect(wrapper.emitted('success')).toHaveLength(1)
}) })
it('shows reopen button in QR mode when payUrl is also available', async () => {
const openSpy = vi.spyOn(window, 'open').mockReturnValue({ closed: false } as Window)
const wrapper = mount(PaymentStatusPanel, {
props: {
orderId: 42,
qrCode: 'https://pay.example.com/qr/42',
payUrl: 'https://pay.example.com/session/42',
expiresAt: '2099-01-01T12:30:00Z',
paymentType: 'alipay',
orderType: 'balance',
},
global: {
stubs: {
Icon: true,
},
},
})
await flushPromises()
expect(wrapper.text()).toContain('payment.qr.openPayWindow')
await wrapper.get('button.btn.btn-secondary.text-sm').trigger('click')
expect(openSpy).toHaveBeenCalledWith(
'https://pay.example.com/session/42',
'paymentPopup',
expect.any(String),
)
openSpy.mockRestore()
})
}) })

View File

@@ -190,14 +190,12 @@ describe('buildCreateOrderPayload', () => {
paymentType: 'alipay_direct', paymentType: 'alipay_direct',
orderType: 'balance', orderType: 'balance',
origin: 'https://app.example.com/', origin: 'https://app.example.com/',
isMobile: true,
isWechatBrowser: false, isWechatBrowser: false,
})).toEqual({ })).toEqual({
amount: 88, amount: 88,
payment_type: 'alipay', payment_type: 'alipay',
order_type: 'balance', order_type: 'balance',
return_url: 'https://app.example.com/payment/result', return_url: 'https://app.example.com/payment/result',
is_mobile: true,
payment_source: 'hosted_redirect', payment_source: 'hosted_redirect',
}) })
}) })
@@ -209,7 +207,6 @@ describe('buildCreateOrderPayload', () => {
orderType: 'subscription', orderType: 'subscription',
planId: 7, planId: 7,
origin: 'https://app.example.com', origin: 'https://app.example.com',
isMobile: false,
isWechatBrowser: true, isWechatBrowser: true,
})).toEqual({ })).toEqual({
amount: 128, amount: 128,
@@ -217,7 +214,6 @@ describe('buildCreateOrderPayload', () => {
order_type: 'subscription', order_type: 'subscription',
plan_id: 7, plan_id: 7,
return_url: 'https://app.example.com/payment/result', return_url: 'https://app.example.com/payment/result',
is_mobile: false,
payment_source: 'wechat_in_app_resume', payment_source: 'wechat_in_app_resume',
}) })
}) })

View File

@@ -12,9 +12,9 @@ describe('PROVIDER_CONFIG_FIELDS.wxpay', () => {
expect(findField('certSerial')?.optional).toBeFalsy() expect(findField('certSerial')?.optional).toBeFalsy()
}) })
it('only keeps the simplified visible credential set in the admin form', () => { it('exposes optional mp and H5 metadata fields for WeChat-specific flows', () => {
expect(findField('mpAppId')).toBeUndefined() expect(findField('mpAppId')?.optional).toBe(true)
expect(findField('h5AppName')).toBeUndefined() expect(findField('h5AppName')?.optional).toBe(true)
expect(findField('h5AppUrl')).toBeUndefined() expect(findField('h5AppUrl')?.optional).toBe(true)
}) })
}) })

View File

@@ -68,7 +68,6 @@ export interface BuildCreateOrderPayloadInput {
orderType: OrderType orderType: OrderType
planId?: number planId?: number
origin?: string origin?: string
isMobile: boolean
isWechatBrowser: boolean isWechatBrowser: boolean
} }
@@ -107,7 +106,6 @@ export function buildCreateOrderPayload(input: BuildCreateOrderPayloadInput): Cr
amount: input.amount, amount: input.amount,
payment_type: visibleMethod, payment_type: visibleMethod,
order_type: input.orderType, order_type: input.orderType,
is_mobile: input.isMobile,
payment_source: visibleMethod === 'wxpay' && input.isWechatBrowser payment_source: visibleMethod === 'wxpay' && input.isWechatBrowser
? 'wechat_in_app_resume' ? 'wechat_in_app_resume'
: 'hosted_redirect', : 'hosted_redirect',

View File

@@ -96,12 +96,15 @@ export const PROVIDER_CONFIG_FIELDS: Record<string, ConfigFieldDef[]> = {
], ],
wxpay: [ wxpay: [
{ key: 'appId', label: 'App ID', sensitive: false }, { key: 'appId', label: 'App ID', sensitive: false },
{ key: 'mpAppId', label: '', sensitive: false, optional: true },
{ key: 'mchId', label: '', sensitive: false }, { key: 'mchId', label: '', sensitive: false },
{ key: 'privateKey', label: '', sensitive: true }, { key: 'privateKey', label: '', sensitive: true },
{ key: 'apiV3Key', label: '', sensitive: true }, { key: 'apiV3Key', label: '', sensitive: true },
{ key: 'certSerial', label: '', sensitive: false }, { key: 'certSerial', label: '', sensitive: false },
{ key: 'publicKey', label: '', sensitive: true }, { key: 'publicKey', label: '', sensitive: true },
{ key: 'publicKeyId', label: '', sensitive: false }, { key: 'publicKeyId', label: '', sensitive: false },
{ key: 'h5AppName', label: '', sensitive: false, optional: true },
{ key: 'h5AppUrl', label: '', sensitive: false, optional: true },
], ],
stripe: [ stripe: [
{ key: 'secretKey', label: '', sensitive: true }, { key: 'secretKey', label: '', sensitive: true },

View File

@@ -1665,8 +1665,6 @@ export default {
failedToLoadApiKeys: 'Failed to load user API keys', failedToLoadApiKeys: 'Failed to load user API keys',
emailRequired: 'Please enter email', emailRequired: 'Please enter email',
concurrencyMin: 'Concurrency must be at least 1', concurrencyMin: 'Concurrency must be at least 1',
soraStorageQuota: 'Sora Storage Quota',
soraStorageQuotaHint: 'In GB, 0 means use group or system default quota',
amountRequired: 'Please enter a valid amount', amountRequired: 'Please enter a valid amount',
insufficientBalance: 'Insufficient balance', insufficientBalance: 'Insufficient balance',
deleteConfirm: "Are you sure you want to delete '{email}'? This action cannot be undone.", deleteConfirm: "Are you sure you want to delete '{email}'? This action cannot be undone.",
@@ -1999,14 +1997,6 @@ export default {
enabled: 'Enabled', enabled: 'Enabled',
disabled: 'Disabled' disabled: 'Disabled'
}, },
claudeMaxSimulation: {
title: 'Claude Max Usage Simulation',
tooltip:
'When enabled, for Claude models without upstream cache-write usage, the system deterministically maps tokens to a small input plus 1h cache creation while keeping total tokens unchanged.',
enabled: 'Enabled (simulate 1h cache)',
disabled: 'Disabled',
hint: 'Only token categories in usage billing logs are adjusted. No per-request mapping state is persisted.'
},
supportedScopes: { supportedScopes: {
title: 'Supported Model Families', title: 'Supported Model Families',
tooltip: 'Select the model families this group supports. Unchecked families will not be routed to this group.', tooltip: 'Select the model families this group supports. Unchecked families will not be routed to this group.',
@@ -2640,7 +2630,7 @@ export default {
resetQuota: 'Reset Quota', resetQuota: 'Reset Quota',
quotaLimit: 'Quota Limit', quotaLimit: 'Quota Limit',
quotaLimitPlaceholder: '0 means unlimited', quotaLimitPlaceholder: '0 means unlimited',
quotaLimitHint: 'Set daily/weekly/total spending limits (USD). Anthropic API key accounts can also configure client affinity. Changing limits won\'t reset usage.', quotaLimitHint: 'Set daily/weekly/total spending limits (USD). Changing limits won\'t reset usage.',
quotaLimitToggle: 'Enable Quota Limit', quotaLimitToggle: 'Enable Quota Limit',
quotaLimitToggleHint: 'When enabled, account will be paused when usage reaches the set limit', quotaLimitToggleHint: 'When enabled, account will be paused when usage reaches the set limit',
quotaDailyLimit: 'Daily Limit', quotaDailyLimit: 'Daily Limit',
@@ -2844,7 +2834,7 @@ export default {
// Quota control (Anthropic OAuth/SetupToken only) // Quota control (Anthropic OAuth/SetupToken only)
quotaControl: { quotaControl: {
title: 'Quota Control', title: 'Quota Control',
hint: 'Configure cost window, session limits, client affinity and other scheduling controls.', hint: 'Configure cost windows, session limits and other scheduling controls.',
windowCost: { windowCost: {
label: '5h Window Cost Limit', label: '5h Window Cost Limit',
hint: 'Limit account cost usage within the 5-hour window', hint: 'Limit account cost usage within the 5-hour window',
@@ -2890,7 +2880,7 @@ export default {
label: 'TLS Fingerprint Simulation', label: 'TLS Fingerprint Simulation',
hint: 'Simulate Node.js/Claude Code client TLS fingerprint', hint: 'Simulate Node.js/Claude Code client TLS fingerprint',
defaultProfile: 'Built-in Default', defaultProfile: 'Built-in Default',
randomProfile: 'Random' randomProfile: 'Random',
}, },
sessionIdMasking: { sessionIdMasking: {
label: 'Session ID Masking', label: 'Session ID Masking',
@@ -2907,25 +2897,7 @@ export default {
hint: 'Forward requests to a custom relay service. Proxy URL will be passed as a query parameter.', hint: 'Forward requests to a custom relay service. Proxy URL will be passed as a query parameter.',
urlHint: 'Relay service URL (e.g., https://relay.example.com)', urlHint: 'Relay service URL (e.g., https://relay.example.com)',
}, },
clientAffinity: {
label: 'Client Affinity Scheduling',
hint: 'When enabled, new sessions prefer accounts previously used by this client to reduce account switching'
}
}, },
affinityNoClients: 'No affinity clients',
affinityClients: '{count} affinity clients:',
affinitySection: 'Client Affinity',
affinitySectionHint: 'Control how clients are distributed across accounts. Configure zone thresholds to balance load.',
affinityToggle: 'Enable Client Affinity',
affinityToggleHint: 'New sessions prefer accounts previously used by this client',
affinityBase: 'Base Limit (Green Zone)',
affinityBasePlaceholder: 'Empty = no limit',
affinityBaseHint: 'Max clients in green zone (full priority scheduling)',
affinityBaseOffHint: 'No green zone limit. All clients receive full priority scheduling.',
affinityBuffer: 'Buffer (Yellow Zone)',
affinityBufferPlaceholder: 'e.g. 3',
affinityBufferHint: 'Additional clients allowed in the yellow zone (degraded priority)',
affinityBufferInfinite: 'Unlimited',
expired: 'Expired', expired: 'Expired',
proxy: 'Proxy', proxy: 'Proxy',
noProxy: 'No Proxy', noProxy: 'No Proxy',
@@ -4947,12 +4919,6 @@ export default {
integrationDoc: 'Payment Integration Docs', integrationDoc: 'Payment Integration Docs',
integrationDocHint: 'Covers endpoint specs, idempotency semantics, and code samples' integrationDocHint: 'Covers endpoint specs, idempotency semantics, and code samples'
}, },
soraClient: {
title: 'Sora Client',
description: 'Control whether to show the Sora client entry in the sidebar',
enabled: 'Enable Sora Client',
enabledHint: 'When enabled, the Sora entry will be shown in the sidebar for users to access Sora features'
},
customMenu: { customMenu: {
title: 'Custom Menu Pages', title: 'Custom Menu Pages',
description: 'Add custom iframe pages to the sidebar navigation. Each page can be visible to regular users or administrators.', description: 'Add custom iframe pages to the sidebar navigation. Each page can be visible to regular users or administrators.',
@@ -5044,8 +5010,6 @@ export default {
field_certSerial: 'Certificate Serial', field_certSerial: 'Certificate Serial',
field_h5AppName: 'H5 App Name', field_h5AppName: 'H5 App Name',
field_h5AppUrl: 'H5 App URL', field_h5AppUrl: 'H5 App URL',
wxpayConfigHint: 'WeChat Pay usually only needs App ID. Fill MP App ID, H5 App Name, and H5 App URL only when your Official Account or H5 flow specifically requires them.',
wxpayAdvancedOptions: 'WeChat Pay Advanced Options',
field_secretKey: 'Secret Key', field_secretKey: 'Secret Key',
field_publishableKey: 'Publishable Key', field_publishableKey: 'Publishable Key',
field_webhookSecret: 'Webhook Secret', field_webhookSecret: 'Webhook Secret',
@@ -5076,37 +5040,6 @@ export default {
providerKey: 'Provider Type', providerKey: 'Provider Type',
selectProviderKey: 'Select Provider Type', selectProviderKey: 'Select Provider Type',
providerConfig: 'Credentials', providerConfig: 'Credentials',
paymentGuideTrigger: 'View payment guide',
guideOpenLabel: 'Enable: ',
guideCallLabel: 'Call: ',
guideFallbackLabel: 'Fallback: ',
alipayGuideSummary: 'Desktop prefers QR precreate and falls back to cashier; mobile prefers WAP checkout.',
alipayGuideFaceToFaceTitle: 'Face-to-face / QR Payment',
alipayGuideFaceToFaceOpen: 'Enable face-to-face or QR payment capability.',
alipayGuideFaceToFaceCall: 'Desktop orders call alipay.trade.precreate first and render the QR code directly.',
alipayGuideFaceToFaceFallback: 'If unavailable or failed, the flow falls back to website checkout automatically.',
alipayGuidePagePayTitle: 'Website Payment',
alipayGuidePagePayOpen: 'Enable website payment.',
alipayGuidePagePayCall: 'When face-to-face is unavailable on desktop, the flow calls alipay.trade.page.pay and still renders the returned link as a QR code.',
alipayGuidePagePayFallback: 'The cashier link stays available so users can reopen the checkout page manually.',
alipayGuideWapTitle: 'WAP Payment',
alipayGuideWapOpen: 'Enable mobile website payment.',
alipayGuideWapCall: 'Mobile orders call alipay.trade.wap.pay first and jump to Alipay checkout.',
alipayGuideWapFallback: 'If mobile payment is unavailable or fails, the frontend switches to QR payment and shows a notice.',
wxpayGuideSummary: 'Desktop prefers Native QR; mobile routes to JSAPI or H5 based on browser context.',
wxpayGuideNote: 'The current form defaults to one shared App ID, which fits the common single-subject web, mobile, and Official Account setup.',
wxpayGuideNativeTitle: 'Native / QR Payment',
wxpayGuideNativeOpen: 'Enable Native or QR payment capability.',
wxpayGuideNativeCall: 'Desktop orders use Native by default and the frontend renders the QR payload.',
wxpayGuideNativeFallback: 'Mobile flows also fall back here when JSAPI or H5 cannot be used.',
wxpayGuideJsapiTitle: 'JSAPI / Official Account',
wxpayGuideJsapiOpen: 'Enable Official Account payment and ensure the browser is inside WeChat with an available OpenID.',
wxpayGuideJsapiCall: 'Inside WeChat, the app calls JSAPI after authorization and launches WeChat Pay directly.',
wxpayGuideJsapiFallback: 'If configuration is missing, the bridge is unavailable, or launch fails, the flow falls back to QR payment.',
wxpayGuideH5Title: 'H5 Payment',
wxpayGuideH5Open: 'Enable H5 payment.',
wxpayGuideH5Call: 'On mobile browsers outside WeChat, the app calls H5 payment when a client IP is available.',
wxpayGuideH5Fallback: 'If H5 is unavailable or order creation fails, the flow falls back to QR payment.',
noProviders: 'No provider instances configured', noProviders: 'No provider instances configured',
supportedTypes: 'Supported Payment Types', supportedTypes: 'Supported Payment Types',
supportedTypesHint: 'Comma-separated, e.g. alipay,wxpay', supportedTypesHint: 'Comma-separated, e.g. alipay,wxpay',
@@ -5205,98 +5138,6 @@ export default {
securityWarning: 'Warning: This key provides full admin access. Keep it secure.', securityWarning: 'Warning: This key provides full admin access. Keep it secure.',
usage: 'Usage: Add to request header - x-api-key: <your-admin-api-key>' usage: 'Usage: Add to request header - x-api-key: <your-admin-api-key>'
}, },
soraS3: {
title: 'Sora Storage',
description: 'Manage Sora media storage profiles with S3 and Google Drive support',
newProfile: 'New Profile',
reloadProfiles: 'Reload Profiles',
empty: 'No storage profiles yet, create one first',
createTitle: 'Create Storage Profile',
editTitle: 'Edit Storage Profile',
selectProvider: 'Select Storage Type',
providerS3Desc: 'S3-compatible object storage',
providerGDriveDesc: 'Google Drive cloud storage',
profileID: 'Profile ID',
profileName: 'Profile Name',
setActive: 'Set as active after creation',
saveProfile: 'Save Profile',
activateProfile: 'Activate',
profileCreated: 'Storage profile created',
profileSaved: 'Storage profile saved',
profileDeleted: 'Storage profile deleted',
profileActivated: 'Active storage profile switched',
profileIDRequired: 'Profile ID is required',
profileNameRequired: 'Profile name is required',
profileSelectRequired: 'Please select a profile first',
endpointRequired: 'S3 endpoint is required when enabled',
bucketRequired: 'Bucket is required when enabled',
accessKeyRequired: 'Access Key ID is required when enabled',
deleteConfirm: 'Delete storage profile {profileID}?',
columns: {
profile: 'Profile',
profileId: 'Profile ID',
name: 'Name',
provider: 'Type',
active: 'Active',
endpoint: 'Endpoint',
bucket: 'Bucket',
storagePath: 'Storage Path',
capacityUsage: 'Capacity / Used',
capacityUnlimited: 'Unlimited',
videoCount: 'Videos',
videoCompleted: 'completed',
videoInProgress: 'in progress',
quota: 'Default Quota',
updatedAt: 'Updated At',
actions: 'Actions',
rootFolder: 'Root folder',
testInTable: 'Test',
testingInTable: 'Testing...',
testTimeout: 'Test timed out (15s)'
},
enabled: 'Enable Storage',
enabledHint: 'When enabled, Sora generated media files will be automatically uploaded',
endpoint: 'S3 Endpoint',
region: 'Region',
bucket: 'Bucket',
prefix: 'Object Prefix',
accessKeyId: 'Access Key ID',
secretAccessKey: 'Secret Access Key',
secretConfigured: '(Configured, leave blank to keep)',
cdnUrl: 'CDN URL',
cdnUrlHint: 'Optional. When configured, files are accessed via CDN URL',
forcePathStyle: 'Force Path Style',
defaultQuota: 'Default Storage Quota',
defaultQuotaHint: 'Default quota when not specified at user or group level. 0 means unlimited',
testConnection: 'Test Connection',
testing: 'Testing...',
testSuccess: 'Connection test successful',
testFailed: 'Connection test failed',
saved: 'Storage settings saved successfully',
saveFailed: 'Failed to save storage settings',
gdrive: {
authType: 'Authentication Method',
serviceAccount: 'Service Account',
clientId: 'Client ID',
clientSecret: 'Client Secret',
clientSecretConfigured: '(Configured, leave blank to keep)',
refreshToken: 'Refresh Token',
refreshTokenConfigured: '(Configured, leave blank to keep)',
serviceAccountJson: 'Service Account JSON',
serviceAccountConfigured: '(Configured, leave blank to keep)',
folderId: 'Folder ID (optional)',
authorize: 'Authorize Google Drive',
authorizeHint: 'Get Refresh Token via OAuth2',
oauthFieldsRequired: 'Please fill in Client ID and Client Secret first',
oauthSuccess: 'Google Drive authorization successful',
oauthFailed: 'Google Drive authorization failed',
closeWindow: 'This window will close automatically',
processing: 'Processing authorization...',
testStorage: 'Test Storage',
testSuccess: 'Google Drive storage test passed (upload, access, delete all OK)',
testFailed: 'Google Drive storage test failed'
}
},
overloadCooldown: { overloadCooldown: {
title: '529 Overload Cooldown', title: '529 Overload Cooldown',
description: 'Configure account scheduling pause strategy when upstream returns 529 (overloaded)', description: 'Configure account scheduling pause strategy when upstream returns 529 (overloaded)',
@@ -5963,7 +5804,6 @@ export default {
wechatOpenInWeChatHint: 'Open the current page inside WeChat, or switch to desktop WeChat QR payment.', wechatOpenInWeChatHint: 'Open the current page inside WeChat, or switch to desktop WeChat QR payment.',
wechatScanOnDesktopHint: 'On desktop, use WeChat Scan to pay; on mobile, reopen the current page inside WeChat.', wechatScanOnDesktopHint: 'On desktop, use WeChat Scan to pay; on mobile, reopen the current page inside WeChat.',
wechatSwitchBrowserHint: 'Switch to desktop WeChat QR payment, or reopen this page in an external browser and retry.', wechatSwitchBrowserHint: 'Switch to desktop WeChat QR payment, or reopen this page in an external browser and retry.',
mobilePaymentFallbackToQr: 'This merchant has not enabled mobile payment. The flow has been switched to QR payment automatically.',
alipayDesktopUnavailable: 'The desktop Alipay flow could not generate a QR code.', alipayDesktopUnavailable: 'The desktop Alipay flow could not generate a QR code.',
alipayDesktopQrHint: 'Desktop Alipay should render a QR code. Refresh and retry, or make sure the payment page was not blocked.', alipayDesktopQrHint: 'Desktop Alipay should render a QR code. Refresh and retry, or make sure the payment page was not blocked.',
alipayMobileUnavailable: 'This page could not hand off to Alipay.', alipayMobileUnavailable: 'This page could not hand off to Alipay.',

View File

@@ -1729,8 +1729,6 @@ export default {
failedToAdjust: '调整失败', failedToAdjust: '调整失败',
emailRequired: '请输入邮箱', emailRequired: '请输入邮箱',
concurrencyMin: '并发数不能小于1', concurrencyMin: '并发数不能小于1',
soraStorageQuota: 'Sora 存储配额',
soraStorageQuotaHint: '单位 GB0 表示使用分组或系统默认配额',
amountRequired: '请输入有效金额', amountRequired: '请输入有效金额',
insufficientBalance: '余额不足', insufficientBalance: '余额不足',
setAllowedGroups: '设置允许分组', setAllowedGroups: '设置允许分组',
@@ -2987,7 +2985,7 @@ export default {
// Quota control (Anthropic OAuth/SetupToken only) // Quota control (Anthropic OAuth/SetupToken only)
quotaControl: { quotaControl: {
title: '配额控制', title: '配额控制',
hint: '配置费用窗口、会话限制、客户端亲和等调度控制。', hint: '配置费用窗口、会话限制等调度控制。',
windowCost: { windowCost: {
label: '5h窗口费用控制', label: '5h窗口费用控制',
hint: '限制账号在5小时窗口内的费用使用', hint: '限制账号在5小时窗口内的费用使用',
@@ -3033,7 +3031,7 @@ export default {
label: 'TLS 指纹模拟', label: 'TLS 指纹模拟',
hint: '模拟 Node.js/Claude Code 客户端的 TLS 指纹', hint: '模拟 Node.js/Claude Code 客户端的 TLS 指纹',
defaultProfile: '内置默认', defaultProfile: '内置默认',
randomProfile: '随机' randomProfile: '随机',
}, },
sessionIdMasking: { sessionIdMasking: {
label: '会话 ID 伪装', label: '会话 ID 伪装',
@@ -3050,25 +3048,7 @@ export default {
hint: '启用后将请求转发到自定义中继服务,代理地址将作为 URL 参数传递给中继服务', hint: '启用后将请求转发到自定义中继服务,代理地址将作为 URL 参数传递给中继服务',
urlHint: '中继服务地址(如 https://relay.example.com', urlHint: '中继服务地址(如 https://relay.example.com',
}, },
clientAffinity: {
label: '客户端亲和调度',
hint: '启用后,新会话会优先调度到该客户端之前使用过的账号,避免频繁切换账号'
}
}, },
affinityNoClients: '无亲和客户端',
affinityClients: '{count} 个亲和客户端:',
affinitySection: '客户端亲和',
affinitySectionHint: '控制客户端在账号间的分布。通过配置区域阈值来平衡负载。',
affinityToggle: '启用客户端亲和',
affinityToggleHint: '新会话优先调度到该客户端之前使用过的账号',
affinityBase: '基础限额(绿区)',
affinityBasePlaceholder: '留空表示不限制',
affinityBaseHint: '绿区最大客户端数量(完整优先级调度)',
affinityBaseOffHint: '未开启绿区限制,所有客户端均享受完整优先级调度',
affinityBuffer: '缓冲区(黄区)',
affinityBufferPlaceholder: '例如 3',
affinityBufferHint: '黄区允许的额外客户端数量(降级优先级调度)',
affinityBufferInfinite: '不限制',
expired: '已过期', expired: '已过期',
proxy: '代理', proxy: '代理',
noProxy: '无代理', noProxy: '无代理',
@@ -5111,12 +5091,6 @@ export default {
integrationDoc: '支付集成文档', integrationDoc: '支付集成文档',
integrationDocHint: '包含接口说明、幂等语义及示例代码' integrationDocHint: '包含接口说明、幂等语义及示例代码'
}, },
soraClient: {
title: 'Sora 客户端',
description: '控制是否在侧边栏展示 Sora 客户端入口',
enabled: '启用 Sora 客户端',
enabledHint: '开启后,侧边栏将显示 Sora 入口,用户可访问 Sora 功能'
},
customMenu: { customMenu: {
title: '自定义菜单页面', title: '自定义菜单页面',
description: '添加自定义 iframe 页面到侧边栏导航。每个页面可以设置为普通用户或管理员可见。', description: '添加自定义 iframe 页面到侧边栏导航。每个页面可以设置为普通用户或管理员可见。',
@@ -5208,8 +5182,6 @@ export default {
field_certSerial: '证书序列号', field_certSerial: '证书序列号',
field_h5AppName: 'H5 应用名称', field_h5AppName: 'H5 应用名称',
field_h5AppUrl: 'H5 应用地址', field_h5AppUrl: 'H5 应用地址',
wxpayConfigHint: '微信支付通常只需要填写 App ID。公众号 App ID、H5 应用名称、H5 应用地址仅在公众号支付或 H5 场景有特殊要求时再填写。',
wxpayAdvancedOptions: '微信支付高级可选项',
field_secretKey: '密钥', field_secretKey: '密钥',
field_publishableKey: '公开密钥', field_publishableKey: '公开密钥',
field_webhookSecret: 'Webhook 密钥', field_webhookSecret: 'Webhook 密钥',
@@ -5240,37 +5212,6 @@ export default {
providerKey: '服务商类型', providerKey: '服务商类型',
selectProviderKey: '选择服务商类型', selectProviderKey: '选择服务商类型',
providerConfig: '凭证配置', providerConfig: '凭证配置',
paymentGuideTrigger: '查看支付方式说明',
guideOpenLabel: '开通:',
guideCallLabel: '调用:',
guideFallbackLabel: '降级:',
alipayGuideSummary: '桌面优先扫码单,失败再走收银台;移动优先手机网站支付。',
alipayGuideFaceToFaceTitle: '当面付 / 扫码支付',
alipayGuideFaceToFaceOpen: '需开通当面付或扫码支付能力。',
alipayGuideFaceToFaceCall: '桌面端下单时优先调用 alipay.trade.precreate前台直接渲染二维码。',
alipayGuideFaceToFaceFallback: '接口不可用或返回失败时,自动降级到电脑网站支付。',
alipayGuidePagePayTitle: '电脑网站支付',
alipayGuidePagePayOpen: '需开通电脑网站支付。',
alipayGuidePagePayCall: '桌面端当面付不可用时调用 alipay.trade.page.pay并继续把返回链接渲染成二维码。',
alipayGuidePagePayFallback: '同时保留打开收银台入口,用户可手动重新拉起支付页。',
alipayGuideWapTitle: '手机网站支付',
alipayGuideWapOpen: '需开通手机网站支付。',
alipayGuideWapCall: '移动端优先调用 alipay.trade.wap.pay跳转支付宝收银台。',
alipayGuideWapFallback: '未开通或返回异常时,前端自动改走扫码支付并提示未开通移动支付。',
wxpayGuideSummary: '桌面优先 Native 扫码,移动端按浏览器环境走 JSAPI 或 H5。',
wxpayGuideNote: '当前表单默认共用一个 App ID适合同主体下统一配置网页、移动和公众号场景。',
wxpayGuideNativeTitle: 'Native / 扫码支付',
wxpayGuideNativeOpen: '需开通 Native 或扫码支付能力。',
wxpayGuideNativeCall: '桌面端默认调用 Native下发二维码内容给前台渲染。',
wxpayGuideNativeFallback: '移动端无法走 JSAPI 或 H5 时,也会自动回退到这里。',
wxpayGuideJsapiTitle: 'JSAPI / 公众号支付',
wxpayGuideJsapiOpen: '需开通公众号支付,并保证当前浏览器在微信内且能拿到 OpenID。',
wxpayGuideJsapiCall: '微信内浏览器完成授权后调用 JSAPI直接拉起微信支付。',
wxpayGuideJsapiFallback: '未配置、Bridge 不可用或拉起失败时,自动改走扫码支付。',
wxpayGuideH5Title: 'H5 支付',
wxpayGuideH5Open: '需开通 H5 支付。',
wxpayGuideH5Call: '移动端非微信浏览器且有客户端 IP 时调用 H5 支付,跳转微信收银台。',
wxpayGuideH5Fallback: '未开通 H5 或下单失败时,自动改走扫码支付。',
noProviders: '暂无服务商实例', noProviders: '暂无服务商实例',
supportedTypes: '支持的支付方式', supportedTypes: '支持的支付方式',
supportedTypesHint: '逗号分隔,如 alipay,wxpay', supportedTypesHint: '逗号分隔,如 alipay,wxpay',
@@ -5368,98 +5309,6 @@ export default {
securityWarning: '警告:此密钥拥有完整的管理员权限,请妥善保管。', securityWarning: '警告:此密钥拥有完整的管理员权限,请妥善保管。',
usage: '使用方法:在请求头中添加 x-api-key: <your-admin-api-key>' usage: '使用方法:在请求头中添加 x-api-key: <your-admin-api-key>'
}, },
soraS3: {
title: 'Sora 存储配置',
description: '以多配置列表管理 Sora 媒体存储,支持 S3 和 Google Drive',
newProfile: '新建配置',
reloadProfiles: '刷新列表',
empty: '暂无存储配置,请先创建',
createTitle: '新建存储配置',
editTitle: '编辑存储配置',
selectProvider: '选择存储类型',
providerS3Desc: 'S3 兼容对象存储',
providerGDriveDesc: 'Google Drive 云盘',
profileID: '配置 ID',
profileName: '配置名称',
setActive: '创建后设为生效',
saveProfile: '保存配置',
activateProfile: '设为生效',
profileCreated: '存储配置创建成功',
profileSaved: '存储配置保存成功',
profileDeleted: '存储配置删除成功',
profileActivated: '生效配置已切换',
profileIDRequired: '请填写配置 ID',
profileNameRequired: '请填写配置名称',
profileSelectRequired: '请先选择配置',
endpointRequired: '启用时必须填写 S3 端点',
bucketRequired: '启用时必须填写存储桶',
accessKeyRequired: '启用时必须填写 Access Key ID',
deleteConfirm: '确定删除存储配置 {profileID} 吗?',
columns: {
profile: '配置',
profileId: 'Profile ID',
name: '名称',
provider: '存储类型',
active: '生效状态',
endpoint: '端点',
bucket: '存储桶',
storagePath: '存储路径',
capacityUsage: '容量 / 已用',
capacityUnlimited: '无限制',
videoCount: '视频数',
videoCompleted: '完成',
videoInProgress: '进行中',
quota: '默认配额',
updatedAt: '更新时间',
actions: '操作',
rootFolder: '根目录',
testInTable: '测试',
testingInTable: '测试中...',
testTimeout: '测试超时15秒'
},
enabled: '启用存储',
enabledHint: '启用后Sora 生成的媒体文件将自动上传到存储',
endpoint: 'S3 端点',
region: '区域',
bucket: '存储桶',
prefix: '对象前缀',
accessKeyId: 'Access Key ID',
secretAccessKey: 'Secret Access Key',
secretConfigured: '(已配置,留空保持不变)',
cdnUrl: 'CDN URL',
cdnUrlHint: '可选,配置后使用 CDN URL 访问文件',
forcePathStyle: '强制路径风格Path Style',
defaultQuota: '默认存储配额',
defaultQuotaHint: '未在用户或分组级别指定配额时的默认值0 表示无限制',
testConnection: '测试连接',
testing: '测试中...',
testSuccess: '连接测试成功',
testFailed: '连接测试失败',
saved: '存储设置保存成功',
saveFailed: '保存存储设置失败',
gdrive: {
authType: '认证方式',
serviceAccount: '服务账号',
clientId: 'Client ID',
clientSecret: 'Client Secret',
clientSecretConfigured: '(已配置,留空保持不变)',
refreshToken: 'Refresh Token',
refreshTokenConfigured: '(已配置,留空保持不变)',
serviceAccountJson: '服务账号 JSON',
serviceAccountConfigured: '(已配置,留空保持不变)',
folderId: 'Folder ID可选',
authorize: '授权 Google Drive',
authorizeHint: '通过 OAuth2 获取 Refresh Token',
oauthFieldsRequired: '请先填写 Client ID 和 Client Secret',
oauthSuccess: 'Google Drive 授权成功',
oauthFailed: 'Google Drive 授权失败',
closeWindow: '此窗口将自动关闭',
processing: '正在处理授权...',
testStorage: '测试存储',
testSuccess: 'Google Drive 存储测试成功(上传、访问、删除均正常)',
testFailed: 'Google Drive 存储测试失败'
}
},
overloadCooldown: { overloadCooldown: {
title: '529 过载冷却', title: '529 过载冷却',
description: '配置上游返回 529过载时的账号调度暂停策略', description: '配置上游返回 529过载时的账号调度暂停策略',
@@ -6151,7 +6000,6 @@ export default {
wechatOpenInWeChatHint: '请复制当前页面链接到微信内打开,或直接改用电脑端微信扫码支付。', wechatOpenInWeChatHint: '请复制当前页面链接到微信内打开,或直接改用电脑端微信扫码支付。',
wechatScanOnDesktopHint: '电脑端请直接使用微信扫一扫完成支付;移动端请在微信内打开当前页面。', wechatScanOnDesktopHint: '电脑端请直接使用微信扫一扫完成支付;移动端请在微信内打开当前页面。',
wechatSwitchBrowserHint: '请改用电脑端微信扫码,或在外部浏览器重新打开本页后再试。', wechatSwitchBrowserHint: '请改用电脑端微信扫码,或在外部浏览器重新打开本页后再试。',
mobilePaymentFallbackToQr: '当前商户未开通移动支付,已自动切换为扫码支付。',
alipayDesktopUnavailable: '当前支付宝桌面支付未成功生成二维码。', alipayDesktopUnavailable: '当前支付宝桌面支付未成功生成二维码。',
alipayDesktopQrHint: '电脑端支付宝应展示扫码单,请刷新后重试,或确认浏览器未拦截当前支付页。', alipayDesktopQrHint: '电脑端支付宝应展示扫码单,请刷新后重试,或确认浏览器未拦截当前支付页。',
alipayMobileUnavailable: '当前页面未成功跳转到支付宝。', alipayMobileUnavailable: '当前页面未成功跳转到支付宝。',

View File

@@ -0,0 +1,186 @@
import { describe, expect, it } from 'vitest'
import { resolveCodexUsageWindow } from '@/utils/codexUsage'
describe('resolveCodexUsageWindow', () => {
it('快照为空时返回空窗口', () => {
const result = resolveCodexUsageWindow(null, '5h', new Date('2026-02-20T08:00:00Z'))
expect(result).toEqual({ usedPercent: null, resetAt: null })
})
it('优先使用后端提供的绝对重置时间', () => {
const result = resolveCodexUsageWindow(
{
codex_5h_used_percent: 55,
codex_5h_reset_at: '2026-02-20T10:00:00Z',
codex_5h_reset_after_seconds: 1
},
'5h',
new Date('2026-02-20T08:00:00Z')
)
expect(result.usedPercent).toBe(55)
expect(result.resetAt).toBe('2026-02-20T10:00:00.000Z')
})
it('窗口已过期时自动归零', () => {
const result = resolveCodexUsageWindow(
{
codex_7d_used_percent: 100,
codex_7d_reset_at: '2026-02-20T07:00:00Z'
},
'7d',
new Date('2026-02-20T08:00:00Z')
)
expect(result.usedPercent).toBe(0)
expect(result.resetAt).toBe('2026-02-20T07:00:00.000Z')
})
it('无绝对时间时使用 updated_at + seconds 回退计算', () => {
const result = resolveCodexUsageWindow(
{
codex_5h_used_percent: 20,
codex_5h_reset_after_seconds: 3600,
codex_usage_updated_at: '2026-02-20T06:30:00Z'
},
'5h',
new Date('2026-02-20T07:00:00Z')
)
expect(result.usedPercent).toBe(20)
expect(result.resetAt).toBe('2026-02-20T07:30:00.000Z')
})
it('支持 legacy primary/secondary 字段映射', () => {
const snapshot = {
codex_primary_window_minutes: 10080,
codex_primary_used_percent: 70,
codex_primary_reset_after_seconds: 86400,
codex_secondary_window_minutes: 300,
codex_secondary_used_percent: 15,
codex_secondary_reset_after_seconds: 1200,
codex_usage_updated_at: '2026-02-20T07:00:00Z'
}
const result5h = resolveCodexUsageWindow(snapshot, '5h', new Date('2026-02-20T07:05:00Z'))
const result7d = resolveCodexUsageWindow(snapshot, '7d', new Date('2026-02-20T07:05:00Z'))
expect(result5h.usedPercent).toBe(15)
expect(result5h.resetAt).toBe('2026-02-20T07:20:00.000Z')
expect(result7d.usedPercent).toBe(70)
expect(result7d.resetAt).toBe('2026-02-21T07:00:00.000Z')
})
it('legacy 5h 在 primary<=360 时优先 primary 并支持字符串数字', () => {
const result = resolveCodexUsageWindow(
{
codex_primary_window_minutes: '300',
codex_primary_used_percent: '21',
codex_primary_reset_after_seconds: '1800',
codex_secondary_window_minutes: '10080',
codex_secondary_used_percent: '99',
codex_secondary_reset_after_seconds: '99999',
codex_usage_updated_at: '2026-02-20T08:00:00Z'
},
'5h',
new Date('2026-02-20T08:10:00Z')
)
expect(result.usedPercent).toBe(21)
expect(result.resetAt).toBe('2026-02-20T08:30:00.000Z')
})
it('legacy 5h 在无窗口信息时回退 secondary', () => {
const result = resolveCodexUsageWindow(
{
codex_secondary_used_percent: 19,
codex_secondary_reset_after_seconds: 120,
codex_usage_updated_at: '2026-02-20T08:00:00Z'
},
'5h',
new Date('2026-02-20T08:00:01Z')
)
expect(result.usedPercent).toBe(19)
expect(result.resetAt).toBe('2026-02-20T08:02:00.000Z')
})
it('legacy 场景下 secondary 为 7d 时能正确识别', () => {
const result = resolveCodexUsageWindow(
{
codex_primary_window_minutes: 300,
codex_primary_used_percent: 5,
codex_primary_reset_after_seconds: 600,
codex_secondary_window_minutes: 10080,
codex_secondary_used_percent: 66,
codex_secondary_reset_after_seconds: 7200,
codex_usage_updated_at: '2026-02-20T07:00:00Z'
},
'7d',
new Date('2026-02-20T07:30:00Z')
)
expect(result.usedPercent).toBe(66)
expect(result.resetAt).toBe('2026-02-20T09:00:00.000Z')
})
it('绝对时间非法时回退到 updated_at + seconds', () => {
const result = resolveCodexUsageWindow(
{
codex_5h_used_percent: 33,
codex_5h_reset_at: 'not-a-date',
codex_5h_reset_after_seconds: 900,
codex_usage_updated_at: '2026-02-20T07:30:00Z'
},
'5h',
new Date('2026-02-20T07:40:00Z')
)
expect(result.usedPercent).toBe(33)
expect(result.resetAt).toBe('2026-02-20T07:45:00.000Z')
})
it('updated_at 非法且无绝对时间时 resetAt 返回 null', () => {
const result = resolveCodexUsageWindow(
{
codex_5h_used_percent: 10,
codex_5h_reset_after_seconds: 123,
codex_usage_updated_at: 'invalid-time'
},
'5h',
new Date('2026-02-20T08:00:00Z')
)
expect(result.usedPercent).toBe(10)
expect(result.resetAt).toBeNull()
})
it('reset_after_seconds 为负数时按 0 秒处理', () => {
const result = resolveCodexUsageWindow(
{
codex_5h_used_percent: 80,
codex_5h_reset_after_seconds: -30,
codex_usage_updated_at: '2026-02-20T08:00:00Z'
},
'5h',
new Date('2026-02-20T07:59:00Z')
)
expect(result.usedPercent).toBe(80)
expect(result.resetAt).toBe('2026-02-20T08:00:00.000Z')
})
it('百分比缺失时仍可计算 resetAt 供倒计时展示', () => {
const result = resolveCodexUsageWindow(
{
codex_7d_reset_after_seconds: 60,
codex_usage_updated_at: '2026-02-20T08:00:00Z'
},
'7d',
new Date('2026-02-20T08:00:01Z')
)
expect(result.usedPercent).toBeNull()
expect(result.resetAt).toBe('2026-02-20T08:01:00.000Z')
})
})

View File

@@ -145,6 +145,25 @@ describe('usageLoadQueue', () => {
expect(Math.abs(timestamps[1] - timestamps[0])).toBeLessThan(50) expect(Math.abs(timestamps[1] - timestamps[0])).toBeLessThan(50)
}) })
it('Antigravity 平台直接执行,不排队', async () => {
const timestamps: number[] = []
const makeFn = () => async () => {
timestamps.push(Date.now())
return 'ok'
}
const acc1 = makeAccount('antigravity', 'oauth', { host: '1.2.3.4', port: 8080 })
const acc2 = makeAccount('antigravity', 'oauth', { host: '1.2.3.4', port: 8080 })
const p1 = enqueueUsageRequest(acc1, makeFn())
const p2 = enqueueUsageRequest(acc2, makeFn())
await Promise.all([p1, p2])
expect(timestamps).toHaveLength(2)
expect(Math.abs(timestamps[1] - timestamps[0])).toBeLessThan(50)
})
it('OpenAI 平台直接执行,不排队', async () => { it('OpenAI 平台直接执行,不排队', async () => {
const timestamps: number[] = [] const timestamps: number[] = []
const makeFn = () => async () => { const makeFn = () => async () => {

View File

@@ -0,0 +1,140 @@
import type { CodexUsageSnapshot } from '@/types'
export interface ResolvedCodexUsageWindow {
usedPercent: number | null
resetAt: string | null
}
type WindowKind = '5h' | '7d'
function asNumber(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim() !== '') {
const n = Number(value)
if (Number.isFinite(n)) return n
}
return null
}
function asString(value: unknown): string | null {
if (typeof value !== 'string') return null
const trimmed = value.trim()
return trimmed === '' ? null : trimmed
}
function asISOTime(value: unknown): string | null {
const raw = asString(value)
if (!raw) return null
const date = new Date(raw)
if (Number.isNaN(date.getTime())) return null
return date.toISOString()
}
function resolveLegacy5h(snapshot: Record<string, unknown>): {
used: number | null
resetAfterSeconds: number | null
} {
const primaryWindow = asNumber(snapshot.codex_primary_window_minutes)
const secondaryWindow = asNumber(snapshot.codex_secondary_window_minutes)
const primaryUsed = asNumber(snapshot.codex_primary_used_percent)
const secondaryUsed = asNumber(snapshot.codex_secondary_used_percent)
const primaryReset = asNumber(snapshot.codex_primary_reset_after_seconds)
const secondaryReset = asNumber(snapshot.codex_secondary_reset_after_seconds)
if (primaryWindow != null && primaryWindow <= 360) {
return { used: primaryUsed, resetAfterSeconds: primaryReset }
}
if (secondaryWindow != null && secondaryWindow <= 360) {
return { used: secondaryUsed, resetAfterSeconds: secondaryReset }
}
return { used: secondaryUsed, resetAfterSeconds: secondaryReset }
}
function resolveLegacy7d(snapshot: Record<string, unknown>): {
used: number | null
resetAfterSeconds: number | null
} {
const primaryWindow = asNumber(snapshot.codex_primary_window_minutes)
const secondaryWindow = asNumber(snapshot.codex_secondary_window_minutes)
const primaryUsed = asNumber(snapshot.codex_primary_used_percent)
const secondaryUsed = asNumber(snapshot.codex_secondary_used_percent)
const primaryReset = asNumber(snapshot.codex_primary_reset_after_seconds)
const secondaryReset = asNumber(snapshot.codex_secondary_reset_after_seconds)
if (primaryWindow != null && primaryWindow >= 10000) {
return { used: primaryUsed, resetAfterSeconds: primaryReset }
}
if (secondaryWindow != null && secondaryWindow >= 10000) {
return { used: secondaryUsed, resetAfterSeconds: secondaryReset }
}
return { used: primaryUsed, resetAfterSeconds: primaryReset }
}
function resolveFromSeconds(
snapshot: Record<string, unknown>,
resetAfterSeconds: number | null
): string | null {
if (resetAfterSeconds == null) return null
const baseRaw = asString(snapshot.codex_usage_updated_at)
const base = baseRaw ? new Date(baseRaw) : new Date()
if (Number.isNaN(base.getTime())) return null
const sec = Math.max(0, resetAfterSeconds)
const resetAt = new Date(base.getTime() + sec * 1000)
return resetAt.toISOString()
}
function applyExpiredRule(
window: ResolvedCodexUsageWindow,
now: Date
): ResolvedCodexUsageWindow {
if (window.usedPercent == null || !window.resetAt) return window
const resetDate = new Date(window.resetAt)
if (Number.isNaN(resetDate.getTime())) return window
if (resetDate.getTime() <= now.getTime()) {
return { usedPercent: 0, resetAt: resetDate.toISOString() }
}
return window
}
export function resolveCodexUsageWindow(
snapshot: (CodexUsageSnapshot & Record<string, unknown>) | null | undefined,
window: WindowKind,
now: Date = new Date()
): ResolvedCodexUsageWindow {
if (!snapshot) {
return { usedPercent: null, resetAt: null }
}
const typedSnapshot = snapshot as Record<string, unknown>
let usedPercent: number | null
let resetAfterSeconds: number | null
let resetAt: string | null
if (window === '5h') {
usedPercent = asNumber(typedSnapshot.codex_5h_used_percent)
resetAfterSeconds = asNumber(typedSnapshot.codex_5h_reset_after_seconds)
resetAt = asISOTime(typedSnapshot.codex_5h_reset_at)
if (usedPercent == null || (resetAfterSeconds == null && !resetAt)) {
const legacy = resolveLegacy5h(typedSnapshot)
if (usedPercent == null) usedPercent = legacy.used
if (resetAfterSeconds == null) resetAfterSeconds = legacy.resetAfterSeconds
}
} else {
usedPercent = asNumber(typedSnapshot.codex_7d_used_percent)
resetAfterSeconds = asNumber(typedSnapshot.codex_7d_reset_after_seconds)
resetAt = asISOTime(typedSnapshot.codex_7d_reset_at)
if (usedPercent == null || (resetAfterSeconds == null && !resetAt)) {
const legacy = resolveLegacy7d(typedSnapshot)
if (usedPercent == null) usedPercent = legacy.used
if (resetAfterSeconds == null) resetAfterSeconds = legacy.resetAfterSeconds
}
}
if (!resetAt) {
resetAt = resolveFromSeconds(typedSnapshot, resetAfterSeconds)
}
return applyExpiredRule({ usedPercent, resetAt }, now)
}

View File

@@ -1,6 +1,6 @@
/** /**
* Shared URL builder for iframe-embedded pages. * Shared URL builder for iframe-embedded pages.
* Used by PurchaseSubscriptionView and CustomPageView to build consistent URLs * Used by CustomPageView to build consistent URLs
* with user_id, token, theme, lang, ui_mode, src_host, and src parameters. * with user_id, token, theme, lang, ui_mode, src_host, and src parameters.
*/ */

View File

@@ -122,8 +122,11 @@
> >
{{ siteName }} {{ siteName }}
</h1> </h1>
<p class="mb-8 text-lg text-gray-600 dark:text-dark-300 md:text-xl"> <p class="mb-3 text-xl font-semibold text-primary-600 dark:text-primary-400 md:text-2xl">
{{ siteSubtitle }} {{ t('home.heroSubtitle') }}
</p>
<p class="mb-8 text-base text-gray-600 dark:text-dark-300 md:text-lg">
{{ t('home.heroDescription') }}
</p> </p>
<!-- CTA Button --> <!-- CTA Button -->
@@ -177,7 +180,7 @@
</div> </div>
<!-- Feature Tags - Centered --> <!-- Feature Tags - Centered -->
<div class="mb-12 flex flex-wrap items-center justify-center gap-4 md:gap-6"> <div class="mb-16 flex flex-wrap items-center justify-center gap-4 md:gap-6">
<div <div
class="inline-flex items-center gap-2.5 rounded-full border border-gray-200/50 bg-white/80 px-5 py-2.5 shadow-sm backdrop-blur-sm dark:border-dark-700/50 dark:bg-dark-800/80" class="inline-flex items-center gap-2.5 rounded-full border border-gray-200/50 bg-white/80 px-5 py-2.5 shadow-sm backdrop-blur-sm dark:border-dark-700/50 dark:bg-dark-800/80"
> >
@@ -204,6 +207,63 @@
</div> </div>
</div> </div>
<!-- Pain Points Section -->
<div class="mb-16">
<h2 class="mb-8 text-center text-2xl font-bold text-gray-900 dark:text-white md:text-3xl">
{{ t('home.painPoints.title') }}
</h2>
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<!-- Pain Point 1: Expensive -->
<div class="rounded-xl border border-red-200/50 bg-red-50/50 p-5 dark:border-red-900/30 dark:bg-red-950/20">
<div class="mb-3 flex h-10 w-10 items-center justify-center rounded-lg bg-red-100 dark:bg-red-900/30">
<svg class="h-5 w-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<h3 class="mb-1.5 font-semibold text-gray-900 dark:text-white">{{ t('home.painPoints.items.expensive.title') }}</h3>
<p class="text-sm text-gray-600 dark:text-dark-400">{{ t('home.painPoints.items.expensive.desc') }}</p>
</div>
<!-- Pain Point 2: Complex -->
<div class="rounded-xl border border-orange-200/50 bg-orange-50/50 p-5 dark:border-orange-900/30 dark:bg-orange-950/20">
<div class="mb-3 flex h-10 w-10 items-center justify-center rounded-lg bg-orange-100 dark:bg-orange-900/30">
<svg class="h-5 w-5 text-orange-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
</div>
<h3 class="mb-1.5 font-semibold text-gray-900 dark:text-white">{{ t('home.painPoints.items.complex.title') }}</h3>
<p class="text-sm text-gray-600 dark:text-dark-400">{{ t('home.painPoints.items.complex.desc') }}</p>
</div>
<!-- Pain Point 3: Unstable -->
<div class="rounded-xl border border-yellow-200/50 bg-yellow-50/50 p-5 dark:border-yellow-900/30 dark:bg-yellow-950/20">
<div class="mb-3 flex h-10 w-10 items-center justify-center rounded-lg bg-yellow-100 dark:bg-yellow-900/30">
<svg class="h-5 w-5 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
</div>
<h3 class="mb-1.5 font-semibold text-gray-900 dark:text-white">{{ t('home.painPoints.items.unstable.title') }}</h3>
<p class="text-sm text-gray-600 dark:text-dark-400">{{ t('home.painPoints.items.unstable.desc') }}</p>
</div>
<!-- Pain Point 4: No Control -->
<div class="rounded-xl border border-gray-200/50 bg-gray-50/50 p-5 dark:border-dark-700/50 dark:bg-dark-800/50">
<div class="mb-3 flex h-10 w-10 items-center justify-center rounded-lg bg-gray-100 dark:bg-dark-700">
<svg class="h-5 w-5 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
</svg>
</div>
<h3 class="mb-1.5 font-semibold text-gray-900 dark:text-white">{{ t('home.painPoints.items.noControl.title') }}</h3>
<p class="text-sm text-gray-600 dark:text-dark-400">{{ t('home.painPoints.items.noControl.desc') }}</p>
</div>
</div>
</div>
<!-- Solutions Section Title -->
<div class="mb-8 text-center">
<h2 class="mb-2 text-2xl font-bold text-gray-900 dark:text-white md:text-3xl">
{{ t('home.solutions.title') }}
</h2>
<p class="text-gray-600 dark:text-dark-400">{{ t('home.solutions.subtitle') }}</p>
</div>
<!-- Features Grid --> <!-- Features Grid -->
<div class="mb-12 grid gap-6 md:grid-cols-3"> <div class="mb-12 grid gap-6 md:grid-cols-3">
<!-- Feature 1: Unified Gateway --> <!-- Feature 1: Unified Gateway -->
@@ -369,6 +429,77 @@
> >
</div> </div>
</div> </div>
<!-- Comparison Table -->
<div class="mb-16">
<h2 class="mb-8 text-center text-2xl font-bold text-gray-900 dark:text-white md:text-3xl">
{{ t('home.comparison.title') }}
</h2>
<div class="overflow-x-auto">
<table class="w-full rounded-xl border border-gray-200/50 bg-white/60 backdrop-blur-sm dark:border-dark-700/50 dark:bg-dark-800/60">
<thead>
<tr class="border-b border-gray-200/50 dark:border-dark-700/50">
<th class="px-6 py-4 text-left text-sm font-semibold text-gray-900 dark:text-white">{{ t('home.comparison.headers.feature') }}</th>
<th class="px-6 py-4 text-center text-sm font-semibold text-gray-500 dark:text-dark-400">{{ t('home.comparison.headers.official') }}</th>
<th class="px-6 py-4 text-center text-sm font-semibold text-primary-600 dark:text-primary-400">{{ t('home.comparison.headers.us') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200/50 dark:divide-dark-700/50">
<tr>
<td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">{{ t('home.comparison.items.pricing.feature') }}</td>
<td class="px-6 py-4 text-center text-sm text-gray-500 dark:text-dark-400">{{ t('home.comparison.items.pricing.official') }}</td>
<td class="px-6 py-4 text-center text-sm font-medium text-primary-600 dark:text-primary-400">{{ t('home.comparison.items.pricing.us') }}</td>
</tr>
<tr>
<td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">{{ t('home.comparison.items.models.feature') }}</td>
<td class="px-6 py-4 text-center text-sm text-gray-500 dark:text-dark-400">{{ t('home.comparison.items.models.official') }}</td>
<td class="px-6 py-4 text-center text-sm font-medium text-primary-600 dark:text-primary-400">{{ t('home.comparison.items.models.us') }}</td>
</tr>
<tr>
<td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">{{ t('home.comparison.items.management.feature') }}</td>
<td class="px-6 py-4 text-center text-sm text-gray-500 dark:text-dark-400">{{ t('home.comparison.items.management.official') }}</td>
<td class="px-6 py-4 text-center text-sm font-medium text-primary-600 dark:text-primary-400">{{ t('home.comparison.items.management.us') }}</td>
</tr>
<tr>
<td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">{{ t('home.comparison.items.stability.feature') }}</td>
<td class="px-6 py-4 text-center text-sm text-gray-500 dark:text-dark-400">{{ t('home.comparison.items.stability.official') }}</td>
<td class="px-6 py-4 text-center text-sm font-medium text-primary-600 dark:text-primary-400">{{ t('home.comparison.items.stability.us') }}</td>
</tr>
<tr>
<td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">{{ t('home.comparison.items.control.feature') }}</td>
<td class="px-6 py-4 text-center text-sm text-gray-500 dark:text-dark-400">{{ t('home.comparison.items.control.official') }}</td>
<td class="px-6 py-4 text-center text-sm font-medium text-primary-600 dark:text-primary-400">{{ t('home.comparison.items.control.us') }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- CTA Section -->
<div class="mb-8 rounded-2xl bg-gradient-to-r from-primary-500 to-primary-600 p-8 text-center shadow-xl shadow-primary-500/20 md:p-12">
<h2 class="mb-3 text-2xl font-bold text-white md:text-3xl">
{{ t('home.cta.title') }}
</h2>
<p class="mb-6 text-primary-100">
{{ t('home.cta.description') }}
</p>
<router-link
v-if="!isAuthenticated"
to="/register"
class="inline-flex items-center gap-2 rounded-full bg-white px-8 py-3 font-semibold text-primary-600 shadow-lg transition-all hover:bg-gray-50 hover:shadow-xl"
>
{{ t('home.cta.button') }}
<Icon name="arrowRight" size="md" :stroke-width="2" />
</router-link>
<router-link
v-else
:to="dashboardPath"
class="inline-flex items-center gap-2 rounded-full bg-white px-8 py-3 font-semibold text-primary-600 shadow-lg transition-all hover:bg-gray-50 hover:shadow-xl"
>
{{ t('home.goToDashboard') }}
<Icon name="arrowRight" size="md" :stroke-width="2" />
</router-link>
</div>
</div> </div>
</main> </main>
@@ -380,7 +511,6 @@
<p class="text-sm text-gray-500 dark:text-dark-400"> <p class="text-sm text-gray-500 dark:text-dark-400">
&copy; {{ currentYear }} {{ siteName }}. {{ t('home.footer.allRightsReserved') }} &copy; {{ currentYear }} {{ siteName }}. {{ t('home.footer.allRightsReserved') }}
</p> </p>
<div class="flex items-center gap-4">
<a <a
v-if="docUrl" v-if="docUrl"
:href="docUrl" :href="docUrl"
@@ -390,17 +520,11 @@
> >
{{ t('home.docs') }} {{ t('home.docs') }}
</a> </a>
<a
:href="githubUrl"
target="_blank"
rel="noopener noreferrer"
class="text-sm text-gray-500 transition-colors hover:text-gray-700 dark:text-dark-400 dark:hover:text-white"
>
GitHub
</a>
</div>
</div> </div>
</footer> </footer>
<!-- 微信客服悬浮按钮 -->
<WechatServiceButton />
</div> </div>
</template> </template>
@@ -410,6 +534,7 @@ import { useI18n } from 'vue-i18n'
import { useAuthStore, useAppStore } from '@/stores' import { useAuthStore, useAppStore } from '@/stores'
import LocaleSwitcher from '@/components/common/LocaleSwitcher.vue' import LocaleSwitcher from '@/components/common/LocaleSwitcher.vue'
import Icon from '@/components/icons/Icon.vue' import Icon from '@/components/icons/Icon.vue'
import WechatServiceButton from '@/components/common/WechatServiceButton.vue'
const { t } = useI18n() const { t } = useI18n()
@@ -419,7 +544,6 @@ const appStore = useAppStore()
// Site settings - directly from appStore (already initialized from injected config) // Site settings - directly from appStore (already initialized from injected config)
const siteName = computed(() => appStore.cachedPublicSettings?.site_name || appStore.siteName || 'Sub2API') const siteName = computed(() => appStore.cachedPublicSettings?.site_name || appStore.siteName || 'Sub2API')
const siteLogo = computed(() => appStore.cachedPublicSettings?.site_logo || appStore.siteLogo || '') const siteLogo = computed(() => appStore.cachedPublicSettings?.site_logo || appStore.siteLogo || '')
const siteSubtitle = computed(() => appStore.cachedPublicSettings?.site_subtitle || 'AI API Gateway Platform')
const docUrl = computed(() => appStore.cachedPublicSettings?.doc_url || appStore.docUrl || '') const docUrl = computed(() => appStore.cachedPublicSettings?.doc_url || appStore.docUrl || '')
const homeContent = computed(() => appStore.cachedPublicSettings?.home_content || '') const homeContent = computed(() => appStore.cachedPublicSettings?.home_content || '')
@@ -432,9 +556,6 @@ const isHomeContentUrl = computed(() => {
// Theme // Theme
const isDark = ref(document.documentElement.classList.contains('dark')) const isDark = ref(document.documentElement.classList.contains('dark'))
// GitHub URL
const githubUrl = 'https://github.com/Wei-Shaw/sub2api'
// Auth state // Auth state
const isAuthenticated = computed(() => authStore.isAuthenticated) const isAuthenticated = computed(() => authStore.isAuthenticated)
const isAdmin = computed(() => authStore.isAdmin) const isAdmin = computed(() => authStore.isAdmin)

View File

@@ -3751,21 +3751,20 @@
<!-- Tab: Features (功能开关) --> <!-- Tab: Features (功能开关) -->
<div v-show="activeTab === 'features'" class="space-y-6"> <div v-show="activeTab === 'features'" class="space-y-6">
<div class="card"> <div class="card">
<div class="border-b border-gray-100 px-6 py-4 dark:border-dark-700"> <div class="border-b border-gray-100 px-6 py-4 dark:border-dark-700">
<h2 class="text-lg font-semibold text-gray-900 dark:text-white"> <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
{{ t('admin.settings.features.channelMonitor.title') }} {{ t("admin.settings.features.channelMonitor.title") }}
</h2> </h2>
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400"> <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
{{ t('admin.settings.features.channelMonitor.description') }} {{ t("admin.settings.features.channelMonitor.description") }}
</p> </p>
<p class="mt-1.5 text-xs"> <p class="mt-1.5 text-xs">
<router-link <router-link
to="/admin/channels/monitor" to="/admin/channels/monitor"
class="inline-flex items-center gap-1 text-primary-600 hover:underline dark:text-primary-400" class="inline-flex items-center gap-1 text-primary-600 hover:underline dark:text-primary-400"
> >
{{ t('admin.settings.features.channelMonitor.configureLink') }} {{ t("admin.settings.features.channelMonitor.configureLink") }}
<span aria-hidden="true">→</span> <span aria-hidden="true">→</span>
</router-link> </router-link>
</p> </p>
@@ -3774,10 +3773,10 @@
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<div> <div>
<label class="text-sm font-medium text-gray-700 dark:text-gray-300"> <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
{{ t('admin.settings.features.channelMonitor.enabled') }} {{ t("admin.settings.features.channelMonitor.enabled") }}
</label> </label>
<p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400"> <p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.settings.features.channelMonitor.enabledHint') }} {{ t("admin.settings.features.channelMonitor.enabledHint") }}
</p> </p>
</div> </div>
<Toggle v-model="form.channel_monitor_enabled" /> <Toggle v-model="form.channel_monitor_enabled" />
@@ -3785,7 +3784,7 @@
<div v-if="form.channel_monitor_enabled"> <div v-if="form.channel_monitor_enabled">
<label class="input-label"> <label class="input-label">
{{ t('admin.settings.features.channelMonitor.defaultInterval') }} {{ t("admin.settings.features.channelMonitor.defaultInterval") }}
<span class="text-red-500">*</span> <span class="text-red-500">*</span>
</label> </label>
<input <input
@@ -3796,7 +3795,7 @@
class="input" class="input"
/> />
<p class="mt-1 text-xs text-gray-400"> <p class="mt-1 text-xs text-gray-400">
{{ t('admin.settings.features.channelMonitor.defaultIntervalHint') }} {{ t("admin.settings.features.channelMonitor.defaultIntervalHint") }}
</p> </p>
</div> </div>
</div> </div>
@@ -3805,17 +3804,17 @@
<div class="card"> <div class="card">
<div class="border-b border-gray-100 px-6 py-4 dark:border-dark-700"> <div class="border-b border-gray-100 px-6 py-4 dark:border-dark-700">
<h2 class="text-lg font-semibold text-gray-900 dark:text-white"> <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
{{ t('admin.settings.features.availableChannels.title') }} {{ t("admin.settings.features.availableChannels.title") }}
</h2> </h2>
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400"> <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
{{ t('admin.settings.features.availableChannels.description') }} {{ t("admin.settings.features.availableChannels.description") }}
</p> </p>
<p class="mt-1.5 text-xs"> <p class="mt-1.5 text-xs">
<router-link <router-link
to="/admin/channels/pricing" to="/admin/channels/pricing"
class="inline-flex items-center gap-1 text-primary-600 hover:underline dark:text-primary-400" class="inline-flex items-center gap-1 text-primary-600 hover:underline dark:text-primary-400"
> >
{{ t('admin.settings.features.availableChannels.configureLink') }} {{ t("admin.settings.features.availableChannels.configureLink") }}
<span aria-hidden="true">→</span> <span aria-hidden="true">→</span>
</router-link> </router-link>
</p> </p>
@@ -3824,18 +3823,18 @@
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<div> <div>
<label class="text-sm font-medium text-gray-700 dark:text-gray-300"> <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
{{ t('admin.settings.features.availableChannels.enabled') }} {{ t("admin.settings.features.availableChannels.enabled") }}
</label> </label>
<p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400"> <p class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.settings.features.availableChannels.enabledHint') }} {{ t("admin.settings.features.availableChannels.enabledHint") }}
</p> </p>
</div> </div>
<Toggle v-model="form.available_channels_enabled" /> <Toggle v-model="form.available_channels_enabled" />
</div> </div>
</div> </div>
</div> </div>
</div>
</div><!-- /Tab: Features --> <!-- /Tab: Features -->
<!-- Tab: Email --> <!-- Tab: Email -->
<!-- Tab: Payment --> <!-- Tab: Payment -->
@@ -4254,8 +4253,6 @@
}}</label> }}</label>
<ImageUpload <ImageUpload
v-model="form.payment_help_image_url" v-model="form.payment_help_image_url"
:upload-label="t('admin.settings.site.uploadImage')"
:remove-label="t('admin.settings.site.remove')"
:placeholder=" :placeholder="
t('admin.settings.payment.helpImagePlaceholder') t('admin.settings.payment.helpImagePlaceholder')
" "

View File

@@ -155,8 +155,6 @@ vi.mock("vue-i18n", async () => {
"admin.settings.payment.findProvider": "查看支持的支付方式", "admin.settings.payment.findProvider": "查看支持的支付方式",
"admin.settings.openaiExperimentalScheduler.title": "OpenAI 实验调度策略", "admin.settings.openaiExperimentalScheduler.title": "OpenAI 实验调度策略",
"admin.settings.openaiExperimentalScheduler.description": "默认关闭。开启后仅影响本网关在 OpenAI 账号间的实验性调度选择逻辑,不代表上游 OpenAI 官方能力。", "admin.settings.openaiExperimentalScheduler.description": "默认关闭。开启后仅影响本网关在 OpenAI 账号间的实验性调度选择逻辑,不代表上游 OpenAI 官方能力。",
"admin.settings.site.uploadImage": "上传图片",
"admin.settings.site.remove": "移除",
}; };
return { return {
...actual, ...actual,
@@ -242,37 +240,6 @@ const SelectStub = defineComponent({
}, },
}); });
const ImageUploadStub = defineComponent({
props: {
modelValue: {
type: String,
default: "",
},
uploadLabel: {
type: String,
default: "",
},
removeLabel: {
type: String,
default: "",
},
placeholder: {
type: String,
default: "",
},
},
setup(props) {
return () =>
h("div", {
class: "image-upload-stub",
"data-model-value": props.modelValue,
"data-upload-label": props.uploadLabel,
"data-remove-label": props.removeLabel,
"data-placeholder": props.placeholder,
});
},
});
const baseSettingsResponse = { const baseSettingsResponse = {
registration_enabled: true, registration_enabled: true,
email_verify_enabled: false, email_verify_enabled: false,
@@ -408,7 +375,7 @@ function mountView() {
GroupBadge: true, GroupBadge: true,
GroupOptionItem: true, GroupOptionItem: true,
ProxySelector: true, ProxySelector: true,
ImageUpload: ImageUploadStub, ImageUpload: true,
BackupSettings: true, BackupSettings: true,
}, },
}, },
@@ -615,7 +582,7 @@ describe("admin SettingsView payment visible method controls", () => {
GroupBadge: true, GroupBadge: true,
GroupOptionItem: true, GroupOptionItem: true,
ProxySelector: true, ProxySelector: true,
ImageUpload: ImageUploadStub, ImageUpload: true,
BackupSettings: true, BackupSettings: true,
}, },
}, },
@@ -641,24 +608,6 @@ describe("admin SettingsView payment visible method controls", () => {
); );
expect(wrapper.text()).not.toContain("OpenAI 高级调度器"); expect(wrapper.text()).not.toContain("OpenAI 高级调度器");
}); });
it("passes translated upload and remove labels to the payment help image uploader", async () => {
const wrapper = mountView();
await flushPromises();
await openPaymentTab(wrapper);
const imageUploads = wrapper.findAll(".image-upload-stub");
expect(imageUploads.length).toBeGreaterThan(0);
const paymentHelpImageUpload = imageUploads.find(
(node) => node.attributes("data-placeholder") === "admin.settings.payment.helpImagePlaceholder",
);
expect(paymentHelpImageUpload).toBeDefined();
expect(paymentHelpImageUpload?.attributes("data-upload-label")).toBe("上传图片");
expect(paymentHelpImageUpload?.attributes("data-remove-label")).toBe("移除");
});
}); });
describe("admin SettingsView wechat connect controls", () => { describe("admin SettingsView wechat connect controls", () => {

View File

@@ -122,6 +122,7 @@ const platformRows = computed((): SummaryRow[] => {
available_accounts: availableAccounts, available_accounts: availableAccounts,
rate_limited_accounts: safeNumber(avail.rate_limit_count), rate_limited_accounts: safeNumber(avail.rate_limit_count),
error_accounts: safeNumber(avail.error_count), error_accounts: safeNumber(avail.error_count),
total_concurrency: totalConcurrency, total_concurrency: totalConcurrency,
used_concurrency: usedConcurrency, used_concurrency: usedConcurrency,
@@ -161,7 +162,6 @@ const groupRows = computed((): SummaryRow[] => {
total_accounts: totalAccounts, total_accounts: totalAccounts,
available_accounts: availableAccounts, available_accounts: availableAccounts,
rate_limited_accounts: safeNumber(avail.rate_limit_count), rate_limited_accounts: safeNumber(avail.rate_limit_count),
error_accounts: safeNumber(avail.error_count), error_accounts: safeNumber(avail.error_count),
total_concurrency: totalConcurrency, total_concurrency: totalConcurrency,
used_concurrency: usedConcurrency, used_concurrency: usedConcurrency,
@@ -329,6 +329,7 @@ function formatDuration(seconds: number): string {
} }
watch( watch(
() => realtimeEnabled.value, () => realtimeEnabled.value,
async (enabled) => { async (enabled) => {

View File

@@ -311,7 +311,6 @@ interface CreateOrderOptions {
wechatResumeToken?: string wechatResumeToken?: string
paymentType?: string paymentType?: string
isResume?: boolean isResume?: boolean
mobileQrFallbackAttempted?: boolean
} }
interface WeixinJSBridgeLike { interface WeixinJSBridgeLike {
@@ -667,15 +666,14 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
submitting.value = true submitting.value = true
errorMessage.value = '' errorMessage.value = ''
errorHintMessage.value = '' errorHintMessage.value = ''
const requestType = normalizeVisibleMethod(options.paymentType || selectedMethod.value) || options.paymentType || selectedMethod.value
try { try {
const requestType = normalizeVisibleMethod(options.paymentType || selectedMethod.value) || options.paymentType || selectedMethod.value
const payload = buildCreateOrderPayload({ const payload = buildCreateOrderPayload({
amount: orderAmount, amount: orderAmount,
paymentType: requestType, paymentType: requestType,
orderType, orderType,
planId, planId,
origin: typeof window !== 'undefined' ? window.location.origin : '', origin: typeof window !== 'undefined' ? window.location.origin : '',
isMobile: isMobileDevice(),
isWechatBrowser: typeof window !== 'undefined' && /MicroMessenger/i.test(window.navigator.userAgent), isWechatBrowser: typeof window !== 'undefined' && /MicroMessenger/i.test(window.navigator.userAgent),
}) })
if (options.openid) { if (options.openid) {
@@ -749,20 +747,8 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
appStore.showInfo(t('payment.qr.cancelled')) appStore.showInfo(t('payment.qr.cancelled'))
resetPayment() resetPayment()
} else if (errMsg && !errMsg.includes('ok')) { } else if (errMsg && !errMsg.includes('ok')) {
resetPayment()
const fallbackApplied = await attemptMobileQrFallback(
{ reason: 'WECHAT_JSAPI_FAILED', message: errMsg },
{
orderAmount,
orderType,
planId,
paymentType: visibleMethod,
attempted: options.mobileQrFallbackAttempted === true,
},
)
if (!fallbackApplied) {
applyScenarioError({ reason: 'WECHAT_JSAPI_FAILED', message: errMsg }, visibleMethod) applyScenarioError({ reason: 'WECHAT_JSAPI_FAILED', message: errMsg }, visibleMethod)
} resetPayment()
} else { } else {
const resultState = { ...decision.paymentState } const resultState = { ...decision.paymentState }
resetPayment() resetPayment()
@@ -770,17 +756,8 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
} }
} catch (err: unknown) { } catch (err: unknown) {
resetPayment() resetPayment()
const fallbackApplied = await attemptMobileQrFallback(err, {
orderAmount,
orderType,
planId,
paymentType: visibleMethod,
attempted: options.mobileQrFallbackAttempted === true,
})
if (!fallbackApplied) {
throw err throw err
} }
}
return return
} }
if (decision.kind === 'redirect_waiting' && decision.paymentState.payUrl) { if (decision.kind === 'redirect_waiting' && decision.paymentState.payUrl) {
@@ -799,14 +776,6 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
} else if (apiErr.reason === 'CANCEL_RATE_LIMITED') { } else if (apiErr.reason === 'CANCEL_RATE_LIMITED') {
errorMessage.value = t('payment.errors.cancelRateLimited') errorMessage.value = t('payment.errors.cancelRateLimited')
errorHintMessage.value = '' errorHintMessage.value = ''
} else if (await attemptMobileQrFallback(err, {
orderAmount,
orderType,
planId,
paymentType: requestType,
attempted: options.mobileQrFallbackAttempted === true,
})) {
return
} else { } else {
const handled = applyScenarioError( const handled = applyScenarioError(
err, err,
@@ -826,101 +795,6 @@ async function createOrder(orderAmount: number, orderType: OrderType, planId?: n
} }
} }
interface MobileQrFallbackContext {
orderAmount: number
orderType: OrderType
planId?: number
paymentType: string
attempted: boolean
}
function shouldFallbackToDesktopQr(err: unknown, paymentMethod: string, attempted: boolean): boolean {
if (attempted || !isMobileDevice()) {
return false
}
const normalizedMethod = normalizeVisibleMethod(paymentMethod) || paymentMethod
const reason = typeof err === 'object' && err && 'reason' in err && typeof err.reason === 'string'
? err.reason
: ''
const message = err instanceof Error
? err.message
: (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string'
? err.message
: '')
const normalizedMessage = message.toLowerCase()
if (normalizedMethod === 'wxpay') {
return reason === 'WECHAT_H5_NOT_AUTHORIZED'
|| reason === 'WECHAT_PAYMENT_MP_NOT_CONFIGURED'
|| reason === 'WECHAT_JSAPI_FAILED'
|| reason === 'PAYMENT_GATEWAY_ERROR'
|| reason === 'UNHANDLED_PAYMENT_SCENARIO'
|| normalizedMessage.includes('weixinjsbridge is unavailable')
|| normalizedMessage.includes('wechat_jsapi_unavailable')
}
if (normalizedMethod === 'alipay') {
return reason === 'PAYMENT_GATEWAY_ERROR' || reason === 'UNHANDLED_PAYMENT_SCENARIO'
}
return false
}
async function attemptMobileQrFallback(err: unknown, context: MobileQrFallbackContext): Promise<boolean> {
if (!shouldFallbackToDesktopQr(err, context.paymentType, context.attempted)) {
return false
}
try {
const visibleMethod = normalizeVisibleMethod(context.paymentType) || context.paymentType
const payload = buildCreateOrderPayload({
amount: context.orderAmount,
paymentType: visibleMethod,
orderType: context.orderType,
planId: context.planId,
origin: typeof window !== 'undefined' ? window.location.origin : '',
isMobile: false,
isWechatBrowser: false,
})
const result = await paymentStore.createOrder(payload) as CreateOrderResult & { resume_token?: string }
const stripeMethod = visibleMethod === 'wxpay' ? 'wechat_pay' : 'alipay'
const stripeRouteUrl = result.client_secret
? router.resolve({
path: '/payment/stripe',
query: {
order_id: String(result.order_id),
client_secret: result.client_secret,
method: stripeMethod,
resume_token: result.resume_token || undefined,
},
}).href
: ''
const decision = decidePaymentLaunch(result, {
visibleMethod,
orderType: context.orderType,
isMobile: false,
isWechatBrowser: false,
stripePopupUrl: stripeRouteUrl,
stripeRouteUrl,
})
if (decision.kind !== 'qr_waiting' || !decision.paymentState.qrCode) {
return false
}
errorMessage.value = ''
errorHintMessage.value = ''
paymentState.value = decision.paymentState
paymentPhase.value = 'paying'
persistRecoverySnapshot(decision.recovery)
appStore.showWarning(t('payment.errors.mobilePaymentFallbackToQr'))
return true
} catch {
return false
}
}
function applyScenarioError(err: unknown, paymentMethod: string): boolean { function applyScenarioError(err: unknown, paymentMethod: string): boolean {
const descriptor = describePaymentScenarioError(err, { const descriptor = describePaymentScenarioError(err, {
paymentMethod, paymentMethod,

View File

@@ -16,7 +16,6 @@ const refreshUser = vi.hoisted(() => vi.fn())
const fetchActiveSubscriptions = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)) const fetchActiveSubscriptions = vi.hoisted(() => vi.fn().mockResolvedValue(undefined))
const showError = vi.hoisted(() => vi.fn()) const showError = vi.hoisted(() => vi.fn())
const showInfo = vi.hoisted(() => vi.fn()) const showInfo = vi.hoisted(() => vi.fn())
const showWarning = vi.hoisted(() => vi.fn())
const getCheckoutInfo = vi.hoisted(() => vi.fn()) const getCheckoutInfo = vi.hoisted(() => vi.fn())
const bridgeInvoke = vi.hoisted(() => vi.fn()) const bridgeInvoke = vi.hoisted(() => vi.fn())
@@ -70,7 +69,6 @@ vi.mock('@/stores', () => ({
useAppStore: () => ({ useAppStore: () => ({
showError, showError,
showInfo, showInfo,
showWarning,
}), }),
})) }))
@@ -195,7 +193,6 @@ describe('PaymentView WeChat JSAPI flow', () => {
fetchActiveSubscriptions.mockReset().mockResolvedValue(undefined) fetchActiveSubscriptions.mockReset().mockResolvedValue(undefined)
showError.mockReset() showError.mockReset()
showInfo.mockReset() showInfo.mockReset()
showWarning.mockReset()
getCheckoutInfo.mockReset().mockResolvedValue(checkoutInfoFixture()) getCheckoutInfo.mockReset().mockResolvedValue(checkoutInfoFixture())
bridgeInvoke.mockReset() bridgeInvoke.mockReset()
window.localStorage.clear() window.localStorage.clear()
@@ -367,24 +364,13 @@ describe('PaymentView WeChat JSAPI flow', () => {
}) })
}) })
it('falls back to QR flow when mobile WeChat payment is unavailable', async () => { it('shows explicit H5 authorization guidance instead of failing silently', async () => {
routeState.query = { routeState.query = {
wechat_resume: '1', wechat_resume: '1',
wechat_resume_token: 'resume-token-h5', wechat_resume_token: 'resume-token-h5',
payment_type: 'wxpay_direct', payment_type: 'wxpay_direct',
} }
createOrder createOrder.mockRejectedValueOnce({ reason: 'WECHAT_H5_NOT_AUTHORIZED' })
.mockRejectedValueOnce({ reason: 'WECHAT_H5_NOT_AUTHORIZED' })
.mockResolvedValueOnce({
order_id: 778,
amount: 88,
pay_amount: 88,
fee_rate: 0,
expires_at: '2099-01-01T00:10:00.000Z',
payment_type: 'wxpay',
qr_code: 'weixin://wxpay/bizpayurl?pr=fallback-native',
out_trade_no: 'sub2_qr_778',
})
shallowMount(PaymentView, { shallowMount(PaymentView, {
global: { global: {
@@ -397,18 +383,8 @@ describe('PaymentView WeChat JSAPI flow', () => {
await flushPromises() await flushPromises()
await flushPromises() await flushPromises()
expect(createOrder).toHaveBeenNthCalledWith(1, expect.objectContaining({ expect(showError).toHaveBeenCalledWith(
payment_type: 'wxpay', 'payment.errors.wechatH5NotAuthorized payment.errors.wechatOpenInWeChatHint',
is_mobile: true, )
wechat_resume_token: 'resume-token-h5',
}))
expect(createOrder).toHaveBeenNthCalledWith(2, expect.objectContaining({
payment_type: 'wxpay',
is_mobile: false,
payment_source: 'hosted_redirect',
}))
expect(showWarning).toHaveBeenCalledWith('payment.errors.mobilePaymentFallbackToQr')
expect(showError).not.toHaveBeenCalled()
expect(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY)).toContain('weixin://wxpay/bizpayurl?pr=fallback-native')
}) })
}) })

View File

@@ -13,6 +13,7 @@ export default defineConfig({
test: { test: {
globals: true, globals: true,
environment: 'jsdom', environment: 'jsdom',
setupFiles: ['src/__tests__/setup.ts'],
include: ['src/**/*.{test,spec}.{js,ts,jsx,tsx}'], include: ['src/**/*.{test,spec}.{js,ts,jsx,tsx}'],
exclude: ['node_modules', 'dist'], exclude: ['node_modules', 'dist'],
coverage: { coverage: {