diff --git a/README.md b/README.md index 8ca37bfa..fe174a9f 100644 --- a/README.md +++ b/README.md @@ -407,11 +407,13 @@ qualityGuard: holdTimeout: 30s minOutputTokens: 8 onExhausted: fail_closed # fail_open | fail_closed + # Disable on the first confirmed missing-thinking or degraded-speed hit. + autoDisable: true accountCooldown: 12h idleAccountCooldown: 15m ``` -`requestRetry` runs on the gateway request path and is independent of the sidecar. `config.example.yaml` keeps `enabled: false`; set it true to intercept. When enabled, a thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; replay-safe stateless requests may try another account. TUI follow-ups (`previous_response_id`) and hosted-tool turns are still held for classification, but a quality withhold never replays account-bound state or side-effecting tools across accounts; `onExhausted` returns `503 quality_degraded` or releases that held body. Context compaction, image, video, and ForcedEgress probe requests are unchanged. +`requestRetry` runs on the gateway request path and is independent of the sidecar. The example above explicitly enables it; built-in defaults and `config.example.yaml` leave both `enabled` and `autoDisable` off. Either switch enables request-path quality checks and retries. A thinking-model stream with enough visible output and no streamed reasoning is **not delivered**; another account is tried. `autoDisable: true` disables an account on the first confirmed missing-thinking or degraded output-speed hit (soft-TPS, hard-TPS, or buffered-burst). The Account Maintenance switch controls `autoDisable`; turning it off restores the YAML `requestRetry.enabled` policy. If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. Context compaction is exempt from both missing-thinking and output-speed account penalties. Image, video, stored-response, and ForcedEgress probe requests are unchanged. Grok TUI tool turns stay held so 0-thinking dumps cannot skip the gate. ```bash docker compose --profile quality-guard up -d --build diff --git a/README.zh-CN.md b/README.zh-CN.md index 0d08279d..05ab9133 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -373,11 +373,13 @@ qualityGuard: holdTimeout: 30s minOutputTokens: 8 onExhausted: fail_closed # fail_open | fail_closed + # 首次确认缺 thinking 或吞吐降智(soft/hard/burst)时立即禁用账号。 + autoDisable: true accountCooldown: 12h idleAccountCooldown: 15m ``` -`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。`config.example.yaml` 里 `enabled` 仍为 false,打开后才拦截。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**;只有可安全重放的无状态请求才会排除账号重试。TUI 续聊(`previous_response_id`)和 hosted tools 仍会进入 hold 检测,但质量拦截不会把账号绑定状态或有副作用的工具跨账号重放,最终按 `onExhausted` 返回 `503 quality_degraded` 或放出当前响应。上下文压缩、图片、视频和 ForcedEgress 探针不受影响。 +`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。上面的示例显式开启;内置默认值和 `config.example.yaml` 均将 `enabled`、`autoDisable` 设为关闭。任一开关开启后都会启用请求内质量检测与重试。可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试;`autoDisable: true` 会在首次确认缺 thinking 或吞吐降智(soft/hard/burst)时直接禁用账号。管理页面的“自动停用降智账号”控制 `autoDisable`,关闭后恢复 YAML 中 `requestRetry.enabled` 的原有策略。全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。上下文压缩同时豁免缺 thinking 和输出速度的账号惩罚。不处理图/视频、stored response 钉账号和 ForcedEgress 探针。Grok TUI 带 tools 的回合仍会 hold,避免 0-thinking 降智流跳过闸门。 ```bash docker compose --profile quality-guard up -d --build diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index 41928954..52dcb8e4 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -352,7 +352,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat modelRepo.SetInvalidationObserver(invalidationService.Notify) clientKeyRepo.SetInvalidationObserver(invalidationService.Notify) gatewayService := gateway.NewService(modelService, auditService, accountService, clientKeyService, providers, selector, responseRepo, cfg.Routing.MaxAttempts) - gatewayService.UpdateQualityRetry(qualityRetryRuntime(cfg.QualityGuard.RequestRetry)) + gatewayService.UpdateQualityRetry(qualityRetryRuntime(cfg.QualityGuard)) gatewayService.UpdateVideoMaxAttempts(cfg.Routing.VideoMaxAttempts) gatewayService.UpdateMarkBuildChatDeniedAsReauth(cfg.Routing.MarkBuildChatDeniedAsReauth) gatewayService.SetLogger(logger) @@ -409,7 +409,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat egressManager.UpdateAccountIsolatedConnections(next.Routing.AccountIsolatedConnections) reasoningReplay.UpdateConfig(reasoningreplay.Config{Enabled: next.Routing.ReasoningReplayEnabled, TTL: next.Routing.ReasoningReplayTTL.Value()}) gatewayService.UpdateMaxAttempts(next.Routing.MaxAttempts) - gatewayService.UpdateQualityRetry(qualityRetryRuntime(next.QualityGuard.RequestRetry)) + gatewayService.UpdateQualityRetry(qualityRetryRuntime(next.QualityGuard)) gatewayService.UpdateVideoMaxAttempts(next.Routing.VideoMaxAttempts) gatewayService.UpdateMarkBuildChatDeniedAsReauth(next.Routing.MarkBuildChatDeniedAsReauth) gatewayService.UpdateBuildForbiddenReauthPolicy(next.Accounts.MarkBuildForbiddenReauth, next.Accounts.BuildForbiddenReauthCodes) @@ -490,17 +490,26 @@ func accountAutoCleanConfig(value config.AccountsConfig) accountapp.AutoCleanCon } } -func qualityRetryRuntime(value config.QualityGuardRequestRetryConfig) gateway.QualityRetryRuntime { +func qualityRetryRuntime(value config.QualityGuardConfig) gateway.QualityRetryRuntime { + retry := value.RequestRetry return gateway.QualityRetryRuntime{ - Enabled: value.Enabled, - MaxAttempts: value.MaxAttempts, - HoldTimeout: value.HoldTimeout.Value(), - MinOutputTokens: int64(value.MinOutputTokens), - OnExhausted: value.OnExhausted, - AccountCooldown: value.AccountCooldown.Value(), - IdleAccountCooldown: value.IdleAccountCooldown.Value(), - MinEncryptedBytes: value.MinEncryptedBytes, - EncryptedBytesPerReasoningToken: value.EncryptedBytesPerReasoningToken, + // Auto-disable needs request-path detection even when the YAML retry + // switch is off. Derive this at runtime so turning auto-disable off + // restores the original policy without persisting a second switch. + Enabled: retry.Enabled || retry.AutoDisable, + MaxAttempts: retry.MaxAttempts, + HoldTimeout: retry.HoldTimeout.Value(), + MinOutputTokens: int64(retry.MinOutputTokens), + OnExhausted: retry.OnExhausted, + AutoDisable: retry.AutoDisable, + AccountCooldown: retry.AccountCooldown.Value(), + IdleAccountCooldown: retry.IdleAccountCooldown.Value(), + MinEncryptedBytes: retry.MinEncryptedBytes, + EncryptedBytesPerReasoningToken: retry.EncryptedBytesPerReasoningToken, + SoftTPS: value.SoftTPS, + HardTPS: value.HardTPS, + MinGenerationMS: value.MinimumGenerationWindow.Value().Milliseconds(), + FailClosed: value.FailClosed, } } diff --git a/backend/internal/app/quality_retry_test.go b/backend/internal/app/quality_retry_test.go new file mode 100644 index 00000000..b5c7417f --- /dev/null +++ b/backend/internal/app/quality_retry_test.go @@ -0,0 +1,77 @@ +package app + +import ( + "context" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/application/gateway" + settingsapp "github.com/chenyme/grok2api/backend/internal/application/settings" + "github.com/chenyme/grok2api/backend/internal/infra/config" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/chenyme/grok2api/backend/internal/infra/security" +) + +func TestDegradedAccountSwitchAppliesAndRestoresRequestRetryPolicy(t *testing.T) { + for _, retryEnabled := range []bool{false, true} { + t.Run(fmt.Sprintf("yaml_retry_%t", retryEnabled), func(t *testing.T) { + ctx := context.Background() + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(`secrets: + jwtSecret: "12345678901234567890123456789012" + credentialEncryptionKey: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" +`), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(path) + if err != nil { + t.Fatal(err) + } + cfg.QualityGuard.RequestRetry.Enabled = retryEnabled + db, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "settings.db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if err := db.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(cfg.Secrets.CredentialEncryptionKey) + if err != nil { + t.Fatal(err) + } + repo := relational.NewRuntimeSettingsRepository(db, cipher) + var applied gateway.QualityRetryRuntime + service := settingsapp.NewService(cfg, time.Time{}, 0, repo, nil, func(next config.Config) { + applied = qualityRetryRuntime(next.QualityGuard) + if next.QualityGuard.RequestRetry.Enabled != retryEnabled { + t.Fatal("management switch changed the YAML retry policy") + } + }) + for _, autoDisable := range []bool{true, false} { + snapshot := service.Get() + input := snapshot.Config + input.Accounts.AutoDisableDegradedAccounts = autoDisable + input.Accounts.AutoDisableDegradedAccountsProvided = true + if _, err := service.Update(ctx, snapshot.Revision, input); err != nil { + t.Fatal(err) + } + wantEnabled := retryEnabled || autoDisable + if applied.Enabled != wantEnabled || applied.AutoDisable != autoDisable { + t.Fatalf("hot reload: autoDisable=%t runtime=%#v", autoDisable, applied) + } + reloaded, _, _, err := settingsapp.LoadPersisted(ctx, cfg, repo) + if err != nil { + t.Fatal(err) + } + runtime := qualityRetryRuntime(reloaded.QualityGuard) + if runtime.Enabled != wantEnabled || runtime.AutoDisable != autoDisable || reloaded.QualityGuard.RequestRetry.Enabled != retryEnabled { + t.Fatalf("restart: autoDisable=%t runtime=%#v", autoDisable, runtime) + } + } + }) + } +} diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 6ba9144d..331d36ea 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -4,7 +4,9 @@ import ( "context" "errors" "fmt" + "net" "net/url" + "strconv" "strings" "sync" "time" @@ -1349,6 +1351,9 @@ func NormalizeProxyURL(value string) (string, error) { return "", errors.New("代理地址包含保留的账号占位符文本") } parseValue := strings.ReplaceAll(value, ProxyAccountPlaceholder, proxyAccountSentinel) + if normalized, ok := normalizeLegacyHTTPProxy(parseValue); ok { + parseValue = normalized + } parsed, err := url.Parse(parseValue) if err != nil { return "", errors.New("代理地址格式无效") @@ -1384,6 +1389,22 @@ func NormalizeProxyURL(value string) (string, error) { return parsed.String(), nil } +func normalizeLegacyHTTPProxy(value string) (string, bool) { + parts := strings.SplitN(value, ":", 4) + if len(parts) != 4 || net.ParseIP(parts[0]).To4() == nil || parts[2] == "" || parts[3] == "" { + return "", false + } + port, err := strconv.ParseUint(parts[1], 10, 16) + if err != nil || port == 0 { + return "", false + } + return (&url.URL{ + Scheme: "http", + Host: net.JoinHostPort(parts[0], strconv.FormatUint(port, 10)), + User: url.UserPassword(parts[2], parts[3]), + }).String(), true +} + func SanitizeCloudflareCookies(value string) string { allowed := make([]string, 0, 4) seen := make(map[string]struct{}) diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index c22059cf..e4ee7e5e 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -3,6 +3,7 @@ package egress import ( "encoding/base64" "errors" + "net/url" "strings" "testing" "time" @@ -49,6 +50,37 @@ func TestNormalizeProxyURLValidatesStructure(t *testing.T) { } } +func TestNormalizeProxyURLAcceptsLegacyHTTPProxyFormat(t *testing.T) { + value, err := NormalizeProxyURL("127.0.0.1:8080:user:password") + if err != nil { + t.Fatal(err) + } + if value != "http://user:password@127.0.0.1:8080" { + t.Fatalf("normalized legacy HTTP proxy = %q", value) + } +} + +func TestNormalizeProxyURLPreservesLegacyCredentials(t *testing.T) { + for _, password := range []string{"pass:with:colons", "pass:@/?#%中文"} { + t.Run(password, func(t *testing.T) { + value, err := NormalizeProxyURL("127.0.0.1:8080:user@domain:" + password) + if err != nil { + t.Fatal(err) + } + parsed, err := url.Parse(value) + if err != nil { + t.Fatal(err) + } + if parsed.Scheme != "http" || parsed.Host != "127.0.0.1:8080" || parsed.User == nil || parsed.User.Username() != "user@domain" { + t.Fatalf("unexpected normalized proxy = %q", value) + } + if got, ok := parsed.User.Password(); !ok || got != password { + t.Fatalf("password = %q, want %q", got, password) + } + }) + } +} + func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) { base := "trojan://password@proxy.example:443?security=tls&sni=edge.example" one, err := NormalizeProxyURL(base + "#one") @@ -65,21 +97,32 @@ func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) { } func TestNormalizeProxyURLAllowsAccountPlaceholderOnlyInUsername(t *testing.T) { - value, err := NormalizeProxyURL("socks5h://Default.{account}:token@resin:2260") - if err != nil { - t.Fatal(err) - } - if value != "socks5h://Default.%7Baccount%7D:token@resin:2260" && value != "socks5h://Default.{account}:token@resin:2260" { - t.Fatalf("normalized Resin proxy = %q", value) - } - if !strings.Contains(value, ProxyAccountPlaceholder) { - t.Fatalf("account placeholder was lost: %q", value) + for _, raw := range []string{ + "socks5h://Default.{account}:token@resin:2260", + "127.0.0.1:8080:Default.{account}:token", + } { + t.Run(raw, func(t *testing.T) { + value, err := NormalizeProxyURL(raw) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(value, ProxyAccountPlaceholder) { + t.Fatalf("account placeholder was lost: %q", value) + } + if again, err := NormalizeProxyURL(value); err != nil || again != value { + t.Fatalf("proxy normalization is not stable: %q, err = %v", again, err) + } + }) } for _, invalid := range []string{ "socks5h://user:token@{account}:2260", "socks5h://user:{account}@resin:2260", "socks5h://{account}:{account}@resin:2260", "socks5h://grok2api_account_placeholder:token@{account}:2260", + "127.0.0.1:8080:user:{account}", + "127.0.0.1:8080:{account}:{account}", + "127.0.0.1:8080:{account}.{account}:token", + "127.0.0.1:8080:grok2api_account_placeholder:{account}", } { if _, err := NormalizeProxyURL(invalid); err == nil { t.Fatalf("invalid account placeholder accepted: %q", invalid) diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index 2536b967..ee98e42a 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -45,6 +45,7 @@ func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) { plain, skipped, err := parseProxySubscription(strings.Join([]string{ "# proxy list", "http://user:pass@one.example:8080", + "127.0.0.1:3128:legacy:password", "socks5h://two.example:1080", "http://user:pass@one.example:8080", "not a proxy", @@ -52,9 +53,12 @@ func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) { if err != nil { t.Fatal(err) } - if len(plain) != 2 || skipped != 2 { + if len(plain) != 3 || skipped != 2 { t.Fatalf("plain entries=%d skipped=%d", len(plain), skipped) } + if plain[1].ProxyURL != "http://legacy:password@127.0.0.1:3128" { + t.Fatalf("legacy HTTP proxy = %q", plain[1].ProxyURL) + } for _, entry := range plain { if entry.ProxyURL == "" || len(entry.Key) != 64 { t.Fatalf("unsafe parsed entry: %#v", entry) @@ -71,6 +75,31 @@ func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) { } } +func TestParseProxySubscriptionPreservesLegacyAccountPlaceholder(t *testing.T) { + content := strings.Join([]string{ + "127.0.0.1:8080:Default.{account}:pass:word", + "http://Default.{account}:pass%3Aword@127.0.0.1:8080", + "127.0.0.1:8080:user:{account}", + }, "\n") + for name, input := range map[string]string{ + "plain": content, + "base64": base64.StdEncoding.EncodeToString([]byte(content)), + } { + t.Run(name, func(t *testing.T) { + entries, skipped, err := parseProxySubscription(input) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || skipped != 2 { + t.Fatalf("entries=%d skipped=%d, want one entry, one duplicate and one invalid placeholder", len(entries), skipped) + } + if entries[0].ProxyURL != "http://Default.{account}:pass%3Aword@127.0.0.1:8080" { + t.Fatalf("legacy account proxy = %q", entries[0].ProxyURL) + } + }) + } +} + func TestParseProxySubscriptionRejectsNoUsableEntries(t *testing.T) { if _, _, err := parseProxySubscription("# only comments\nfile:///tmp/proxies\n"); err == nil { t.Fatal("invalid proxy subscription was accepted") diff --git a/backend/internal/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index df3845e7..9eadd316 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -59,12 +59,17 @@ type QualityRetryRuntime struct { HoldTimeout time.Duration MinOutputTokens int64 OnExhausted string + AutoDisable bool AccountCooldown time.Duration // IdleAccountCooldown is applied to truly empty upstream streams // (idle timeout / empty peek). Missing-thinking still uses AccountCooldown. IdleAccountCooldown time.Duration MinEncryptedBytes int EncryptedBytesPerReasoningToken int + SoftTPS float64 + HardTPS float64 + MinGenerationMS int64 + FailClosed bool } // QualityStreamSignals is the hold classifier input. Tests drive this @@ -129,6 +134,15 @@ func normalizeQualityRetry(cfg QualityRetryRuntime) QualityRetryRuntime { if cfg.EncryptedBytesPerReasoningToken <= 0 { cfg.EncryptedBytesPerReasoningToken = defaultEncryptedBytesPerReasoningToken } + if cfg.SoftTPS <= 0 { + cfg.SoftTPS = audit.DefaultDegradeSoftTPS + } + if cfg.HardTPS <= cfg.SoftTPS { + cfg.HardTPS = audit.DefaultDegradeHardTPS + } + if cfg.MinGenerationMS <= 0 { + cfg.MinGenerationMS = audit.DefaultDegradeMinGenMS + } cfg.OnExhausted = normalizeQualityExhaustionPolicy(cfg.OnExhausted) return cfg } @@ -565,10 +579,10 @@ func jsonStringEquals(raw json.RawMessage, want string) bool { return json.Unmarshal(raw, &value) == nil && strings.EqualFold(strings.TrimSpace(value), want) } -func (s *Service) applyMissingThinkingPenalty(ctx context.Context, requestID string, credential accountdomain.Credential, cooldown time.Duration) { +func (s *Service) applyMissingThinkingPenalty(ctx context.Context, requestID string, credential accountdomain.Credential, cooldown time.Duration, autoDisable bool) { writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), finalizationTimeout) defer cancel() - action, err := s.selector.markMissingThinking(writeCtx, credential, cooldown) + action, err := s.selector.markMissingThinking(writeCtx, credential, cooldown, autoDisable) if err != nil { s.logger.Error("quality_degraded_penalty_failed", "request_id", requestID, "account_id", credential.ID, "action", action, "error", err) return @@ -581,6 +595,26 @@ func (s *Service) applyMissingThinkingPenalty(ctx context.Context, requestID str } } +func (s *Service) applyOutputSpeedPenalty(ctx context.Context, record audit.Record, credential accountdomain.Credential, cfg QualityRetryRuntime, forcedEgress bool) error { + // Both explicit and TUI compaction are classified in the audit record. + // System summaries stay exempt from account quality penalties. + if record.Operation == audit.OperationCompaction { + return nil + } + if !cfg.Enabled || !cfg.AutoDisable || forcedEgress || credential.Provider != accountdomain.ProviderBuild || !record.Streaming || record.FirstTokenMS == nil || record.OutputTokens < cfg.MinOutputTokens || !auditRequestSucceeded(record.StatusCode, record.ErrorCode) { + return nil + } + class, tps, _ := audit.ClassifyOutputSpeed(record.OutputTokens, record.ReasoningTokens, *record.FirstTokenMS, record.DurationMS, cfg.SoftTPS, cfg.HardTPS, cfg.MinGenerationMS, cfg.FailClosed) + if class == "" { + return nil + } + if err := s.selector.disableAccount(ctx, credential); err != nil { + return err + } + s.logger.Info("quality_degraded_disabled", "request_id", record.RequestID, "account_id", credential.ID, "class", class, "output_tps", tps) + return nil +} + func (s *Service) recordQualityDegraded(ctx context.Context, base audit.Record, credential accountdomain.Credential, usage Usage, startedAt time.Time, trace *infraegress.Trace, provider accountdomain.Provider) { record := base record.EventID = newAuditEventID() diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index 1e58b9ab..611b7f10 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "log/slog" "math" "net/http" "path/filepath" @@ -220,6 +221,58 @@ func TestEncryptedThinkingFloorSaturates(t *testing.T) { } } +func TestAutoDisableFirstOutputSpeedHit(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "output-speed-disable.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "degraded-speed", SourceKey: "degraded-speed", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, Priority: 10, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) + service := &Service{selector: selector, logger: slog.Default()} + firstTokenMS := int64(1_000) + record := audit.Record{ + RequestID: "degraded-speed", Provider: string(accountdomain.ProviderBuild), Streaming: true, StatusCode: http.StatusOK, + OutputTokens: 120, FirstTokenMS: &firstTokenMS, DurationMS: 1_300, + } + cfg := normalizeQualityRetry(QualityRetryRuntime{Enabled: true, AutoDisable: true, MinOutputTokens: 32}) + if err := service.applyOutputSpeedPenalty(ctx, record, credential, cfg, false); err != nil { + t.Fatal(err) + } + healthy, err := accounts.Get(ctx, credential.ID) + if err != nil || !healthy.Enabled { + t.Fatalf("below-threshold hit must remain scheduled: %#v, err=%v", healthy, err) + } + record.DurationMS = 1_200 + record.Operation = audit.OperationCompaction + if err := service.applyOutputSpeedPenalty(ctx, record, credential, cfg, false); err != nil { + t.Fatal(err) + } + compacted, err := accounts.Get(ctx, credential.ID) + if err != nil || !compacted.Enabled { + t.Fatalf("compaction must remain exempt from speed penalties: %#v, err=%v", compacted, err) + } + record.Operation = audit.OperationResponses + if err := service.applyOutputSpeedPenalty(ctx, record, credential, cfg, false); err != nil { + t.Fatal(err) + } + disabled, err := accounts.Get(ctx, credential.ID) + if err != nil || disabled.Enabled { + t.Fatalf("first degraded-speed hit must disable: %#v, err=%v", disabled, err) + } +} + func TestDecideQualityRetry(t *testing.T) { t.Parallel() if got := DecideQualityRetry(QualityDeliver, 0, 2, qualityRetryFailOpen); got != QualityActionDeliver { diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index ced08daf..c55e4a09 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -1232,27 +1232,19 @@ func (s *Selector) clearQuotaConsumptionAccount(provider account.Provider, accou s.quotaMu.Unlock() } -// markMissingThinking cools an account for the first no-thinking hit and -// disables it if missing thinking appears again after that cooldown. -func (s *Selector) markMissingThinking(ctx context.Context, credential account.Credential, cooldown time.Duration) (missingThinkingPenaltyResult, error) { +// markMissingThinking disables immediately when configured; otherwise it +// cools the first no-thinking hit and disables a later hit after the cooldown. +func (s *Selector) markMissingThinking(ctx context.Context, credential account.Credential, cooldown time.Duration, autoDisable bool) (missingThinkingPenaltyResult, error) { if cooldown <= 0 { cooldown = defaultMissingThinkingCooldown } now := time.Now().UTC() inCooldown := credential.CooldownUntil != nil && now.Before(*credential.CooldownUntil) - if isMissingThinkingStrike(credential.LastError) && !inCooldown { - disabled := false - if _, err := s.accounts.UpdateMany(ctx, credential.Provider, []uint64{credential.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { + if autoDisable || (isMissingThinkingStrike(credential.LastError) && !inCooldown) { + if err := s.disableAccount(ctx, credential); err != nil { return missingThinkingPenaltyUnchanged, err } healthErr := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, credential.FailureCount, nil, lastErrorMissingThinkingDisabled, false) - s.ApplyInvalidation(repository.InvalidationEvent{ - Kind: repository.InvalidationAccountStateChanged, Provider: credential.Provider, AccountID: credential.ID, - }) - s.evictCandidate(credential.Provider, credential.ID) - if s.sticky != nil { - _ = s.sticky.DeleteByAccount(ctx, credential.ID) - } return missingThinkingPenaltyDisabled, healthErr } if inCooldown { @@ -1270,6 +1262,21 @@ func (s *Selector) markMissingThinking(ctx context.Context, credential account.C return missingThinkingPenaltyCooled, nil } +func (s *Selector) disableAccount(ctx context.Context, credential account.Credential) error { + disabled := false + if _, err := s.accounts.UpdateMany(ctx, credential.Provider, []uint64{credential.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { + return err + } + s.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountStateChanged, Provider: credential.Provider, AccountID: credential.ID, + }) + s.evictCandidate(credential.Provider, credential.ID) + if s.sticky != nil { + _ = s.sticky.DeleteByAccount(ctx, credential.ID) + } + return nil +} + func (s *Selector) MarkFailure(ctx context.Context, credential account.Credential, status int, retryAfter time.Duration) { retryAfter = s.boundUpstreamRetryAfter(retryAfter) _ = s.markFailure(ctx, credential, credential.FailureCount, credential.FailureCount+1, status, retryAfter, status == 0) diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index aeaff8cd..912393b5 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -1611,7 +1611,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) { } selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, 30*time.Second, 30*time.Minute, 500*time.Millisecond) before := time.Now().UTC() - if action, err := selector.markMissingThinking(ctx, credential, time.Hour); err != nil || action != missingThinkingPenaltyCooled { + if action, err := selector.markMissingThinking(ctx, credential, time.Hour, false); err != nil || action != missingThinkingPenaltyCooled { t.Fatalf("first penalty = (%s, %v)", action, err) } first, err := accounts.Get(ctx, credential.ID) @@ -1624,7 +1624,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) { if wait := first.CooldownUntil.Sub(before); wait < 50*time.Minute || wait > 70*time.Minute { t.Fatalf("first cooldown = %s", wait) } - if action, err := selector.markMissingThinking(ctx, first, time.Hour); err != nil || action != missingThinkingPenaltyUnchanged { + if action, err := selector.markMissingThinking(ctx, first, time.Hour, false); err != nil || action != missingThinkingPenaltyUnchanged { t.Fatalf("in-cooldown penalty = (%s, %v)", action, err) } stillCooling, err := accounts.Get(ctx, credential.ID) @@ -1636,7 +1636,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) { } expired := time.Now().UTC().Add(-time.Second) stillCooling.CooldownUntil = &expired - if action, err := selector.markMissingThinking(ctx, stillCooling, time.Hour); err != nil || action != missingThinkingPenaltyDisabled { + if action, err := selector.markMissingThinking(ctx, stillCooling, time.Hour, false); err != nil || action != missingThinkingPenaltyDisabled { t.Fatalf("second penalty = (%s, %v)", action, err) } second, err := accounts.Get(ctx, credential.ID) @@ -1657,7 +1657,7 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) { if err != nil { t.Fatal(err) } - if action, err := selector.markMissingThinking(ctx, ok, time.Hour); err != nil || action != missingThinkingPenaltyCooled { + if action, err := selector.markMissingThinking(ctx, ok, time.Hour, false); err != nil || action != missingThinkingPenaltyCooled { t.Fatalf("recovery penalty = (%s, %v)", action, err) } cooled, err := accounts.Get(ctx, ok.ID) @@ -1672,6 +1672,24 @@ func TestMarkMissingThinkingCoolsThenDisables(t *testing.T) { if kept.LastError != lastErrorMissingThinking || kept.CooldownUntil != nil || kept.FailureCount != 0 { t.Fatalf("success must keep thinking strike and clear cooldown, got %#v", kept) } + + immediate, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "auto-disable", SourceKey: "auto-disable", EncryptedAccessToken: "encrypted", Enabled: true, + AuthStatus: account.AuthStatusActive, Priority: 10, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + if action, err := selector.markMissingThinking(ctx, immediate, time.Hour, true); err != nil || action != missingThinkingPenaltyDisabled { + t.Fatalf("auto-disable penalty = (%s, %v)", action, err) + } + disabled, err := accounts.Get(ctx, immediate.ID) + if err != nil { + t.Fatal(err) + } + if disabled.Enabled || disabled.LastError != lastErrorMissingThinkingDisabled || disabled.CooldownUntil != nil { + t.Fatalf("auto-disable first strike = %#v", disabled) + } } func TestMarkFailureSoftNetworkCooldown(t *testing.T) { diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 5abd80b1..6882276a 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1128,6 +1128,11 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string } record.CreatedAt = now applyAuditEgress(&record, egressTrace, route.Provider) + if err := budget.run("quality_disable", finalizationHealthBudget, func(stageCtx context.Context) error { + return s.applyOutputSpeedPenalty(stageCtx, record, credential, holdCfg, input.ForcedEgressNodeID != 0) + }); err != nil { + s.logger.Error("quality_degraded_penalty_failed", "request_id", input.RequestID, "account_id", credential.ID, "error", err) + } if supportsStoredResponses && operation == audit.OperationResponses && responseID != "" && successful { err := budget.run("response_ownership", finalizationOwnershipBudget, func(stageCtx context.Context) error { return s.responses.Save(stageCtx, inferencedomain.ResponseOwnership{ResponseID: responseID, AccountID: accountID, ClientKeyID: input.ClientKey.ID, ModelRouteID: route.ID, Provider: route.Provider, PromptCacheKey: ownershipPromptCacheKey, ReasoningReplayKey: reasoningReplayKey, ExpiresAt: now.Add(responseOwnershipTTL), CreatedAt: now, UpdatedAt: now}) @@ -1554,7 +1559,7 @@ attemptLoop: } else if s.providers.SupportsCredentialRefresh(credential.Provider) && lastFailure.CredentialRejected { failureHandled = s.markReauthRequired(ctx, input.RequestID, credential, fmt.Sprintf("%s credential rejected", credential.Provider)) } - if lastFailure.AccountScoped && !failureHandled { + if !failureHandled && (lastFailure.AccountScoped || credential.Provider == accountdomain.ProviderBuild && response.StatusCode == http.StatusForbidden) { s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter) } else if !lastFailure.AccountScoped && response.StatusCode >= http.StatusInternalServerError { // Provider-wide 5xx responses should rotate this request and briefly @@ -1615,7 +1620,7 @@ attemptLoop: } commit := CommitQualityHold(verdict, qualityAccountAttempts-1, holdCfg.MaxAttempts, hasNextAccount, holdCfg.OnExhausted) if verdict == QualityWithhold { - s.applyMissingThinkingPenalty(ctx, input.RequestID, credential, holdCfg.AccountCooldown) + s.applyMissingThinkingPenalty(ctx, input.RequestID, credential, holdCfg.AccountCooldown, holdCfg.AutoDisable) } deferFailOpenAudit := commit.Action == QualityActionRetry && holdCfg.OnExhausted == qualityRetryFailOpen if commit.Audit && !deferFailOpenAudit { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 0fd0e8c9..f7c414e4 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -253,6 +253,9 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatalf("ownership = %#v, err = %v", ownership, err) } + service.UpdateQualityRetry(QualityRetryRuntime{ + Enabled: true, AutoDisable: true, MinOutputTokens: 32, SoftTPS: 1, HardTPS: 2, + }) compacted, err := service.CreateResponse(ctx, Input{ RequestID: "req-compact", ClientKey: clientKey, PublicModel: "grok-test", PromptCacheSeed: "claude-session", Body: []byte(`{"model":"grok-test","stream":true,"input":[{"role":"user","content":"continue"},{"type":"compaction_trigger"}]}`), Streaming: true, @@ -265,12 +268,25 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatal("first token marker is nil") } compacted.MarkFirstToken() - compacted.Finalize(Usage{}, "resp-compact", "") + time.Sleep(2 * time.Millisecond) + compacted.Finalize(Usage{Reported: true, OutputTokens: 120}, "resp-compact", "") _ = compacted.Body.Close() logs, total, err = auditRepo.List(ctx, 0, 10) if err != nil || total != 2 || logs[0].Operation != audit.OperationCompaction || !logs[0].Streaming || logs[0].FirstTokenMS == nil { t.Fatalf("compaction audit = %#v, total=%d, err=%v", logs, total, err) } + assertCompactionSpeedExempt := func(record audit.Record) { + t.Helper() + class, _, _ := audit.ClassifyOutputSpeed(record.OutputTokens, record.ReasoningTokens, *record.FirstTokenMS, record.DurationMS, 1, 2, 1000, false) + if class == "" { + t.Fatal("compaction fixture must exceed the speed threshold") + } + credential, err := accountRepo.Get(ctx, second.ID) + if err != nil || !credential.Enabled { + t.Fatalf("compaction must not disable its account: %#v, err=%v", credential, err) + } + } + assertCompactionSpeedExempt(logs[0]) if _, err := responseRepo.Get(ctx, "resp-compact", clientKey.ID, time.Now().UTC()); !errors.Is(err, repository.ErrNotFound) { t.Fatalf("compaction response ownership err = %v", err) } @@ -279,7 +295,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { // the quality hold and is labeled compaction only in the audit record, so // Provider routing and stored-response ownership must remain intact. service.UpdateQualityRetry(QualityRetryRuntime{ - Enabled: true, MaxAttempts: 2, MinOutputTokens: 32, + Enabled: true, AutoDisable: true, MaxAttempts: 2, MinOutputTokens: 32, SoftTPS: 1, HardTPS: 2, OnExhausted: qualityRetryFailClosed, HoldTimeout: time.Second, }) adapter.resetAttempts() @@ -298,7 +314,8 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatalf("TUI compaction body = %q", tuiBody) } tuiCompacted.MarkFirstToken() - tuiCompacted.Finalize(Usage{}, "resp-tui-compact", "") + time.Sleep(2 * time.Millisecond) + tuiCompacted.Finalize(Usage{Reported: true, OutputTokens: 120}, "resp-tui-compact", "") _ = tuiCompacted.Body.Close() if len(adapter.attempts) != 1 || adapter.lastOperation != string(audit.OperationResponses) { t.Fatalf("TUI compaction attempts = %#v, Provider operation = %q", adapter.attempts, adapter.lastOperation) @@ -307,6 +324,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { if err != nil || total != 3 || logs[0].Operation != audit.OperationCompaction { t.Fatalf("TUI compaction audit = %#v, total=%d, err=%v", logs, total, err) } + assertCompactionSpeedExempt(logs[0]) if ownership, err := responseRepo.Get(ctx, "resp-tui-compact", clientKey.ID, time.Now().UTC()); err != nil || ownership.AccountID != second.ID { t.Fatalf("TUI compaction ownership = %#v, err=%v", ownership, err) } @@ -1963,7 +1981,7 @@ func TestParseFreeQuotaExhaustionCurrentBuildFreeLimit(t *testing.T) { } } -func TestGatewayUnknownBuildForbiddenTraversesAllAccountsWithoutCooldown(t *testing.T) { +func TestGatewayUnknownBuildForbiddenTraversesAllAccountsWithCooldown(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "systemic-forbidden.db")) if err != nil { @@ -2033,8 +2051,8 @@ func TestGatewayUnknownBuildForbiddenTraversesAllAccountsWithoutCooldown(t *test if getErr != nil { t.Fatal(getErr) } - if observed.FailureCount != 0 || observed.CooldownUntil != nil || observed.AuthStatus != account.AuthStatusActive { - t.Fatalf("account %d was penalized after unknown 403: %#v", credential.ID, observed) + if observed.FailureCount == 0 || observed.CooldownUntil == nil || observed.AuthStatus != account.AuthStatusActive { + t.Fatalf("account %d was not cooled down after unknown Build 403: %#v", credential.ID, observed) } } logs, total, err := auditRepo.List(ctx, 0, 10) @@ -3946,8 +3964,8 @@ func TestGatewayUnknownBuildForbiddenRotatesWithoutPenalizingAccount(t *testing. if err != nil { t.Fatal(err) } - if observed.AuthStatus != account.AuthStatusActive || observed.FailureCount != 0 || observed.CooldownUntil != nil { - t.Fatalf("unknown 403 penalized first account: %#v", observed) + if observed.AuthStatus != account.AuthStatusActive || observed.FailureCount == 0 || observed.CooldownUntil == nil { + t.Fatalf("unknown Build 403 did not cool down first account: %#v", observed) } candidates, err := accountRepo.ListRoutingCandidates(ctx, account.ProviderBuild, 0, model, "") if err != nil { diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index d3bf44a9..35e3351c 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -531,6 +531,26 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), job.Quality) quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel) + // The initial creation path (selectSchedulableEligibleMediaRouteWithQuotaMode, + // called from CreateVideoJob) always scopes account selection to the + // requesting client key's AccountScope. A retry here must not silently + // widen that: falling back to the unscoped account pool would let a key + // restricted to e.g. free-tier/web-only accounts consume a premium or + // console/build-only account's quota purely because its originally + // pinned account had a transient failure. + accountScope := clientkey.AccountScope{} + if job.ClientKeyID > 0 { + key, keyErr := s.clientKeys.Get(ctx, job.ClientKeyID) + if keyErr != nil { + if parent.Err() != nil { + s.deferVideoJob(parent, job) + return + } + s.failVideoJob(ctx, job, "client_key_unavailable", keyErr, 0, nil) + return + } + accountScope = key.AccountScope() + } attemptPolicy := s.videoAttemptPolicy() excluded := make(map[uint64]bool) forbiddenEgressRetried := make(map[uint64]bool) @@ -564,7 +584,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } if lease == nil { if selection == nil { - selection, err = s.selector.beginSelectionSession(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false) + selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, accountScope) } if err == nil { lease, err = selection.Acquire(ctx, excluded, false) diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index 5658131c..bde71cdc 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -900,3 +900,130 @@ func TestVideoWebForbiddenRetriesPinnedAccountOnceThenFailsOver(t *testing.T) { t.Fatalf("unclassified failed job = %#v", stored) } } + +// The initial creation path (CreateVideoJob) always scopes account selection +// to the requesting client key's AccountScope. This confirms the retry path +// inside runVideoJob does not silently widen that scope when the originally +// pinned account fails: a key restricted to Super-tier accounts must never +// fail over to a Free-tier account, even though one is available in the pool. +func TestVideoRetryDoesNotEscapeClientKeyAccountScope(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "video-retry-scope.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + mediaRepo := relational.NewMediaJobRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + key, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "video-scope-test", Prefix: "video-scope-test", SecretHash: strings.Repeat("b", 64), + EncryptedSecret: "encrypted", Enabled: true, RPMLimit: 60, MaxConcurrent: 4, + // Restricted to Super-tier Web accounts only. + ProviderScope: clientkey.ProviderScopeWeb, TierScope: clientkey.TierScopeSuper, + }) + if err != nil { + t.Fatal(err) + } + createAccount := func(name string, tier account.WebTier, priority int) account.Credential { + credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: tier, + Name: name, SourceKey: name, EncryptedAccessToken: name + "-token", ExpiresAt: time.Now().Add(time.Hour), + Enabled: true, AuthStatus: account.AuthStatusActive, Priority: priority, MaxConcurrent: 1, + }) + if createErr != nil { + t.Fatal(createErr) + } + return credential + } + // pinned is the Super-tier account the job was originally created against + // (in scope); outOfScope is a Free-tier account that must never be used + // for this key, even as a failover target. + pinned := createAccount("pinned-super", account.WebTierSuper, 200) + outOfScope := createAccount("free-out-of-scope", account.WebTierBasic, 100) + if err := modelRepo.UpsertDiscovered(ctx, account.ProviderWeb, []string{"grok-imagine-video"}); err != nil { + t.Fatal(err) + } + for _, accountID := range []uint64{pinned.ID, outOfScope.ID} { + if err := modelRepo.ReplaceAccountCapabilities(ctx, accountID, []string{"grok-imagine-video"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } + route, err := modelRepo.GetByProviderUpstream(ctx, account.ProviderWeb, "grok-imagine-video") + if err != nil { + t.Fatal(err) + } + + // The pinned account always fails (forbidden), forcing the retry path to + // look for a replacement. Without the fix, that replacement search ignores + // the client key's scope entirely and would pick the Free-tier account. + adapter := &videoCreateFailoverAdapter{ + failures: map[uint64]int{pinned.ID: 999}, + status: http.StatusForbidden, + } + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, selector, nil, 3) + service.ConfigureMedia(mediaRepo, 1) + service.UpdateVideoMaxAttempts(3) + + now := time.Now().UTC() + job := media.Job{ + ID: "video_scope_retry", RequestID: "request-video-scope-retry", ClientKeyID: key.ID, ClientKeyName: key.Name, + AccountID: pinned.ID, AccountName: pinned.Name, Provider: string(account.ProviderWeb), + Model: route.PublicID, ModelRouteID: route.ID, UpstreamModel: route.UpstreamModel, + Operation: provider.VideoOperationGenerate, Prompt: "test", Seconds: 5, Quality: "720p", + Status: media.StatusInProgress, InputJSON: `{}`, CreatedAt: now, UpdatedAt: now, + } + t.Run("worker shutdown during key lookup preserves recovery", func(t *testing.T) { + shutdownJob := job + shutdownJob.ID = "video_scope_worker_shutdown" + shutdownJob.RequestID = "request-video-scope-worker-shutdown" + if err := mediaRepo.CreateMediaJob(ctx, shutdownJob); err != nil { + t.Fatal(err) + } + workerCtx, stopWorker := context.WithCancel(ctx) + stopWorker() + service.runVideoJob(workerCtx, shutdownJob, route) + + stored, err := mediaRepo.GetMediaJob(ctx, shutdownJob.ID, key.ID) + if err != nil { + t.Fatal(err) + } + if stored.Status != media.StatusInProgress || stored.LeaseUntil == nil || !stored.LeaseUntil.After(time.Now().UTC()) { + t.Fatalf("job must remain eligible for recovery after worker shutdown, got %#v", stored) + } + if stored.ErrorCode != "" || stored.ErrorMessage != "" || stored.CompletedAt != nil || stored.UsageRecordedAt != nil { + t.Fatalf("worker shutdown must not finalize the job, got %#v", stored) + } + if attempts := adapter.Attempts(); len(attempts) != 0 { + t.Fatalf("worker shutdown must not invoke the upstream, got attempts %#v", attempts) + } + }) + + if err := mediaRepo.CreateMediaJob(ctx, job); err != nil { + t.Fatal(err) + } + service.runVideoJob(ctx, job, route) + + for _, attemptedAccountID := range adapter.Attempts() { + if attemptedAccountID == outOfScope.ID { + t.Fatalf("out-of-scope Free-tier account %d was used for a key scoped to Super tier only", outOfScope.ID) + } + } + stored, err := mediaRepo.GetMediaJob(ctx, job.ID, job.ClientKeyID) + if err != nil { + t.Fatal(err) + } + if stored.Status != media.StatusFailed { + t.Fatalf("expected the job to fail rather than complete via an out-of-scope account, got %#v", stored) + } +} diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 03b4b3a1..0c0f51aa 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -377,8 +377,12 @@ func (s *Service) validateBoundAccounts(ctx context.Context, providerValue accou return result, nil } values, _, err := s.accounts.List(ctx, repository.AccountListQuery{ - Page: repository.PageQuery{Offset: 0, Limit: 1000}, - Filter: repository.AccountListFilter{Provider: string(providerValue)}, + Page: repository.PageQuery{Offset: 0, Limit: len(result)}, + Filter: repository.AccountListFilter{ + Provider: string(providerValue), + RestrictIDs: true, + AccountIDs: result, + }, }) if err != nil { return nil, err diff --git a/backend/internal/application/model/service_test.go b/backend/internal/application/model/service_test.go index 075c7e2a..2551c60b 100644 --- a/backend/internal/application/model/service_test.go +++ b/backend/internal/application/model/service_test.go @@ -111,6 +111,57 @@ func TestNormalizeBatchIDsAllowsGroupedRouteExpansion(t *testing.T) { } } +func TestValidateBoundAccountsSupportsAccountsFilteredByIDs(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-bound-accounts.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + modelRepo := relational.NewModelRepository(database) + accountRepo := relational.NewAccountRepository(database) + registry := provider.NewRegistry(&modelRouteAdapter{modelCapabilityAdapter: &modelCapabilityAdapter{}}) + service := NewService(modelRepo, accountRepo, nil, registry) + + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + + targetAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, + Name: "target-account", + SourceKey: "target-account", + EncryptedAccessToken: encrypted, + ExpiresAt: time.Now().Add(time.Hour), + AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + + bound, err := service.validateBoundAccounts(ctx, account.ProviderBuild, []uint64{targetAccount.ID}) + if err != nil { + t.Fatalf("validateBoundAccounts failed: %v", err) + } + if len(bound) != 1 || bound[0] != targetAccount.ID { + t.Fatalf("bound accounts = %v, want [%d]", bound, targetAccount.ID) + } + + _, err = service.validateBoundAccounts(ctx, account.ProviderWeb, []uint64{targetAccount.ID}) + if err == nil { + t.Fatal("expected error for mismatched provider, got nil") + } +} + + func TestSyncAggregatesCapabilitiesFromAllAccounts(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-sync.db")) diff --git a/backend/internal/application/settings/service.go b/backend/internal/application/settings/service.go index 0558c4fd..edca51e4 100644 --- a/backend/internal/application/settings/service.go +++ b/backend/internal/application/settings/service.go @@ -137,8 +137,9 @@ type ClientKeyDefaultsConfig struct { // AccountsConfig 是管理接口使用的账号池维护策略输入。 type AccountsConfig struct { - MarkBuildForbiddenReauth bool - BuildForbiddenReauthCodes []string + AutoDisableDegradedAccounts bool + MarkBuildForbiddenReauth bool + BuildForbiddenReauthCodes []string // ExcludeBuildBotFlaggedFromScheduling drops bot-risk Build accounts from scheduling only. ExcludeBuildBotFlaggedFromScheduling bool AutoCleanReauthEnabled bool @@ -151,6 +152,8 @@ type AccountsConfig struct { BuildForbiddenReauthCodesProvided bool // ExcludeBuildBotFlaggedFromSchedulingProvided preserves the value when an older management client omits the field. ExcludeBuildBotFlaggedFromSchedulingProvided bool + // AutoDisableDegradedAccountsProvided preserves config.yaml when an older management client omits the field. + AutoDisableDegradedAccountsProvided bool } // EditableConfig 聚合管理端允许修改的运行参数。 @@ -439,12 +442,16 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C base.Accounts.BuildForbiddenReauthCodes = append([]string(nil), value.Accounts.BuildForbiddenReauthCodes...) } base.Accounts.ExcludeBuildBotFlaggedFromScheduling = value.Accounts.ExcludeBuildBotFlaggedFromScheduling + if value.Accounts.AutoDisableDegradedAccounts != nil { + base.QualityGuard.RequestRetry.AutoDisable = *value.Accounts.AutoDisableDegradedAccounts + } return base } func toDomainConfig(value config.Config) settingsdomain.Config { randomDelay := value.Batch.RandomDelay.Value() accountIsolatedConnections := value.Routing.AccountIsolatedConnections + autoDisableDegradedAccounts := value.QualityGuard.RequestRetry.AutoDisable return settingsdomain.Config{ Server: settingsdomain.ServerConfig{MaxConcurrentRequests: value.Server.MaxConcurrentRequests}, ProviderBuild: settingsdomain.ProviderBuildConfig{ @@ -502,6 +509,7 @@ func toDomainConfig(value config.Config) settingsdomain.Config { RPMLimit: value.ClientKeyDefaults.RPMLimit, MaxConcurrent: value.ClientKeyDefaults.MaxConcurrent, }, Accounts: settingsdomain.AccountsConfig{ + AutoDisableDegradedAccounts: &autoDisableDegradedAccounts, MarkBuildForbiddenReauth: value.Accounts.MarkBuildForbiddenReauth, BuildForbiddenReauthCodes: append([]string(nil), value.Accounts.BuildForbiddenReauthCodes...), ExcludeBuildBotFlaggedFromScheduling: value.Accounts.ExcludeBuildBotFlaggedFromScheduling, @@ -600,6 +608,9 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, next.ClientKeyDefaults.RPMLimit = input.ClientKeyDefaults.RPMLimit next.ClientKeyDefaults.MaxConcurrent = input.ClientKeyDefaults.MaxConcurrent if input.AccountsProvided { + if input.Accounts.AutoDisableDegradedAccountsProvided { + next.QualityGuard.RequestRetry.AutoDisable = input.Accounts.AutoDisableDegradedAccounts + } if input.Accounts.MarkBuildForbiddenReauthProvided { next.Accounts.MarkBuildForbiddenReauth = input.Accounts.MarkBuildForbiddenReauth } @@ -740,6 +751,8 @@ func toEditable(cfg config.Config) EditableConfig { }, ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: cfg.ClientKeyDefaults.RPMLimit, MaxConcurrent: cfg.ClientKeyDefaults.MaxConcurrent}, Accounts: AccountsConfig{ + AutoDisableDegradedAccounts: cfg.QualityGuard.RequestRetry.AutoDisable, + AutoDisableDegradedAccountsProvided: true, MarkBuildForbiddenReauth: cfg.Accounts.MarkBuildForbiddenReauth, BuildForbiddenReauthCodes: append([]string(nil), cfg.Accounts.BuildForbiddenReauthCodes...), ExcludeBuildBotFlaggedFromScheduling: cfg.Accounts.ExcludeBuildBotFlaggedFromScheduling, diff --git a/backend/internal/application/settings/service_test.go b/backend/internal/application/settings/service_test.go index ca61c972..3036e957 100644 --- a/backend/internal/application/settings/service_test.go +++ b/backend/internal/application/settings/service_test.go @@ -835,6 +835,50 @@ func TestUpdateAccountsAutoCleanRoundTrip(t *testing.T) { } } +func TestUpdateAutoDisableDegradedAccountsRoundTrip(t *testing.T) { + cfg := testConfig(t) + cfg.QualityGuard.RequestRetry.AutoDisable = false + repo := &runtimeSettingsRepositoryStub{} + var applied config.Config + service := NewService(cfg, time.Time{}, 0, repo, nil, func(next config.Config) { applied = next }) + input := service.Get().Config + input.Accounts.AutoDisableDegradedAccounts = true + input.Accounts.AutoDisableDegradedAccountsProvided = true + + snapshot, err := service.Update(context.Background(), 0, input) + if err != nil { + t.Fatal(err) + } + if !applied.QualityGuard.RequestRetry.AutoDisable || !snapshot.Config.Accounts.AutoDisableDegradedAccounts { + t.Fatalf("auto-disable switch was not applied: applied=%v snapshot=%#v", applied.QualityGuard.RequestRetry.AutoDisable, snapshot.Config.Accounts) + } + if repo.value.Accounts.AutoDisableDegradedAccounts == nil || !*repo.value.Accounts.AutoDisableDegradedAccounts { + t.Fatalf("auto-disable switch was not persisted: %#v", repo.value.Accounts) + } + reloaded, _, _, err := LoadPersisted(context.Background(), cfg, repo) + if err != nil { + t.Fatal(err) + } + if !reloaded.QualityGuard.RequestRetry.AutoDisable { + t.Fatal("persisted auto-disable switch was not restored") + } +} + +func TestLoadPersistedKeepsYAMLAutoDisableForOlderPayload(t *testing.T) { + cfg := testConfig(t) + cfg.QualityGuard.RequestRetry.AutoDisable = true + value := toDomainConfig(cfg) + value.Accounts.AutoDisableDegradedAccounts = nil + + loaded, _, _, err := LoadPersisted(context.Background(), cfg, &runtimeSettingsRepositoryStub{value: value, found: true}) + if err != nil { + t.Fatal(err) + } + if !loaded.QualityGuard.RequestRetry.AutoDisable { + t.Fatal("legacy runtime settings overrode config.yaml autoDisable") + } +} + func TestUpdateWithoutAccountsPreservesCurrentAutoCleanConfig(t *testing.T) { cfg := testConfig(t) cfg.Accounts.AutoCleanReauthEnabled = true diff --git a/backend/internal/domain/settings/settings.go b/backend/internal/domain/settings/settings.go index b56060c7..31d1654a 100644 --- a/backend/internal/domain/settings/settings.go +++ b/backend/internal/domain/settings/settings.go @@ -147,6 +147,9 @@ type ClientKeyDefaultsConfig struct { // AccountsConfig 定义账号池后台维护策略;默认全部关闭。 type AccountsConfig struct { + // AutoDisableDegradedAccounts is optional so legacy persisted settings keep + // the qualityGuard.requestRetry.autoDisable value supplied by config.yaml. + AutoDisableDegradedAccounts *bool // MarkBuildForbiddenReauth marks high-confidence Grok Build permission denials as requiring reauthorization. MarkBuildForbiddenReauth bool // BuildForbiddenReauthCodes contains exact upstream error codes that opt into account invalidation. diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index edf9dc9f..d8212bcf 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -295,6 +295,8 @@ type QualityGuardRequestRetryConfig struct { HoldTimeout Duration `yaml:"holdTimeout"` MinOutputTokens int `yaml:"minOutputTokens"` OnExhausted string `yaml:"onExhausted"` + // AutoDisable also enables request-path detection without changing Enabled. + AutoDisable bool `yaml:"autoDisable"` AccountCooldown Duration `yaml:"accountCooldown"` // IdleAccountCooldown cools an account after a truly empty upstream // stream. Independent of accountCooldown (missing-thinking). Zero uses 15m. @@ -740,6 +742,15 @@ func validateQualityGuardConfig(value QualityGuardConfig) error { if err := validateQualityGuardRequestRetry(value.RequestRetry); err != nil { return err } + // Automatic account disabling uses these thresholds without the sidecar. + if value.Enabled || value.RequestRetry.AutoDisable { + if value.SoftTPS < 1 || value.HardTPS <= value.SoftTPS || value.HardTPS > 10000 { + return errors.New("qualityGuard TPS 阈值无效") + } + if value.MinimumGenerationWindow.Value() < time.Millisecond || value.MinimumGenerationWindow.Value() > 2*time.Minute { + return errors.New("qualityGuard.minimumGenerationWindow 必须在 1 毫秒到 2 分钟之间") + } + } if !value.Enabled { return nil } @@ -758,9 +769,6 @@ func validateQualityGuardConfig(value QualityGuardConfig) error { if value.PassivePollInterval.Value() < time.Second || value.PassivePollInterval.Value() > 5*time.Minute { return errors.New("qualityGuard.passivePollInterval 必须在 1 秒到 5 分钟之间") } - if value.SoftTPS < 1 || value.HardTPS <= value.SoftTPS || value.HardTPS > 10000 { - return errors.New("qualityGuard TPS 阈值无效") - } if value.ConsecutiveSoft < 1 || value.ConsecutiveSoft > 20 || value.ConsecutiveErrors < 1 || value.ConsecutiveErrors > 20 { return errors.New("qualityGuard 连续异常次数必须在 1 到 20 之间") } @@ -773,9 +781,6 @@ func validateQualityGuardConfig(value QualityGuardConfig) error { if value.MaxOutputTokens < 32 || value.MaxOutputTokens > 4096 { return errors.New("qualityGuard.maxOutputTokens 必须在 32 到 4096 之间") } - if value.MinimumGenerationWindow.Value() < time.Millisecond || value.MinimumGenerationWindow.Value() > 2*time.Minute { - return errors.New("qualityGuard.minimumGenerationWindow 必须在 1 毫秒到 2 分钟之间") - } if value.RotationTimeout.Value() < 5*time.Second || value.RotationTimeout.Value() > 5*time.Minute { return errors.New("qualityGuard.rotationTimeout 必须在 5 秒到 5 分钟之间") } @@ -792,7 +797,7 @@ func validateQualityGuardConfig(value QualityGuardConfig) error { } func validateQualityGuardRequestRetry(value QualityGuardRequestRetryConfig) error { - if !value.Enabled { + if !value.Enabled && !value.AutoDisable { return nil } if value.MaxAttempts != 0 && (value.MaxAttempts < 1 || value.MaxAttempts > 6) { diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index cd2ba074..a14b9b99 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -203,6 +203,9 @@ qualityGuard: nodeIDs: [2, 9] minimumHealthyNodes: 1 activeInterval: 45m + requestRetry: + enabled: true + autoDisable: true `) if err := os.WriteFile(path, data, 0o600); err != nil { t.Fatal(err) @@ -215,7 +218,7 @@ qualityGuard: t.Fatalf("qualityGuard = %#v", value.QualityGuard) } retry := value.QualityGuard.RequestRetry - if retry.Enabled || retry.MaxAttempts != 6 || retry.HoldTimeout.Value() != 30*time.Second || retry.MinOutputTokens != 8 || retry.OnExhausted != "fail_closed" || retry.AccountCooldown.Value() != 12*time.Hour { + if !retry.Enabled || !retry.AutoDisable || retry.MaxAttempts != 6 || retry.HoldTimeout.Value() != 30*time.Second || retry.MinOutputTokens != 8 || retry.OnExhausted != "fail_closed" || retry.AccountCooldown.Value() != 12*time.Hour || retry.IdleAccountCooldown.Value() != 15*time.Minute { t.Fatalf("loaded requestRetry defaults = %#v", retry) } } @@ -223,11 +226,39 @@ qualityGuard: func TestDefaultQualityGuardRequestRetryContract(t *testing.T) { t.Parallel() got := defaultConfig().QualityGuard.RequestRetry - if got.Enabled || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute || got.MinEncryptedBytes != 256 || got.EncryptedBytesPerReasoningToken != 4 { + if got.Enabled || got.AutoDisable || got.MaxAttempts != 6 || got.HoldTimeout.Value() != 30*time.Second || got.MinOutputTokens != 8 || got.OnExhausted != "fail_closed" || got.AccountCooldown.Value() != 12*time.Hour || got.IdleAccountCooldown.Value() != 15*time.Minute || got.MinEncryptedBytes != 256 || got.EncryptedBytesPerReasoningToken != 4 { t.Fatalf("requestRetry defaults = %#v", got) } } +func TestAutoDisableValidatesRequestPolicyWithoutSidecar(t *testing.T) { + t.Parallel() + base := defaultConfig().QualityGuard + base.RequestRetry.AutoDisable = true + if err := validateQualityGuardConfig(base); err != nil { + t.Fatalf("auto-disable with default policy: %v", err) + } + for _, test := range []struct { + name string + change func(*QualityGuardConfig) + }{ + {"retry limit", func(c *QualityGuardConfig) { c.RequestRetry.MaxAttempts = 7 }}, + {"hold timeout", func(c *QualityGuardConfig) { c.RequestRetry.HoldTimeout = Duration(time.Minute) }}, + {"output floor", func(c *QualityGuardConfig) { c.RequestRetry.MinOutputTokens = 1 }}, + {"soft TPS", func(c *QualityGuardConfig) { c.SoftTPS = 0 }}, + {"hard TPS", func(c *QualityGuardConfig) { c.HardTPS = c.SoftTPS }}, + {"generation window", func(c *QualityGuardConfig) { c.MinimumGenerationWindow = 0 }}, + } { + t.Run(test.name, func(t *testing.T) { + cfg := base + test.change(&cfg) + if err := validateQualityGuardConfig(cfg); err == nil { + t.Fatal("invalid active request-path policy must be rejected even when the sidecar is disabled") + } + }) + } +} + func TestQualityGuardRequestRetryAccountCooldownBounds(t *testing.T) { t.Parallel() for _, test := range []struct { diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index 4905e356..77125a00 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -65,6 +65,7 @@ type imagineSlot struct { } type imagineCollector struct { + requestID string slots map[string]*imagineSlot terminalCount int } @@ -88,8 +89,12 @@ func imageGenerationUserError(message, param, code string) (*provider.Response, }}), nil } -func newImagineCollector() *imagineCollector { - return &imagineCollector{slots: make(map[string]*imagineSlot)} +func newImagineCollector(requestID ...string) *imagineCollector { + var reqID string + if len(requestID) > 0 { + reqID = strings.TrimSpace(requestID[0]) + } + return &imagineCollector{requestID: reqID, slots: make(map[string]*imagineSlot)} } func (c *imagineCollector) Accept(message map[string]any) { @@ -97,6 +102,17 @@ func (c *imagineCollector) Accept(message map[string]any) { if typeName != "image" && typeName != "json" { return } + if c.requestID != "" { + msgReqID := firstString(message, "requestId", "request_id", "req_id", "reqId") + if msgReqID == "" { + if item, ok := message["item"].(map[string]any); ok { + msgReqID = firstString(item, "requestId", "request_id") + } + } + if msgReqID != c.requestID { + return + } + } rawURL, _ := message["url"].(string) imageID := firstString(message, "image_id", "job_id", "id") if imageID == "" && rawURL != "" { @@ -706,7 +722,8 @@ func (a *Adapter) generateWSImageAttempt(ctx context.Context, request provider.I a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) return nil, err } - if err := connection.WriteJSON(imagineRequestMessage(newWebID("img"), request.Prompt, ratio, cfg.AllowNSFW, modelConfig.Pro, modelConfig.ExpectedCount)); err != nil { + reqID := newWebID("img") + if err := connection.WriteJSON(imagineRequestMessage(reqID, request.Prompt, ratio, cfg.AllowNSFW, modelConfig.Pro, modelConfig.ExpectedCount)); err != nil { a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) return nil, err } @@ -715,11 +732,11 @@ func (a *Adapter) generateWSImageAttempt(ctx context.Context, request provider.I streamCtx, cancel := context.WithCancel(ctx) leaseOwned = false connectionOwned = false - go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, count, request.PartialImages, modelConfig) + go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, count, request.PartialImages, modelConfig, reqID) return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil } - collector := newImagineCollector() + collector := newImagineCollector(reqID) for collector.UsableCount() < count && !collector.Done(modelConfig.ExpectedCount) { messageType, data, readErr := connection.ReadMessage() if readErr != nil { @@ -1521,7 +1538,7 @@ func (a *Adapter) imageBytes(ctx context.Context, credential account.Credential, return a.downloadImage(ctx, credential, image.URL) } -func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, count, partialImages int, modelConfig imagineModelConfig) { +func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, count, partialImages int, modelConfig imagineModelConfig, requestID ...string) { defer lease.Release() defer connection.Close() done := make(chan struct{}) @@ -1533,7 +1550,7 @@ func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter case <-done: } }() - collector := newImagineCollector() + collector := newImagineCollector(requestID...) emitted := 0 partialIndex := 0 for emitted < count { diff --git a/backend/internal/infra/provider/web/media_clearance_retry_test.go b/backend/internal/infra/provider/web/media_clearance_retry_test.go index 6b374355..4c60d55c 100644 --- a/backend/internal/infra/provider/web/media_clearance_retry_test.go +++ b/backend/internal/infra/provider/web/media_clearance_retry_test.go @@ -88,18 +88,33 @@ func TestGenerateWSImageReacquiresAfterChallengeHandshake(t *testing.T) { return } defer connection.Close() + var requestIDForResponse string for range 2 { var message map[string]any if err := connection.ReadJSON(&message); err != nil { t.Errorf("read Imagine request: %v", err) return } + if item, ok := message["item"].(map[string]any); ok { + if content, ok := item["content"].([]any); ok && len(content) > 0 { + if first, ok := content[0].(map[string]any); ok { + if requestID, ok := first["requestId"].(string); ok && requestID != "" { + // The Imagine collector binds response frames to the request ID. + requestIDForResponse = requestID + } + } + } + } + } + if requestIDForResponse == "" { + t.Error("Imagine request did not include requestId") + return } _ = connection.WriteJSON(map[string]any{ - "type": "image", "id": "image-1", "blob": "aW1hZ2U=", "percentage_complete": 100, "grid_index": 0, + "type": "image", "id": "image-1", "requestId": requestIDForResponse, "blob": "aW1hZ2U=", "percentage_complete": 100, "grid_index": 0, }) _ = connection.WriteJSON(map[string]any{ - "type": "json", "id": "image-1", "current_status": "completed", "moderated": false, "order": 0, + "type": "json", "id": "image-1", "requestId": requestIDForResponse, "current_status": "completed", "moderated": false, "order": 0, }) })) defer server.Close() diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 2627addf..c294a605 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -1786,3 +1786,73 @@ func MarshalJSONBytes(value any) []byte { data, _ := json.Marshal(value) return data } + +func TestImagineCollectorFiltersMismatchedRequestIDs(t *testing.T) { + reqID := "img_target_12345" + collector := newImagineCollector(reqID) + + // 1. Frame from another/stale request with mismatched requestId must be ignored + collector.Accept(map[string]any{ + "type": "image", + "id": "stale-image-1", + "requestId": "img_stale_99999", + "url": "https://imagine-public.x.ai/imagine-public/images/stale.jpg", + "percentage_complete": 100.0, + }) + collector.Accept(map[string]any{ + "type": "json", + "image_id": "stale-image-1", + "requestId": "img_stale_99999", + "current_status": "completed", + "moderated": false, + }) + + if collector.UsableCount() != 0 || len(collector.Images()) != 0 { + t.Fatalf("collector accepted stale image with mismatched requestId: %#v", collector.Images()) + } + + // 2. Nested item.requestId must also be matched + staleNestedCollector := newImagineCollector(reqID) + staleNestedCollector.Accept(map[string]any{ + "type": "image", + "id": "stale-nested-1", + "item": map[string]any{ + "requestId": "img_stale_88888", + }, + "url": "https://imagine-public.x.ai/imagine-public/images/stale2.jpg", + "percentage_complete": 100.0, + }) + staleNestedCollector.Accept(map[string]any{ + "type": "json", + "image_id": "stale-nested-1", + "item": map[string]any{"requestId": "img_stale_88888"}, + "current_status": "completed", + "moderated": false, + }) + if len(staleNestedCollector.Images()) != 0 || staleNestedCollector.Done(1) { + t.Fatalf("collector accepted nested stale image") + } + + // 3. Matching target request frames are accepted normally + collector.Accept(map[string]any{ + "type": "image", + "id": "target-image-1", + "requestId": reqID, + "url": "https://imagine-public.x.ai/imagine-public/images/target.jpg", + "percentage_complete": 100.0, + }) + collector.Accept(map[string]any{ + "type": "json", + "image_id": "target-image-1", + "requestId": reqID, + "current_status": "completed", + "moderated": false, + }) + + if collector.UsableCount() != 1 || len(collector.Images()) != 1 { + t.Fatalf("collector failed to accept matching target image: %#v", collector.Images()) + } + if collector.Images()[0].ID != "target-image-1" { + t.Fatalf("expected target-image-1, got %s", collector.Images()[0].ID) + } +} diff --git a/backend/internal/infra/provider/web/sso_build.go b/backend/internal/infra/provider/web/sso_build.go index f6f443bb..1dc6fb20 100644 --- a/backend/internal/infra/provider/web/sso_build.go +++ b/backend/internal/infra/provider/web/sso_build.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "net/url" + "regexp" "sort" "strconv" "strings" @@ -19,6 +20,7 @@ import ( infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/security" + "golang.org/x/net/html" ) const ( @@ -62,7 +64,7 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C defer cancel() flow := &ssoBuildFlow{ client: lease, userAgent: lease.UserAgent, - cookies: map[string]string{"sso": token, "sso-rw": token}, + cookies: ssoBuildCookies(token, lease.CFCookies), } seed, err := flow.convert(requestCtx, credential) if err != nil { @@ -101,9 +103,11 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre device.ExpiresIn = 1800 } - // verify/approve 已在 auth.x.ai 完成状态变更。重定向目标只是结果页, - // 因此不访问 accounts.x.ai,直接解析首个 3xx Location 的状态路径。 - status, finalURL, _, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false) + // verify → consent。xAI 2025-09 起在 device 授权流程加入防伪令牌:consent 页面内嵌一个 + // 一次性 consent_token(ES256 JWT,typ=consent+jwt),approve 必须回传它,否则返回 + // 403「Request could not be verified」。因此这里不能只看 3xx 的状态路径,还要取到 + // consent 页面来解析该令牌。 + status, finalURL, verifyBody, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false) if err != nil { return provider.CredentialSeed{}, err } @@ -119,9 +123,37 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre } return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败") } - status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoApproveURL, url.Values{ + consentPageURL := finalURL + + // verify 以 3xx 跳转到 consent 时响应体为空,需要 GET consent 页面本身来解析 consent_token。 + consentToken := extractConsentToken(verifyBody) + if consentToken == "" { + consentStatus, _, consentBody, cerr := f.do(ctx, http.MethodGet, consentPageURL, nil) + if cerr != nil { + return provider.CredentialSeed{}, fmt.Errorf("获取 xAI consent 页面失败: %w", cerr) + } + if consentStatus < 200 || consentStatus >= 300 { + return provider.CredentialSeed{}, fmt.Errorf("获取 xAI consent 页面失败: %w", conversionHTTPError{status: consentStatus}) + } + consentToken = extractConsentToken(consentBody) + } + if !consentTokenMatchesDevice(consentToken, device.DeviceCode) { + return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败:未获取 consent_token") + } + + status, finalURL, _, err = f.doWithFollowHeaders(ctx, http.MethodPost, ssoApproveURL, url.Values{ "user_code": {device.UserCode}, "action": {"allow"}, "principal_type": {"User"}, "principal_id": {""}, - }, false) + "consent_token": {consentToken}, + }, false, map[string]string{ + "Origin": "https://accounts.x.ai", + "Referer": consentPageURL, + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Sec-Fetch-Dest": "document", + "Sec-Fetch-Mode": "navigate", + "Sec-Fetch-Site": "same-site", + "Sec-Fetch-User": "?1", + "Upgrade-Insecure-Requests": "1", + }) if err != nil { return provider.CredentialSeed{}, err } @@ -223,6 +255,10 @@ func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url // doWithFollow 在 follow=false 时遇到 3xx 直接返回状态码与解析后的 Location 作为 finalURL, // 用于重定向目标域会被 Cloudflare 拦截(accounts.x.ai)的请求。 func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string, form url.Values, follow bool) (int, string, []byte, error) { + return f.doWithFollowHeaders(ctx, method, endpoint, form, follow, nil) +} + +func (f *ssoBuildFlow) doWithFollowHeaders(ctx context.Context, method, endpoint string, form url.Values, follow bool, extraHeaders map[string]string) (int, string, []byte, error) { if !safeXAIURL(endpoint) { return 0, "", nil, fmt.Errorf("xAI OAuth URL 不安全") } @@ -242,6 +278,17 @@ func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") request.Header.Set("User-Agent", f.userAgent) request.Header.Set("Cookie", f.cookieHeader()) + if currentMethod == http.MethodGet && ssoDeviceRedirectState(currentURL) == "consent" { + request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") + request.Header.Set("Referer", "https://auth.x.ai/") + request.Header.Set("Sec-Fetch-Dest", "document") + request.Header.Set("Sec-Fetch-Mode", "navigate") + request.Header.Set("Sec-Fetch-Site", "same-site") + request.Header.Set("Upgrade-Insecure-Requests", "1") + } + for key, value := range extraHeaders { + request.Header.Set(key, value) + } if currentForm != nil { request.Header.Set("Content-Type", "application/x-www-form-urlencoded") } @@ -275,7 +322,7 @@ func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string return response.StatusCode, currentURL, data, fmt.Errorf("xAI OAuth 重定向到非受信域名") } if !follow { - return response.StatusCode, currentURL, nil, nil + return response.StatusCode, currentURL, data, nil } if response.StatusCode == http.StatusSeeOther || ((response.StatusCode == http.StatusMovedPermanently || response.StatusCode == http.StatusFound) && currentMethod != http.MethodGet && currentMethod != http.MethodHead) { currentMethod = http.MethodGet @@ -331,6 +378,17 @@ func (f *ssoBuildFlow) cookieHeader() string { return strings.Join(parts, "; ") } +func ssoBuildCookies(token, cloudflareCookies string) map[string]string { + cookies := make(map[string]string) + for _, part := range strings.Split(infraegress.BuildSSOCookie(token, cloudflareCookies), ";") { + name, value, ok := strings.Cut(strings.TrimSpace(part), "=") + if ok && name != "" { + cookies[name] = value + } + } + return cookies +} + func safeXAIURL(raw string) bool { parsed, err := url.Parse(raw) if err != nil || parsed.Scheme != "https" || parsed.User != nil || parsed.Hostname() == "" { @@ -351,6 +409,53 @@ func normalizeSSOToken(value string) string { return strings.NewReplacer("\r", "", "\n", "", "\x00", "").Replace(value) } +var ( + consentTokenJSONRe = regexp.MustCompile(`(?i)\\?["']?(?:consentToken|consent_token)\\?["']?\s*[:=]\s*\\?["'](eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\\?["']`) +) + +// extractConsentToken 从 consent 页面 HTML 中解析一次性 consent_token: +// 优先取表单隐藏字段 name="consent_token",回退到 RSC/JSON 里的 consentToken。 +func extractConsentToken(body []byte) string { + tokenizer := html.NewTokenizer(strings.NewReader(string(body))) + for { + tokenType := tokenizer.Next() + if tokenType == html.ErrorToken { + break + } + if tokenType != html.StartTagToken { + continue + } + token := tokenizer.Token() + if !strings.EqualFold(token.Data, "input") { + continue + } + var name, value string + for _, attribute := range token.Attr { + switch strings.ToLower(attribute.Key) { + case "name": + name = attribute.Val + case "value": + value = attribute.Val + } + } + if strings.EqualFold(name, "consent_token") && value != "" { + return value + } + } + if m := consentTokenJSONRe.FindSubmatch(body); m != nil { + return string(m[1]) + } + return "" +} + +func consentTokenMatchesDevice(token, deviceCode string) bool { + parts := strings.Split(token, ".") + if len(parts) != 3 || parts[0] == "" || parts[2] == "" { + return false + } + return claimString(decodeBuildClaims(token), "dc") == deviceCode && deviceCode != "" +} + func decodeBuildClaims(token string) map[string]any { parts := strings.Split(token, ".") if len(parts) < 2 { diff --git a/backend/internal/infra/provider/web/sso_build_test.go b/backend/internal/infra/provider/web/sso_build_test.go index 7bcd2615..416f4a60 100644 --- a/backend/internal/infra/provider/web/sso_build_test.go +++ b/backend/internal/infra/provider/web/sso_build_test.go @@ -69,36 +69,78 @@ func TestSSOBuildFlowMapsDeadSSOToUnauthorized(t *testing.T) { } } -func TestSSOBuildFlowUsesAuthEndpointsOnly(t *testing.T) { +func TestSSOBuildFlowConvertsEndToEndWithConsentToken(t *testing.T) { client := &scriptedSSOClient{responses: []*http.Response{ {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader( `{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))}, {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))}, + {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader( + `
`))}, {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/done"}}, Body: io.NopCloser(strings.NewReader(""))}, {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader( `{"access_token":"access","refresh_token":"refresh","expires_in":3600}`))}, }} - flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live", "sso-rw": "live"}} + flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: ssoBuildCookies("live", "cf_clearance=clearance")} seed, err := flow.convert(context.Background(), fakeCredential()) if err != nil { t.Fatal(err) } - if seed.AccessToken != "access" || seed.RefreshToken != "refresh" || len(client.requests) != 4 { + if seed.AccessToken != "access" || seed.RefreshToken != "refresh" || len(client.requests) != 5 { t.Fatalf("seed=%#v requests=%d", seed, len(client.requests)) } - for _, request := range client.requests { - if request.URL.Hostname() != "auth.x.ai" { + hosts := []string{"auth.x.ai", "auth.x.ai", "accounts.x.ai", "auth.x.ai", "auth.x.ai"} + for index, request := range client.requests { + if request.URL.Hostname() != hosts[index] { t.Fatalf("device flow visited unexpected host %q", request.URL.Hostname()) } } + if client.requests[3].URL.RawQuery != "" { + t.Fatalf("approve must post a form body, got query %q", client.requests[3].URL.RawQuery) + } + approve := client.requests[3] + if approve.Method != http.MethodPost { + t.Fatalf("approve method = %q, want POST", approve.Method) + } + wantHeaders := map[string]string{ + "Origin": "https://accounts.x.ai", + "Referer": "https://accounts.x.ai/oauth2/device/consent", + "Sec-Fetch-Dest": "document", + "Sec-Fetch-Mode": "navigate", + "Sec-Fetch-Site": "same-site", + "Sec-Fetch-User": "?1", + "Upgrade-Insecure-Requests": "1", + } + for name, want := range wantHeaders { + if got := approve.Header.Get(name); got != want { + t.Errorf("approve %s = %q, want %q", name, got, want) + } + } + consentCookie := client.requests[2].Header.Get("Cookie") + if !strings.Contains(consentCookie, "sso=live") || !strings.Contains(consentCookie, "cf_clearance=clearance") { + t.Fatalf("consent request cookies = %q", consentCookie) + } + if client.requests[2].Header.Get("Sec-Fetch-Mode") != "navigate" || client.requests[2].Header.Get("Sec-Fetch-Dest") != "document" { + t.Fatalf("consent request is missing navigation headers: %#v", client.requests[2].Header) + } + body, err := io.ReadAll(client.requests[3].Body) + if err != nil { + t.Fatal(err) + } + approveForm, err := url.ParseQuery(string(body)) + if err != nil { + t.Fatal(err) + } + if approveForm.Get("consent_token") != "eyJhbGciOiJFUzI1NiJ9.eyJkYyI6ImRjIn0.sig" { + t.Fatalf("approve form missing consent_token: %q", approveForm.Get("consent_token")) + } } func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) { client := &scriptedSSOClient{responses: []*http.Response{ - {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))}, + {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader("verify response"))}, }} flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live"}} - status, finalURL, _, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false) + status, finalURL, body, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false) if err != nil { t.Fatal(err) } @@ -111,6 +153,9 @@ func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) { if len(client.requests) != 1 { t.Fatalf("redirect must not be followed, requests = %d", len(client.requests)) } + if string(body) != "verify response" { + t.Fatalf("redirect response body = %q", body) + } } func TestSSODeviceRedirectStateRequiresExactTrustedPath(t *testing.T) { @@ -131,6 +176,47 @@ func TestSSODeviceRedirectStateRequiresExactTrustedPath(t *testing.T) { func fakeCredential() accountdomain.Credential { return accountdomain.Credential{} } +func TestExtractConsentToken(t *testing.T) { + form := []byte(``) + if token := extractConsentToken(form); token != "eyJhbGciOiJFUzI1NiJ9.a.b" { + t.Fatalf("form token = %q", token) + } + jsonPayload := []byte(`{"consentToken":"eyJhbGciOiJFUzI1NiJ9.c.d","other":1}`) + if token := extractConsentToken(jsonPayload); token != "eyJhbGciOiJFUzI1NiJ9.c.d" { + t.Fatalf("json token = %q", token) + } + rscPayload := []byte(`{\"consentToken\":\"eyJhbGciOiJFUzI1NiJ9.e.f\"}`) + if token := extractConsentToken(rscPayload); token != "eyJhbGciOiJFUzI1NiJ9.e.f" { + t.Fatalf("escaped RSC token = %q", token) + } + if token := extractConsentToken([]byte("nothing")); token != "" { + t.Fatalf("unexpected token = %q", token) + } +} + +func TestConsentTokenMustMatchDeviceCode(t *testing.T) { + token := "eyJhbGciOiJFUzI1NiJ9.eyJkYyI6ImRjIn0.sig" + if !consentTokenMatchesDevice(token, "dc") { + t.Fatal("consent token for current device code was rejected") + } + if consentTokenMatchesDevice(token, "other-device") { + t.Fatal("consent token for a different device code was accepted") + } + if consentTokenMatchesDevice("not-a-jwt", "dc") { + t.Fatal("malformed consent token was accepted") + } +} + +func TestSSOBuildCookiesCarrySanitizedCloudflareClearance(t *testing.T) { + cookies := ssoBuildCookies("sso-token", "cf_clearance=clearance; __cf_bm=bm; sso=attacker") + if cookies["sso"] != "sso-token" || cookies["sso-rw"] != "sso-token" { + t.Fatalf("SSO cookies = %#v", cookies) + } + if cookies["cf_clearance"] != "clearance" || cookies["__cf_bm"] != "bm" { + t.Fatalf("Cloudflare cookies = %#v", cookies) + } +} + func TestSSOBuildConversionSanitizesTokenAndURLs(t *testing.T) { if token := normalizeSSOToken("sso=token-value; x-userid=drop"); token != "token-value" { t.Fatalf("token = %q", token) diff --git a/backend/internal/transport/http/settings/handler.go b/backend/internal/transport/http/settings/handler.go index 5ece7097..659abcd5 100644 --- a/backend/internal/transport/http/settings/handler.go +++ b/backend/internal/transport/http/settings/handler.go @@ -130,6 +130,7 @@ type clientKeyDefaultsConfigDTO struct { } type accountsConfigDTO struct { + AutoDisableDegradedAccounts *bool `json:"autoDisableDegradedAccounts,omitempty"` MarkBuildForbiddenReauth *bool `json:"markBuildForbiddenReauth,omitempty"` BuildForbiddenReauthCodes *[]string `json:"buildForbiddenReauthCodes,omitempty"` ExcludeBuildBotFlaggedFromScheduling *bool `json:"excludeBuildBotFlaggedFromScheduling,omitempty"` @@ -252,6 +253,8 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { } if value.Accounts != nil { result.Accounts = settingsapp.AccountsConfig{ + AutoDisableDegradedAccounts: boolValue(value.Accounts.AutoDisableDegradedAccounts), + AutoDisableDegradedAccountsProvided: value.Accounts.AutoDisableDegradedAccounts != nil, MarkBuildForbiddenReauth: boolValue(value.Accounts.MarkBuildForbiddenReauth), BuildForbiddenReauthCodes: stringSliceValue(value.Accounts.BuildForbiddenReauthCodes), ExcludeBuildBotFlaggedFromScheduling: boolValue(value.Accounts.ExcludeBuildBotFlaggedFromScheduling), @@ -329,6 +332,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { RPMLimit: config.ClientKeyDefaults.RPMLimit, MaxConcurrent: config.ClientKeyDefaults.MaxConcurrent, }, Accounts: &accountsConfigDTO{ + AutoDisableDegradedAccounts: boolPointer(config.Accounts.AutoDisableDegradedAccounts), MarkBuildForbiddenReauth: boolPointer(config.Accounts.MarkBuildForbiddenReauth), BuildForbiddenReauthCodes: stringSlicePointer(config.Accounts.BuildForbiddenReauthCodes), ExcludeBuildBotFlaggedFromScheduling: boolPointer(config.Accounts.ExcludeBuildBotFlaggedFromScheduling), diff --git a/backend/internal/transport/http/settings/security_test.go b/backend/internal/transport/http/settings/security_test.go index 72606d72..0c080cef 100644 --- a/backend/internal/transport/http/settings/security_test.go +++ b/backend/internal/transport/http/settings/security_test.go @@ -152,7 +152,7 @@ func TestLegacySettingsRequestPreservesBuildForbiddenCodesWhenOmitted(t *testing t.Fatal(err) } input := dto.toApplication() - if !input.AccountsProvided || !input.Accounts.MarkBuildForbiddenReauthProvided || input.Accounts.BuildForbiddenReauthCodesProvided { + if !input.AccountsProvided || !input.Accounts.MarkBuildForbiddenReauthProvided || input.Accounts.BuildForbiddenReauthCodesProvided || input.Accounts.AutoDisableDegradedAccountsProvided { t.Fatalf("legacy field presence was not preserved: %#v", input.Accounts) } } diff --git a/config.example.yaml b/config.example.yaml index 7a3ae2f4..72c2afd5 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -150,8 +150,8 @@ qualityGuard: nodeIDs: [] rotatableNodeIDs: [] # Optional request-path withhold/retry for thinking models. - # Recommended lab values are filled in; enabled stays false so stock - # installs do not intercept. Set enabled: true to turn the hold on. + # Recommended lab values are filled in; enabled and autoDisable stay false + # so stock installs do not intercept. Either switch enables detection. # Observe up to 30s for real reasoning evidence. A reasoning-item stub plus # enough visible output at the deadline is withheld (TUI dump after 30s), # not released as late ciphertext. Empty stub-only streams keep waiting. @@ -170,8 +170,12 @@ qualityGuard: holdTimeout: 30s minOutputTokens: 8 onExhausted: fail_closed # fail_open | fail_closed - # First missing-thinking hit cools the account; a later hit after the - # cooldown expires disables it. + # Immediately disable an account on its first confirmed missing-thinking + # or degraded output-speed hit (soft-TPS, hard-TPS, or buffered-burst). + # Also enables request-path detection independently of enabled above. + # When false, enabled controls the historical cooldown/second-hit policy. + # Context compaction and forced egress probes remain exempt. + autoDisable: false accountCooldown: 12h # Empty SSE / idle-timeout penalty. Independent of accountCooldown. # Single-account pools should set this lower; toggling enabled does not diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index 3881b1c0..9b7503db 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -27,6 +27,7 @@ export type SettingsConfigDTO = { audit: { bufferSize: number; batchSize: number; flushInterval: string; commitDelayMS: number; retentionDays?: number }; clientKeyDefaults: { rpmLimit: number; maxConcurrent: number }; accounts: { + autoDisableDegradedAccounts: boolean; markBuildForbiddenReauth: boolean; buildForbiddenReauthCodes: string[]; excludeBuildBotFlaggedFromScheduling: boolean; @@ -139,6 +140,7 @@ const settingsConfigValidator = hasShape({ clientKeyDefaults: hasShape({ rpmLimit: isNumber, maxConcurrent: isNumber }), // Older backends may omit accounts; withSettingsDefaults supplies a safe local default. accounts: isOptional(hasShape({ + autoDisableDegradedAccounts: isOptional(isBoolean), markBuildForbiddenReauth: isOptional(isBoolean), buildForbiddenReauthCodes: isOptional(isArrayOf(isString)), excludeBuildBotFlaggedFromScheduling: isOptional(isBoolean), @@ -149,6 +151,7 @@ const settingsConfigValidator = hasShape({ })), }); const defaultAccountsConfig = (): SettingsConfigDTO["accounts"] => ({ + autoDisableDegradedAccounts: false, markBuildForbiddenReauth: false, buildForbiddenReauthCodes: ["permission-denied"], excludeBuildBotFlaggedFromScheduling: false, @@ -188,6 +191,7 @@ function withSettingsDefaults(snapshot: SettingsSnapshotDTO): SettingsSnapshotDT }, }, accounts: { + autoDisableDegradedAccounts: accounts.autoDisableDegradedAccounts ?? false, markBuildForbiddenReauth: accounts.markBuildForbiddenReauth ?? false, buildForbiddenReauthCodes: accounts.buildForbiddenReauthCodes ?? ["permission-denied"], excludeBuildBotFlaggedFromScheduling: accounts.excludeBuildBotFlaggedFromScheduling ?? false, diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index d3481b26..6854bc2b 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -163,6 +163,7 @@ export const settingsSchema = z.object({ .refine((value) => value.batchSize <= value.bufferSize, { path: ["batchSize"] }), clientKeyDefaults: z.object({ rpmLimit: positiveInteger.max(100_000), maxConcurrent: positiveInteger.max(1_024) }), accounts: z.object({ + autoDisableDegradedAccounts: z.boolean(), markBuildForbiddenReauth: z.boolean(), buildForbiddenReauthCodes: z.string().superRefine((value, context) => { const codes = parseForbiddenCodes(value); @@ -226,6 +227,7 @@ export function toSettingsForm(config: SettingsConfigDTO): SettingsForm { }, clientKeyDefaults: config.clientKeyDefaults, accounts: { + autoDisableDegradedAccounts: config.accounts.autoDisableDegradedAccounts, markBuildForbiddenReauth: config.accounts.markBuildForbiddenReauth, buildForbiddenReauthCodes: config.accounts.buildForbiddenReauthCodes.join("\n"), excludeBuildBotFlaggedFromScheduling: config.accounts.excludeBuildBotFlaggedFromScheduling, @@ -275,6 +277,7 @@ export function toSettingsDTO(config: SettingsForm): SettingsConfigDTO { }, clientKeyDefaults: config.clientKeyDefaults, accounts: { + autoDisableDegradedAccounts: config.accounts.autoDisableDegradedAccounts, markBuildForbiddenReauth: config.accounts.markBuildForbiddenReauth, buildForbiddenReauthCodes: parseForbiddenCodes(config.accounts.buildForbiddenReauthCodes), excludeBuildBotFlaggedFromScheduling: config.accounts.excludeBuildBotFlaggedFromScheduling, diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index 76eec191..f30a17c8 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -436,6 +436,18 @@ export function SettingsPage() { + +
+ + ( +
+ +
+ )} /> +
+
+
+
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index b31d7146..1cf6070e 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1022,7 +1022,7 @@ const resources = { console: { baseURLHelp: "Grok Console 请求与账号操作使用的基础端点。", chatTimeoutHelp: "Grok Console 聊天请求完成前允许等待的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "仅文本 SSE 连续无上游数据时允许等待的最长时间;不影响媒体和非流式请求。" }, batch: { title: "批量任务", importConcurrency: "导入同步并发", importConcurrencyHelp: "批量导入后并行执行账号初始化与信息同步的任务数。", conversionConcurrency: "账号转换并发", conversionConcurrencyHelp: "跨 Provider 转换账号时允许同时处理的任务数。", syncConcurrency: "数据同步并发", syncConcurrencyHelp: "批量同步账号额度、状态与能力时允许同时处理的任务数。", refreshConcurrency: "凭据刷新并发", refreshConcurrencyHelp: "批量刷新账号凭据时允许同时处理的任务数。", randomDelay: "随机延迟上限(ms)", randomDelayHelp: "批量任务启动前增加的随机延迟上限,用于平滑上游请求峰值。" }, media: { title: "媒体存储", maxImageSize: "单张图片上限", maxImageSizeHelp: "单个图片文件允许写入本地媒体存储的最大大小。", maxTotalSize: "媒体存储上限", maxTotalSizeHelp: "本地图片与视频文件允许占用的总存储空间。", cleanupThresholdPercent: "自动清理阈值", cleanupThresholdPercentHelp: "存储使用率达到该比例后,系统按时间清理较早的媒体文件。", cleanupInterval: "容量检查间隔", cleanupIntervalHelp: "后台检查媒体存储使用量并触发清理的时间间隔。", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" }, - egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" }, + egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个标准代理地址,HTTP 代理也可使用 IP:端口:用户名:密码。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" }, routing: { title: "路由策略", stickyTTL: "会话粘性时长", stickyTTLHelp: "同一会话优先复用已选账号的有效时长;到期后重新参与调度。", cooldownBase: "基础冷却时间", cooldownBaseHelp: "账号发生可恢复故障后首次进入冷却的时长。", cooldownMax: "最大冷却时间", cooldownMaxHelp: "连续故障触发指数退避时允许达到的最长冷却时间。", capacityWait: "账号满载等待", capacityWaitHelp: "全部候选账号并发已满时,切换或失败前等待容量释放的时间。", maxAttempts: "最大尝试次数", maxAttemptsHelp: "单次请求在可用账号之间切换并重试的最大次数,范围为 1–200。", videoMaxAttempts: "视频最大尝试次数", videoMaxAttemptsHelp: "仅作用于视频任务创建阶段的切号重试,可单独设置数值,或开启无限制。创建成功后的轮询不会换号。", preferFreeBuild: "Grok Build Free 账号优先", preferFreeBuildHelp: "启用后优先选择已确认可用的 Free 账号,其他路由条件保持不变。", accountIsolatedConnections: "按账号隔离上游连接", accountIsolatedConnectionsHelp: "开启后,不同账号使用各自的上游 TCP/HTTP 连接池,便于外部 L4 或按连接哈希的负载均衡器分散流量;同一账号仍可复用连接。适用于 Build / Web / Console 出站及 Web 转 Build。会增加连接数、TLS 握手、内存和文件描述符占用,建议仅在确有外部连接级负载均衡需求时开启。" }, audit: { title: "请求审计与日志设置", @@ -1043,6 +1043,9 @@ const resources = { clientKeys: { title: "密钥默认限制", rpmLimit: "默认 RPM", rpmLimitHelp: "新建客户端密钥默认允许的每分钟请求数。", maxConcurrent: "默认并发数", maxConcurrentHelp: "新建客户端密钥默认允许同时执行的请求数。" }, accounts: { title: "账号维护", + degradedAccountTitle: "降智账号处理", + autoDisableDegradedAccounts: "自动停用降智账号", + autoDisableDegradedAccountsHelp: "开启后启用请求内质量检测与重试,首次确认缺少 thinking 或吞吐降智时立即停用账号;关闭后不因吞吐降智停用,缺少 thinking 的拦截与冷却按原有配置执行。", invalidationTitle: "自动拦截判定", botRiskSchedulingTitle: "风控调度", excludeBuildBotFlaggedFromScheduling: "风控 Build 号移出调度", @@ -1815,7 +1818,7 @@ const resources = { errorFrameCount_one: "{{count}} error frame", errorFrameCount_other: "{{count}} error frames", }, - settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", audit: "Audit & Logs", accounts: "Account maintenance", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", freeVideoDurationCap: "Free-account video duration cap", freeVideoDurationCapHelp: "Caps duration sent to Grok Web for free-tier accounts so requests over the upstream limit do not 429 and rotate accounts uselessly. Default 6 seconds, range 1–15.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H.\nResin users can put {account} in the username to bind one lease per account.", proxyPool: "Proxy pool mode", proxyPoolHelp: "A request-level connection failure does not cool the entire shared node. Proxies containing {account} use this policy automatically.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed", refreshClearance: "Refresh Clearance", clearanceRefreshed: "Clearance refreshed", clearanceManaged: "Cloudflare cookies and User-Agent are managed by FlareSolverr; account-bound proxies are isolated per account." }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", stickyTTLHelp: "How long a session prefers its selected account before returning to normal scheduling.", cooldownBase: "Base cooldown", cooldownBaseHelp: "Initial cooldown applied after a recoverable account failure.", cooldownMax: "Maximum cooldown", cooldownMaxHelp: "Longest cooldown allowed when repeated failures trigger exponential backoff.", capacityWait: "Saturated account wait", capacityWaitHelp: "How long to wait for capacity before switching accounts or failing when all candidates are saturated.", maxAttempts: "Maximum attempts", maxAttemptsHelp: "Maximum account switches and retries allowed for one request, from 1 to 200.", videoMaxAttempts: "Video maximum attempts", videoMaxAttemptsHelp: "Create-phase account failover for video jobs only. Set a number or enable unlimited. Polling after create stays on the same account.", preferFreeBuild: "Prefer Grok Build Free accounts", preferFreeBuildHelp: "Prefer confirmed usable Free accounts without changing other routing eligibility rules.", accountIsolatedConnections: "Isolate upstream connections by account", accountIsolatedConnectionsHelp: "When enabled, each account uses its own upstream TCP/HTTP connection pool so external L4 or connection-hash load balancers can spread traffic; the same account still reuses connections. Applies to Build, Web, Console, and Web-to-Build traffic. This increases connections, TLS handshakes, memory, and file-descriptor usage, so enable it only when connection-level balancing is required." }, audit: { title: "Request Audit & Logs", tabTitle: "Audit & Logs", retentionTitle: "Log Retention Policy", retentionDays: "Log retention days", retentionDaysHelp: "Automatically purges request audits and failure attempts older than the specified days. Set to 0 for indefinite retention, default is 7 days.", performanceTitle: "Buffer & Performance", bufferSize: "Queue capacity", bufferSizeHelp: "Maximum audit records held in memory before persistence.", batchSize: "Batch size", batchSizeHelp: "Maximum audit records written in one database transaction.", flushInterval: "Flush interval", flushIntervalHelp: "Maximum time pending audit records wait before they are committed.", commitDelay: "Commit aggregation delay (ms)", commitDelayHelp: "Maximum time acknowledged writes wait to join an atomic batch before commit." }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", rpmLimitHelp: "Requests per minute assigned to newly created client keys.", maxConcurrent: "Default concurrency", maxConcurrentHelp: "Concurrent requests assigned to newly created client keys." }, accounts: { title: "Account maintenance", invalidationTitle: "Automatic interception", botRiskSchedulingTitle: "Bot-risk scheduling", excludeBuildBotFlaggedFromScheduling: "Exclude bot-risk Build accounts from scheduling", excludeBuildBotFlaggedFromSchedulingHelp: "When enabled, Grok Build accounts whose JWT bot_flag_source/bfs is 1 or 2 are removed from Build scheduling only. Linked Web/Console accounts keep their normal scheduling. Accounts remain in the pool for viewing and manual actions.", cleanupTitle: "Account cleanup", autoCleanReauthEnabled: "Automatic invalid-account cleanup", autoCleanReauthEnabledHelp: "Permanently deletes invalid accounts after the configured retention period. Accounts with active requests or video jobs are skipped.", autoCleanReauthInterval: "Cleanup interval", autoCleanReauthIntervalHelp: "How often to check for eligible accounts, from 1 minute to 1 hour.", autoCleanReauthMinAge: "Minimum retention", autoCleanReauthMinAgeHelp: "How long to retain an account after it is marked for reauthorization.", autoCleanIncludeDisabled: "Include disabled accounts", autoCleanIncludeDisabledHelp: "Includes disabled accounts that require reauthorization in automatic cleanup.", autoCleanEnableTitle: "Enable automatic cleanup?", autoCleanEnableDescription: "Eligible accounts will be permanently deleted and cannot be recovered. The first run starts after one full cleanup interval.", autoCleanIncludeDisabledTitle: "Include disabled accounts?", autoCleanIncludeDisabledDescription: "Disabled accounts that require reauthorization will also be permanently deleted. This action cannot be undone.", autoCleanConfirm: "Enable" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, + settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", audit: "Audit & Logs", accounts: "Account maintenance", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", freeVideoDurationCap: "Free-account video duration cap", freeVideoDurationCapHelp: "Caps duration sent to Grok Web for free-tier accounts so requests over the upstream limit do not 429 and rotate accounts uselessly. Default 6 seconds, range 1–15.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H.\nResin users can put {account} in the username to bind one lease per account.", proxyPool: "Proxy pool mode", proxyPoolHelp: "A request-level connection failure does not cool the entire shared node. Proxies containing {account} use this policy automatically.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed", refreshClearance: "Refresh Clearance", clearanceRefreshed: "Clearance refreshed", clearanceManaged: "Cloudflare cookies and User-Agent are managed by FlareSolverr; account-bound proxies are isolated per account." }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", stickyTTLHelp: "How long a session prefers its selected account before returning to normal scheduling.", cooldownBase: "Base cooldown", cooldownBaseHelp: "Initial cooldown applied after a recoverable account failure.", cooldownMax: "Maximum cooldown", cooldownMaxHelp: "Longest cooldown allowed when repeated failures trigger exponential backoff.", capacityWait: "Saturated account wait", capacityWaitHelp: "How long to wait for capacity before switching accounts or failing when all candidates are saturated.", maxAttempts: "Maximum attempts", maxAttemptsHelp: "Maximum account switches and retries allowed for one request, from 1 to 200.", videoMaxAttempts: "Video maximum attempts", videoMaxAttemptsHelp: "Create-phase account failover for video jobs only. Set a number or enable unlimited. Polling after create stays on the same account.", preferFreeBuild: "Prefer Grok Build Free accounts", preferFreeBuildHelp: "Prefer confirmed usable Free accounts without changing other routing eligibility rules.", accountIsolatedConnections: "Isolate upstream connections by account", accountIsolatedConnectionsHelp: "When enabled, each account uses its own upstream TCP/HTTP connection pool so external L4 or connection-hash load balancers can spread traffic; the same account still reuses connections. Applies to Build, Web, Console, and Web-to-Build traffic. This increases connections, TLS handshakes, memory, and file-descriptor usage, so enable it only when connection-level balancing is required." }, audit: { title: "Request Audit & Logs", tabTitle: "Audit & Logs", retentionTitle: "Log Retention Policy", retentionDays: "Log retention days", retentionDaysHelp: "Automatically purges request audits and failure attempts older than the specified days. Set to 0 for indefinite retention, default is 7 days.", performanceTitle: "Buffer & Performance", bufferSize: "Queue capacity", bufferSizeHelp: "Maximum audit records held in memory before persistence.", batchSize: "Batch size", batchSizeHelp: "Maximum audit records written in one database transaction.", flushInterval: "Flush interval", flushIntervalHelp: "Maximum time pending audit records wait before they are committed.", commitDelay: "Commit aggregation delay (ms)", commitDelayHelp: "Maximum time acknowledged writes wait to join an atomic batch before commit." }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", rpmLimitHelp: "Requests per minute assigned to newly created client keys.", maxConcurrent: "Default concurrency", maxConcurrentHelp: "Concurrent requests assigned to newly created client keys." }, accounts: { title: "Account maintenance", degradedAccountTitle: "Degraded-account handling", autoDisableDegradedAccounts: "Automatically disable degraded accounts", autoDisableDegradedAccountsHelp: "Enables request-path quality checks and retries; the first confirmed missing-thinking or degraded-throughput hit disables the account immediately. When disabled, throughput hits do not disable accounts, and missing-thinking checks and cooldowns follow the existing configuration.", invalidationTitle: "Automatic interception", botRiskSchedulingTitle: "Bot-risk scheduling", excludeBuildBotFlaggedFromScheduling: "Exclude bot-risk Build accounts from scheduling", excludeBuildBotFlaggedFromSchedulingHelp: "When enabled, Grok Build accounts whose JWT bot_flag_source/bfs is 1 or 2 are removed from Build scheduling only. Linked Web/Console accounts keep their normal scheduling. Accounts remain in the pool for viewing and manual actions.", cleanupTitle: "Account cleanup", autoCleanReauthEnabled: "Automatic invalid-account cleanup", autoCleanReauthEnabledHelp: "Permanently deletes invalid accounts after the configured retention period. Accounts with active requests or video jobs are skipped.", autoCleanReauthInterval: "Cleanup interval", autoCleanReauthIntervalHelp: "How often to check for eligible accounts, from 1 minute to 1 hour.", autoCleanReauthMinAge: "Minimum retention", autoCleanReauthMinAgeHelp: "How long to retain an account after it is marked for reauthorization.", autoCleanIncludeDisabled: "Include disabled accounts", autoCleanIncludeDisabledHelp: "Includes disabled accounts that require reauthorization in automatic cleanup.", autoCleanEnableTitle: "Enable automatic cleanup?", autoCleanEnableDescription: "Eligible accounts will be permanently deleted and cannot be recovered. The first run starts after one full cleanup interval.", autoCleanIncludeDisabledTitle: "Include disabled accounts?", autoCleanIncludeDisabledDescription: "Disabled accounts that require reauthorization will also be permanently deleted. This action cannot be undone.", autoCleanConfirm: "Enable" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, egressProxyProfiles: { title: "Proxy address library", libraryTitle: "Proxy address library", libraryDescription: "Manage reusable proxy addresses in one place. Changes sync to every node using the address.", description: "Save proxy addresses that need to be reused across nodes.", add: "Add proxy address", addTitle: "Add proxy address", editTitle: "Edit proxy address", dialogDescription: "Changing the proxy address updates every bound node. Capacity and operational state remain isolated per node.", name: "Address name", endpoint: "Proxy address", nodes: "Used by", search: "Search address names", empty: "No proxy addresses", emptyLibrary: "The library is empty. Add an address to reuse it across nodes.", noMatches: "No matching proxy addresses", loadingSelection: "Loading selected address…", selectionUnavailable: "Proxy address #{{id}} is unavailable", saved: "Proxy address saved", deleted: "Proxy address deleted", deleteTitle: "Delete proxy address?", deleteDescription: "This deletes {{name}}. Addresses currently used by nodes cannot be deleted.", deleteBlocked: "Used by {{count}} nodes", assignment: "Proxy address source", assignmentHelp: "Select an address from the library to reuse it across Provider nodes. Health, capacity, User-Agent, and Clearance remain isolated per node.", independent: "Configure this node separately", managedByProfile: "Managed by the proxy address library", nodeCount: "{{count}} nodes", backToLibrary: "Back to address library", createFromPicker: "Add and use a proxy address", refreshNodes: "Refresh proxy nodes", reveal: "Reveal full proxy URL", hide: "Hide full proxy URL", revealUnavailable: "Only a saved proxy address can reveal its URL" }, settingsBuildTransport: { responseHeaderTimeout: "Response header timeout", responseHeaderTimeoutHelp: "Maximum time to wait for the first Grok Build response headers after the request body is sent.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum wait for useful generated content or tool progress. Keepalives and private control events do not extend the deadline." }, @@ -2166,7 +2169,7 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record