From 8038dca603eade3ec5ec392daa40819808a78ca7 Mon Sep 17 00:00:00 2001 From: volcanolin Date: Tue, 22 Sep 2026 15:44:49 +0800 Subject: [PATCH 01/14] fix(web): filter imagine websocket events by requestId to prevent stale gallery frame crosstalk --- backend/internal/infra/provider/web/image.go | 31 ++++++--- .../infra/provider/web/protocol_test.go | 63 +++++++++++++++++++ 2 files changed, 87 insertions(+), 7 deletions(-) diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index 4905e356..fd049536 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 != "" && 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/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 2627addf..ce89620a 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -1786,3 +1786,66 @@ 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 + collector.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, + }) + if collector.UsableCount() != 0 { + 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) + } +} From abc5c294f911d6bf1bbdefddec2c5b7c9be72122 Mon Sep 17 00:00:00 2001 From: li Date: Fri, 25 Sep 2026 20:37:20 +0800 Subject: [PATCH 02/14] =?UTF-8?q?fix(web):=20device=20approve=20=E5=B8=A6?= =?UTF-8?q?=E4=B8=8A=20consent=5Ftoken=EF=BC=8C=E4=BF=AE=E5=A4=8D=20conver?= =?UTF-8?q?t-to-build=20403?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit xAI 在 device 授权流程新增了一次性 consent_token(ES256 JWT, typ=consent+jwt), 放在 /oauth2/device/consent 页面里,approve 必须回传,否则 403 "Request could not be verified"。旧流程没取这个令牌,导致 SSO→Build 全部换不出。 verify 之后 GET consent 页面解析 consent_token,再随 approve 一起提交。 --- .../internal/infra/provider/web/sso_build.go | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/backend/internal/infra/provider/web/sso_build.go b/backend/internal/infra/provider/web/sso_build.go index f6f443bb..86714c9d 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" @@ -101,9 +102,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,8 +122,21 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre } return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败") } + + // verify 以 3xx 跳转到 consent 时响应体为空,需要 GET consent 页面本身来解析 consent_token。 + consentToken := extractConsentToken(verifyBody) + if consentToken == "" { + if _, _, consentBody, cerr := f.do(ctx, http.MethodGet, finalURL, nil); cerr == nil { + consentToken = extractConsentToken(consentBody) + } + } + if consentToken == "" { + return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败:未获取 consent_token") + } + status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoApproveURL, url.Values{ "user_code": {device.UserCode}, "action": {"allow"}, "principal_type": {"User"}, "principal_id": {""}, + "consent_token": {consentToken}, }, false) if err != nil { return provider.CredentialSeed{}, err @@ -351,6 +367,23 @@ func normalizeSSOToken(value string) string { return strings.NewReplacer("\r", "", "\n", "", "\x00", "").Replace(value) } +var ( + consentTokenFormRe = regexp.MustCompile(`name="consent_token"[^>]*value="([^"]+)"`) + consentTokenJSONRe = regexp.MustCompile(`consentToken["\\:= ]{1,6}(eyJ[A-Za-z0-9._-]+)`) +) + +// extractConsentToken 从 consent 页面 HTML 中解析一次性 consent_token: +// 优先取表单隐藏字段 name="consent_token",回退到 RSC/JSON 里的 consentToken。 +func extractConsentToken(body []byte) string { + if m := consentTokenFormRe.FindSubmatch(body); m != nil { + return string(m[1]) + } + if m := consentTokenJSONRe.FindSubmatch(body); m != nil { + return string(m[1]) + } + return "" +} + func decodeBuildClaims(token string) map[string]any { parts := strings.Split(token, ".") if len(parts) < 2 { From cfc5865df7f0db132a732ba8f047871dfdc86746 Mon Sep 17 00:00:00 2001 From: noodledon Date: Sat, 26 Sep 2026 17:05:58 +0800 Subject: [PATCH 03/14] =?UTF-8?q?fix(web):=20fetch=20consent=5Ftoken=20and?= =?UTF-8?q?=20send=20browser=20form=20headers=20in=20SSO=E2=86=92Build=20d?= =?UTF-8?q?evice=20flow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit xAI's device approval now renders a consent page on accounts.x.ai containing a hidden consent_token JWT, and POSTs to auth.x.ai/oauth2/device/approve without it — or without the Origin/Referer/Sec-Fetch headers a real form submit carries — return 403 'Request could not be verified'. Web→Build conversion failed for every account. After the verify 303, GET the consent page, scrape consent_token, and POST it back with browser-style navigation headers. Verified live against auth.x.ai: approve now 303s to /oauth2/device/done and the token endpoint returns access+refresh tokens. --- .../internal/infra/provider/web/sso_build.go | 52 +++++++++++++++++-- .../infra/provider/web/sso_build_test.go | 30 +++++++++-- 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/backend/internal/infra/provider/web/sso_build.go b/backend/internal/infra/provider/web/sso_build.go index f6f443bb..d3923ac0 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" @@ -103,7 +104,7 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre // 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) + status, finalURL, _, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false, nil) if err != nil { return provider.CredentialSeed{}, err } @@ -119,9 +120,39 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre } return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败") } + consentPage := finalURL + browserHeaders := map[string]string{ + "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", + } + status, _, consentBody, err := f.doWithFollow(ctx, http.MethodGet, consentPage, nil, true, browserHeaders) + if err != nil { + return provider.CredentialSeed{}, err + } + if status < 200 || status >= 400 { + return provider.CredentialSeed{}, fmt.Errorf("SSO Device Consent 页面加载失败: %w", conversionHTTPError{status: status}) + } + consentToken := scrapeConsentToken(consentBody) + if consentToken == "" { + return provider.CredentialSeed{}, fmt.Errorf("SSO Device Consent 缺少 consent_token") + } status, finalURL, _, err = f.doWithFollow(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": consentPage, + "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 } @@ -217,12 +248,12 @@ func (f *ssoBuildFlow) pollToken(ctx context.Context, deviceCode string, interva } func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url.Values) (int, string, []byte, error) { - return f.doWithFollow(ctx, method, endpoint, form, true) + return f.doWithFollow(ctx, method, endpoint, form, true, nil) } // 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) { +func (f *ssoBuildFlow) doWithFollow(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 +273,9 @@ 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()) + for key, value := range extraHeaders { + request.Header.Set(key, value) + } if currentForm != nil { request.Header.Set("Content-Type", "application/x-www-form-urlencoded") } @@ -300,6 +334,16 @@ func (f *ssoBuildFlow) captureCookies(response *http.Response) { } } +var consentTokenPattern = regexp.MustCompile(`name="consent_token"\s+value="([^"]+)"`) + +func scrapeConsentToken(body []byte) string { + match := consentTokenPattern.FindSubmatch(body) + if len(match) < 2 { + return "" + } + return string(match[1]) +} + func ssoDeviceRedirectState(raw string) string { parsed, err := url.Parse(raw) if err != nil || !safeXAIURL(raw) { diff --git a/backend/internal/infra/provider/web/sso_build_test.go b/backend/internal/infra/provider/web/sso_build_test.go index 7bcd2615..50bf24f0 100644 --- a/backend/internal/infra/provider/web/sso_build_test.go +++ b/backend/internal/infra/provider/web/sso_build_test.go @@ -73,7 +73,9 @@ func TestSSOBuildFlowUsesAuthEndpointsOnly(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.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent?user_code=uc"}}, 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}`))}, @@ -83,14 +85,22 @@ func TestSSOBuildFlowUsesAuthEndpointsOnly(t *testing.T) { 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" { - t.Fatalf("device flow visited unexpected host %q", request.URL.Hostname()) + host := request.URL.Hostname() + if host != "auth.x.ai" && host != "accounts.x.ai" { + t.Fatalf("device flow visited unexpected host %q", host) } } + approve := client.requests[3] + if approve.URL.Hostname() != "auth.x.ai" || !strings.Contains(approve.URL.Path, "approve") { + t.Fatalf("request[3] = %s, want approve POST", approve.URL) + } + if approve.Header.Get("Origin") != "https://accounts.x.ai" { + t.Fatalf("approve missing Origin header: %v", approve.Header) + } } func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) { @@ -98,7 +108,7 @@ func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) { {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))}, }} 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, _, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false, nil) if err != nil { t.Fatal(err) } @@ -146,3 +156,13 @@ func TestSSOBuildConversionSanitizesTokenAndURLs(t *testing.T) { } } } + +func TestScrapeConsentToken(t *testing.T) { + page := []byte(``) + if got := scrapeConsentToken(page); got != "tok-abc-123" { + t.Fatalf("scrapeConsentToken = %q", got) + } + if got := scrapeConsentToken([]byte(``)); got != "" { + t.Fatalf("expected empty, got %q", got) + } +} From a88cd8808c77a4cd93be5a42ae4e8d8dfea8f96e Mon Sep 17 00:00:00 2001 From: Solaris-star <820622658@qq.com> Date: Tue, 29 Sep 2026 16:42:33 +0800 Subject: [PATCH 04/14] fix(gateway): cool down Build accounts after unknown 403 --- backend/internal/application/gateway/service.go | 2 +- backend/internal/application/gateway/service_test.go | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 5abd80b1..309cd7e1 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1554,7 +1554,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 diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 0fd0e8c9..90651561 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -1963,7 +1963,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 +2033,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 +3946,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 { From 31bbe64dc95424537d5a5593d3dbfbfaeeb33da7 Mon Sep 17 00:00:00 2001 From: carfeii Date: Wed, 30 Sep 2026 15:26:04 +0800 Subject: [PATCH 05/14] fix: video job retry can bypass client key account scope Every other account-selection path (text chat, image generation, voice, voice websocket) threads the requesting client key's AccountScope through to beginSelectionSessionForKey. The video job's background retry/recovery worker (runVideoJob) used the unscoped beginSelectionSession instead, so once the job's originally pinned account failed, the fallback search for a replacement ignored the client key's provider/tier restrictions entirely. A client key restricted to e.g. Super-tier accounts could end up consuming a Free-tier (or wrong-provider) account's quota purely because its pinned account hit a transient failure, silently widening access beyond what the key was configured to allow. media.Job already stores ClientKeyID, so the fix looks up that key and passes its AccountScope into beginSelectionSessionForKey, matching every other selection path. Added a regression test (TestVideoRetryDoesNotEscapeClientKeyAccountScope) that fails against the prior code (confirmed: the out-of-scope account was used) and passes with the fix. --- backend/internal/application/gateway/video.go | 18 +++- .../application/gateway/video_test.go | 101 ++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index d3bf44a9..c6ed1ee4 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -531,6 +531,22 @@ 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 { + 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 +580,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..71eb3d31 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -900,3 +900,104 @@ 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, + } + 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) + } +} From ea563c31cec42078b409d461138de655657270a4 Mon Sep 17 00:00:00 2001 From: inter Date: Mon, 17 Aug 2026 16:44:07 +0800 Subject: [PATCH 06/14] feat(egress): support legacy authenticated HTTP proxy format --- .../internal/application/egress/service.go | 21 +++++++++++++++++++ .../application/egress/service_test.go | 10 +++++++++ .../application/egress/subscription_test.go | 6 +++++- frontend/src/shared/i18n/index.ts | 4 ++-- 4 files changed, 38 insertions(+), 3 deletions(-) diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 6ba9144d..5c01de68 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" @@ -1341,6 +1343,9 @@ func NormalizeProxyURL(value string) (string, error) { if len(value) > maxProxyURLBytes || strings.IndexFunc(value, func(character rune) bool { return character < 0x20 || character == 0x7f }) >= 0 { return "", errors.New("代理地址过长或包含控制字符") } + if normalized, ok := normalizeLegacyHTTPProxy(value); ok { + value = normalized + } hasAccountPlaceholder := strings.Contains(value, ProxyAccountPlaceholder) if strings.Count(value, ProxyAccountPlaceholder) > 1 { return "", errors.New("代理地址最多包含一个 {account} 占位符") @@ -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..fe4d7786 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -49,6 +49,16 @@ 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 TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) { base := "trojan://password@proxy.example:443?security=tls&sni=edge.example" one, err := NormalizeProxyURL(base + "#one") diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index 2536b967..7b1d7691 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) diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index b31d7146..d3a6431d 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: "请求审计与日志设置", @@ -2166,7 +2166,7 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record Date: Wed, 26 Aug 2026 22:49:00 +0800 Subject: [PATCH 07/14] feat(gateway): auto-disable degraded accounts --- README.md | 4 +- README.zh-CN.md | 4 +- backend/internal/app/application.go | 30 ++++++++----- .../application/gateway/quality_retry.go | 33 +++++++++++++- .../application/gateway/quality_retry_test.go | 44 +++++++++++++++++++ .../internal/application/gateway/selector.go | 33 ++++++++------ .../application/gateway/selector_test.go | 26 +++++++++-- .../internal/application/gateway/service.go | 7 ++- backend/internal/infra/config/config.go | 1 + backend/internal/infra/config/config_test.go | 7 ++- config.example.yaml | 6 ++- 11 files changed, 157 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 8ca37bfa..0d1cfbca 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 enables it. When enabled, 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). If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. 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..86752ac1 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 探测/隔离相互独立。示例配置默认开启。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试;`autoDisable: true` 会在首次确认缺 thinking 或吞吐降智(soft/hard/burst)时直接禁用账号。全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。不处理图/视频、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..ad9b77f3 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,23 @@ 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, + Enabled: retry.Enabled, + 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/application/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index df3845e7..4b9872fc 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,21 @@ 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 { + 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..593a1233 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,49 @@ 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 + 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..d19e9b4f 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}) @@ -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/infra/config/config.go b/backend/internal/infra/config/config.go index edf9dc9f..eeea5d42 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -295,6 +295,7 @@ type QualityGuardRequestRetryConfig struct { HoldTimeout Duration `yaml:"holdTimeout"` MinOutputTokens int `yaml:"minOutputTokens"` OnExhausted string `yaml:"onExhausted"` + 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. diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index cd2ba074..78c6dc13 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,7 +226,7 @@ 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) } } diff --git a/config.example.yaml b/config.example.yaml index 7a3ae2f4..e46d1177 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -170,8 +170,10 @@ 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). + # When false, missing-thinking keeps the historical cooldown/second-hit policy. + autoDisable: true accountCooldown: 12h # Empty SSE / idle-timeout penalty. Independent of accountCooldown. # Single-account pools should set this lower; toggling enabled does not From b789e8466d362b917a87e570320c5c6606c9aad3 Mon Sep 17 00:00:00 2001 From: inter Date: Sun, 4 Oct 2026 04:59:10 +0800 Subject: [PATCH 08/14] feat(settings): support auto-disable degraded accounts in management UI and filter bound accounts by ID --- backend/internal/application/model/service.go | 8 ++- .../application/model/service_test.go | 51 +++++++++++++++++++ .../internal/application/settings/service.go | 17 ++++++- .../application/settings/service_test.go | 44 ++++++++++++++++ backend/internal/domain/settings/settings.go | 3 ++ .../transport/http/settings/handler.go | 4 ++ .../transport/http/settings/security_test.go | 2 +- .../src/features/settings/settings-api.ts | 4 ++ .../src/features/settings/settings-model.ts | 3 ++ .../src/features/settings/settings-page.tsx | 12 +++++ frontend/src/shared/i18n/index.ts | 5 +- 11 files changed, 147 insertions(+), 6 deletions(-) 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/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/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..d14b6cfe 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -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: "When enabled, the first confirmed missing-thinking or degraded-throughput hit disables the account immediately. When disabled, throughput hits do not disable accounts, while missing-thinking falls back to cooling the first hit and disabling after a later confirmation.", 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." }, From 2f29773bede1c6c022ecbd16b285571673eae516 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:28:01 +0800 Subject: [PATCH 09/14] fix: refine requestId filtering in imagine collector to enhance image handling --- backend/internal/infra/provider/web/image.go | 2 +- .../internal/infra/provider/web/protocol_test.go | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index fd049536..77125a00 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -109,7 +109,7 @@ func (c *imagineCollector) Accept(message map[string]any) { msgReqID = firstString(item, "requestId", "request_id") } } - if msgReqID != "" && msgReqID != c.requestID { + if msgReqID != c.requestID { return } } diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index ce89620a..c294a605 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -1787,7 +1787,6 @@ func MarshalJSONBytes(value any) []byte { return data } - func TestImagineCollectorFiltersMismatchedRequestIDs(t *testing.T) { reqID := "img_target_12345" collector := newImagineCollector(reqID) @@ -1813,7 +1812,8 @@ func TestImagineCollectorFiltersMismatchedRequestIDs(t *testing.T) { } // 2. Nested item.requestId must also be matched - collector.Accept(map[string]any{ + staleNestedCollector := newImagineCollector(reqID) + staleNestedCollector.Accept(map[string]any{ "type": "image", "id": "stale-nested-1", "item": map[string]any{ @@ -1822,7 +1822,14 @@ func TestImagineCollectorFiltersMismatchedRequestIDs(t *testing.T) { "url": "https://imagine-public.x.ai/imagine-public/images/stale2.jpg", "percentage_complete": 100.0, }) - if collector.UsableCount() != 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") } From bedc88feb6421e2ea74d3fad2af77e2c31e42ec5 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:09:31 +0800 Subject: [PATCH 10/14] feat: enhance SSO flow with consent token handling and cookie management --- .../internal/infra/provider/web/sso_build.go | 73 +++++++++++++++-- .../infra/provider/web/sso_build_test.go | 82 +++++++++++++++++-- 2 files changed, 139 insertions(+), 16 deletions(-) diff --git a/backend/internal/infra/provider/web/sso_build.go b/backend/internal/infra/provider/web/sso_build.go index 86714c9d..8969504f 100644 --- a/backend/internal/infra/provider/web/sso_build.go +++ b/backend/internal/infra/provider/web/sso_build.go @@ -20,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 ( @@ -63,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 { @@ -126,11 +127,16 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre // verify 以 3xx 跳转到 consent 时响应体为空,需要 GET consent 页面本身来解析 consent_token。 consentToken := extractConsentToken(verifyBody) if consentToken == "" { - if _, _, consentBody, cerr := f.do(ctx, http.MethodGet, finalURL, nil); cerr == nil { - consentToken = extractConsentToken(consentBody) + consentStatus, _, consentBody, cerr := f.do(ctx, http.MethodGet, finalURL, 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 consentToken == "" { + if !consentTokenMatchesDevice(consentToken, device.DeviceCode) { return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败:未获取 consent_token") } @@ -258,6 +264,14 @@ 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") + } if currentForm != nil { request.Header.Set("Content-Type", "application/x-www-form-urlencoded") } @@ -291,7 +305,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 @@ -347,6 +361,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() == "" { @@ -368,15 +393,37 @@ func normalizeSSOToken(value string) string { } var ( - consentTokenFormRe = regexp.MustCompile(`name="consent_token"[^>]*value="([^"]+)"`) - consentTokenJSONRe = regexp.MustCompile(`consentToken["\\:= ]{1,6}(eyJ[A-Za-z0-9._-]+)`) + 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 { - if m := consentTokenFormRe.FindSubmatch(body); m != nil { - return string(m[1]) + 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]) @@ -384,6 +431,14 @@ func extractConsentToken(body []byte) string { 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..e0147a0a 100644 --- a/backend/internal/infra/provider/web/sso_build_test.go +++ b/backend/internal/infra/provider/web/sso_build_test.go @@ -69,36 +69,60 @@ 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) + } + 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 +135,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 +158,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) From 23793f3e0d67a7f63974bc041da2c399a464ecde Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:46:28 +0800 Subject: [PATCH 11/14] fix: ensure requestId is included in Imagine websocket responses for accurate event handling --- .../web/media_clearance_retry_test.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) 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() From 6cd06ea5e7c43861acd5fbe63f2c22faedf2e10a Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:10:00 +0800 Subject: [PATCH 12/14] fix: add recovery test for video job on worker shutdown --- backend/internal/application/gateway/video.go | 4 +++ .../application/gateway/video_test.go | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index c6ed1ee4..35e3351c 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -542,6 +542,10 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model 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 } diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index 71eb3d31..bde71cdc 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -983,6 +983,32 @@ func TestVideoRetryDoesNotEscapeClientKeyAccountScope(t *testing.T) { 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) } From 0a3efcc459852dee442be5b82d275d78233ce7a3 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:32:17 +0800 Subject: [PATCH 13/14] feat: enhance proxy URL normalization and test logic --- .../internal/application/egress/service.go | 6 +-- .../application/egress/service_test.go | 51 +++++++++++++++---- .../application/egress/subscription_test.go | 25 +++++++++ 3 files changed, 70 insertions(+), 12 deletions(-) diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 5c01de68..331d36ea 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -1343,9 +1343,6 @@ func NormalizeProxyURL(value string) (string, error) { if len(value) > maxProxyURLBytes || strings.IndexFunc(value, func(character rune) bool { return character < 0x20 || character == 0x7f }) >= 0 { return "", errors.New("代理地址过长或包含控制字符") } - if normalized, ok := normalizeLegacyHTTPProxy(value); ok { - value = normalized - } hasAccountPlaceholder := strings.Contains(value, ProxyAccountPlaceholder) if strings.Count(value, ProxyAccountPlaceholder) > 1 { return "", errors.New("代理地址最多包含一个 {account} 占位符") @@ -1354,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("代理地址格式无效") diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index fe4d7786..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" @@ -59,6 +60,27 @@ func TestNormalizeProxyURLAcceptsLegacyHTTPProxyFormat(t *testing.T) { } } +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") @@ -75,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 7b1d7691..ee98e42a 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -75,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") From 659ee8ca69e2909cf4ce9865e5ecae08e6555ed1 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:44:11 +0800 Subject: [PATCH 14/14] refactor: enhance request retry configuration and auto-disable logic; update documentation and tests for clarity --- README.md | 2 +- README.zh-CN.md | 2 +- backend/internal/app/application.go | 5 +- backend/internal/app/quality_retry_test.go | 77 +++++++++++++++++++ .../application/gateway/quality_retry.go | 5 ++ .../application/gateway/quality_retry_test.go | 9 +++ .../application/gateway/service_test.go | 24 +++++- backend/internal/infra/config/config.go | 18 +++-- backend/internal/infra/config/config_test.go | 28 +++++++ config.example.yaml | 10 ++- frontend/src/shared/i18n/index.ts | 4 +- 11 files changed, 165 insertions(+), 19 deletions(-) create mode 100644 backend/internal/app/quality_retry_test.go diff --git a/README.md b/README.md index 0d1cfbca..fe174a9f 100644 --- a/README.md +++ b/README.md @@ -413,7 +413,7 @@ qualityGuard: idleAccountCooldown: 15m ``` -`requestRetry` runs on the gateway request path and is independent of the sidecar. The example enables it. When enabled, 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). If every attempt still has no reasoning, `onExhausted` either returns `503 quality_degraded` or delivers the last body. Image, video, stored-response, and ForcedEgress probe requests are unchanged. Grok TUI tool turns stay held so 0-thinking dumps cannot skip the gate. +`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 86752ac1..05ab9133 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -379,7 +379,7 @@ qualityGuard: idleAccountCooldown: 15m ``` -`requestRetry` 在网关请求路径上生效,与 sidecar 探测/隔离相互独立。示例配置默认开启。开启后,可见输出达到 `minOutputTokens` 且全程无流式 reasoning 时**不发给用户**,排除该账号再试;`autoDisable: true` 会在首次确认缺 thinking 或吞吐降智(soft/hard/burst)时直接禁用账号。全部仍无推理则按 `onExhausted` 返回 `503 quality_degraded` 或放出最后一枪。不处理图/视频、stored response 钉账号和 ForcedEgress 探针。Grok TUI 带 tools 的回合仍会 hold,避免 0-thinking 降智流跳过闸门。 +`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 ad9b77f3..52dcb8e4 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -493,7 +493,10 @@ func accountAutoCleanConfig(value config.AccountsConfig) accountapp.AutoCleanCon func qualityRetryRuntime(value config.QualityGuardConfig) gateway.QualityRetryRuntime { retry := value.RequestRetry return gateway.QualityRetryRuntime{ - Enabled: retry.Enabled, + // 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), 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/gateway/quality_retry.go b/backend/internal/application/gateway/quality_retry.go index 4b9872fc..9eadd316 100644 --- a/backend/internal/application/gateway/quality_retry.go +++ b/backend/internal/application/gateway/quality_retry.go @@ -596,6 +596,11 @@ 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 } diff --git a/backend/internal/application/gateway/quality_retry_test.go b/backend/internal/application/gateway/quality_retry_test.go index 593a1233..611b7f10 100644 --- a/backend/internal/application/gateway/quality_retry_test.go +++ b/backend/internal/application/gateway/quality_retry_test.go @@ -255,6 +255,15 @@ func TestAutoDisableFirstOutputSpeedHit(t *testing.T) { 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) } diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 0fd0e8c9..28c4044f 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) } diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index eeea5d42..d8212bcf 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -295,6 +295,7 @@ 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 @@ -741,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 } @@ -759,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 之间") } @@ -774,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 分钟之间") } @@ -793,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 78c6dc13..a14b9b99 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -231,6 +231,34 @@ func TestDefaultQualityGuardRequestRetryContract(t *testing.T) { } } +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/config.example.yaml b/config.example.yaml index e46d1177..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. @@ -172,8 +172,10 @@ qualityGuard: onExhausted: fail_closed # fail_open | fail_closed # Immediately disable an account on its first confirmed missing-thinking # or degraded output-speed hit (soft-TPS, hard-TPS, or buffered-burst). - # When false, missing-thinking keeps the historical cooldown/second-hit policy. - autoDisable: true + # 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/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index d14b6cfe..c7e87276 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1045,7 +1045,7 @@ const resources = { title: "账号维护", degradedAccountTitle: "降智账号处理", autoDisableDegradedAccounts: "自动停用降智账号", - autoDisableDegradedAccountsHelp: "开启后,首次确认缺少 thinking 或吞吐降智时立即停用账号;关闭后不因吞吐降智停用,缺少 thinking 则恢复为首次冷却、再次确认后停用。", + autoDisableDegradedAccountsHelp: "开启后启用请求内质量检测与重试,首次确认缺少 thinking 或吞吐降智时立即停用账号;关闭后不因吞吐降智停用,缺少 thinking 的拦截与冷却按原有配置执行。", invalidationTitle: "自动拦截判定", botRiskSchedulingTitle: "风控调度", excludeBuildBotFlaggedFromScheduling: "风控 Build 号移出调度", @@ -1818,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", degradedAccountTitle: "Degraded-account handling", autoDisableDegradedAccounts: "Automatically disable degraded accounts", autoDisableDegradedAccountsHelp: "When enabled, the first confirmed missing-thinking or degraded-throughput hit disables the account immediately. When disabled, throughput hits do not disable accounts, while missing-thinking falls back to cooling the first hit and disabling after a later confirmation.", 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." },