From 58a6850a671777c94fed63ad7d8327aeedc9c48d Mon Sep 17 00:00:00 2001 From: mcheiyue <2267610721@qq.com> Date: Thu, 13 Aug 2026 00:50:41 +0800 Subject: [PATCH 01/17] =?UTF-8?q?fix(models):=20=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E6=94=B9=E4=B8=BA=E5=BC=82=E6=AD=A5=E8=A7=A6?= =?UTF-8?q?=E5=8F=91=EF=BC=8C=E9=81=BF=E5=85=8D=20CF=20100s=20=E8=B6=85?= =?UTF-8?q?=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/application/model/service.go | 7 +++++++ backend/internal/transport/http/model/handler.go | 10 ++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 79b3b4eb..706b359d 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -412,6 +412,13 @@ func (s *Service) Sync(ctx context.Context) (int, error) { } } +// SyncAsync 异步触发全量模型同步,不阻塞调用方。用 context.Background 避免请求超时导致同步中断。 +func (s *Service) SyncAsync(_ context.Context) { + s.syncAll.DoChan("all", func() (any, error) { + return s.syncAllAccounts(context.Background()) + }) +} + func (s *Service) syncAllAccounts(ctx context.Context) (int, error) { if s.providers == nil { return 0, fmt.Errorf("Provider 注册表未初始化") diff --git a/backend/internal/transport/http/model/handler.go b/backend/internal/transport/http/model/handler.go index 6fc6060d..ab24a95c 100644 --- a/backend/internal/transport/http/model/handler.go +++ b/backend/internal/transport/http/model/handler.go @@ -234,12 +234,10 @@ func (h *Handler) batchDelete(c *gin.Context) { } func (h *Handler) sync(c *gin.Context) { - count, err := h.service.Sync(c.Request.Context()) - if err != nil { - response.Error(c, http.StatusBadGateway, "modelSyncFailed", "同步上游模型失败") - return - } - response.Success(c, http.StatusOK, gin.H{"synced": count}) + // 异步触发全量同步,不阻塞 HTTP 响应。 + // 同步需要 2min+,Cloudflare 免费版 100s 超时,直接同步会 524 → 浏览器 Failed to fetch。 + go h.service.SyncAsync(c.Request.Context()) + response.Success(c, http.StatusOK, gin.H{"synced": 0, "async": true}) } func (h *Handler) update(c *gin.Context) { From 0b39b67f37513c0a4236260913bd084f763dfb6c Mon Sep 17 00:00:00 2001 From: RIERS <50164130+RIERS@users.noreply.github.com> Date: Thu, 13 Aug 2026 09:04:25 +0800 Subject: [PATCH 02/17] feat: add grok-4.6 xhigh reasoning effort Grok 4.6 accepts xhigh as a real thinking level. Keep it on the Build request path and generate grok-4.6-xhigh aliases instead of downgrading unknown-model xhigh to high. Unverified max stays guarded. --- backend/internal/domain/model/reasoning.go | 2 ++ backend/internal/domain/model/reasoning_test.go | 13 +++++++++++++ backend/internal/infra/provider/cli/normalize.go | 3 ++- .../internal/infra/provider/cli/normalize_test.go | 3 +++ .../transport/http/inference/model_list_test.go | 3 ++- frontend/src/shared/i18n/index.ts | 4 ++-- 6 files changed, 24 insertions(+), 4 deletions(-) diff --git a/backend/internal/domain/model/reasoning.go b/backend/internal/domain/model/reasoning.go index 35fcac5b..8caeb974 100644 --- a/backend/internal/domain/model/reasoning.go +++ b/backend/internal/domain/model/reasoning.go @@ -37,12 +37,14 @@ var reasoningEffortSuffixes = []string{ // generally accepted by the model family. Provider-specific wire restrictions are // applied by providerReasoningEffortOverrides: // - grok-4.5: low/medium/high (reasoning cannot be disabled; no xhigh/max) +// - grok-4.6: low/medium/high/xhigh (xhigh is a real upstream effort; max stays guarded) // - grok-4.3: none/low/medium/high // - grok-4.20-multi-agent: low/medium/high/xhigh (effort controls agent count) // // Unknown models default to none-only and never expand into effort aliases. var grokReasoningCapabilities = map[string][]string{ "grok-4.5": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, + "grok-4.6": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh, ReasoningEffortXHigh}, "grok-4.3": {ReasoningEffortNone, ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, "grok-build-0.1": {ReasoningEffortNone}, "grok-4.20-0309-reasoning": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, diff --git a/backend/internal/domain/model/reasoning_test.go b/backend/internal/domain/model/reasoning_test.go index 3e42599f..0ed814d1 100644 --- a/backend/internal/domain/model/reasoning_test.go +++ b/backend/internal/domain/model/reasoning_test.go @@ -17,6 +17,8 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { {model: "grok-4.20-0309-reasoning", want: []string{"low", "medium", "high"}}, {model: "Console/grok-4.20-0309-reasoning", want: []string{}}, {model: "grok-4.20-multi-agent-0309", want: []string{"low", "medium", "high", "xhigh"}}, + {model: "grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, + {model: "Build/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, {model: "grok-build-0.1", want: []string{"none"}}, {model: GrokComposer25Fast, want: []string{"none"}}, {model: "unknown-model", want: []string{"none"}}, @@ -38,6 +40,12 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { if !SupportsReasoningEffort("grok-4.3", "none") || SupportsReasoningEffort("grok-4.3", "xhigh") { t.Fatal("grok-4.3 effort support mismatch") } + if !SupportsReasoningEffort("grok-4.6", "xhigh") || !SupportsReasoningEffort("Build/grok-4.6-xhigh", "xhigh") { + t.Fatal("grok-4.6 must advertise xhigh") + } + if SupportsReasoningEffort("grok-4.6", "none") || SupportsReasoningEffort("grok-4.6", "max") { + t.Fatal("grok-4.6 must not advertise none/max") + } if SupportsReasoningEffortForProvider(account.ProviderConsole, "grok-4.20-0309-reasoning", "low") || !SupportsReasoningEffortForProvider(account.ProviderBuild, "grok-4.20-0309-reasoning", "low") { t.Fatal("grok-4.20 reasoning effort restriction must remain Console-specific") @@ -74,6 +82,8 @@ func TestParseReasoningModelAlias(t *testing.T) { {name: "grok-4.5 rejects xhigh", input: "grok-4.5-xhigh", wantOK: false}, {name: "grok-4.3 none", input: "grok-4.3-none", wantBase: "grok-4.3", wantLevel: "none", wantOK: true}, {name: "xhigh before high", input: "grok-4.20-multi-agent-0309-xhigh", wantBase: "grok-4.20-multi-agent-0309", wantLevel: "xhigh", wantOK: true}, + {name: "grok-4.6 xhigh", input: "grok-4.6-xhigh", wantBase: "grok-4.6", wantLevel: "xhigh", wantOK: true}, + {name: "grok-4.6 rejects max", input: "grok-4.6-max", wantOK: false}, {name: "prefixed base", input: "Build/grok-4.5-medium", wantBase: "Build/grok-4.5", wantLevel: "medium", wantOK: true}, {name: "base model not alias", input: "grok-4.5", wantOK: false}, {name: "single-level model no alias", input: "grok-build-0.1-none", wantOK: false}, @@ -94,6 +104,9 @@ func TestReasoningAliasPublicIDs(t *testing.T) { if got := ReasoningAliasPublicIDs("grok-4.5"); len(got) != 3 || got[0] != "grok-4.5-low" || got[2] != "grok-4.5-high" { t.Fatalf("grok-4.5 aliases = %#v", got) } + if got := ReasoningAliasPublicIDs("grok-4.6"); len(got) != 4 || got[0] != "grok-4.6-low" || got[3] != "grok-4.6-xhigh" { + t.Fatalf("grok-4.6 aliases = %#v", got) + } if got := ReasoningAliasPublicIDs("Build/grok-4.3"); len(got) != 4 || got[0] != "grok-4.3-none" { t.Fatalf("grok-4.3 aliases = %#v", got) } diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index 624b7c1b..b1d6b15f 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -118,7 +118,8 @@ func applyBuildResponseDefaults(payload map[string]json.RawMessage) (bool, error // normalizeBuildReasoningEffortPayload maps client aliases to levels accepted by // the selected Grok model. Grok 4.5 and unknown models retain the proven defensive -// xhigh/max -> high behavior; explicitly supported xhigh models keep their value. +// xhigh/max -> high behavior; grok-4.6 and other explicitly supported xhigh models +// keep their value. Unverified max remains guarded. func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, model string) bool { raw, exists := payload["reasoning"] if !exists || isEmptyJSON(raw) { diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index 9e5ee18b..2b1331c6 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -53,6 +53,9 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { {name: "multi-agent xhigh", model: "grok-4.20-multi-agent-0309", effort: "xhigh", want: "xhigh"}, {name: "multi-agent uppercase xhigh", model: "grok-4.20-multi-agent-0309", effort: "XHIGH", want: "xhigh"}, {name: "multi-agent max remains guarded", model: "grok-4.20-multi-agent-0309", effort: "max", want: "high"}, + {name: "4.6 xhigh", model: "grok-4.6", effort: "xhigh", want: "xhigh"}, + {name: "4.6 uppercase xhigh", model: "grok-4.6", effort: "XHIGH", want: "xhigh"}, + {name: "4.6 max remains guarded", model: "grok-4.6", effort: "max", want: "high"}, {name: "unknown xhigh remains guarded", model: "future-model", effort: "xhigh", want: "high"}, {name: "high", model: "grok-4.5", effort: "high", want: "high"}, {name: "medium", model: "grok-4.5", effort: "medium", want: "medium"}, diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index 8af1ac50..9301d21b 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -44,6 +44,7 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) { now := time.Unix(100, 0).UTC() base := newModelListItems([]modeldomain.Route{ {PublicID: "Build/grok-4.5", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, + {PublicID: "Build/grok-4.6", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, {PublicID: "Console/grok-4.3", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, {PublicID: "Console/grok-4.20-0309-reasoning", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, {PublicID: "Build/grok-build-0.1", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, @@ -53,7 +54,7 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) { for _, item := range expanded { ids[item.ID] = true } - for _, want := range []string{"grok-4.5", "grok-4.5-low", "grok-4.5-medium", "grok-4.5-high", "grok-4.3-none", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", "grok-build-0.1"} { + for _, want := range []string{"grok-4.5", "grok-4.5-low", "grok-4.5-medium", "grok-4.5-high", "grok-4.6", "grok-4.6-low", "grok-4.6-medium", "grok-4.6-high", "grok-4.6-xhigh", "grok-4.3-none", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", "grok-build-0.1"} { if !ids[want] { t.Fatalf("missing model %q in %#v", want, expanded) } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..45e81c9c 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -732,7 +732,7 @@ const resources = { enabledDescription: "控制该密钥是否允许发起 API 请求。", modelAliases: "模型别名", modelAliasesDescription: "仅为当前可用且支持多个推理等级的模型生成后缀别名。", - modelAliasesBuildSupport: "Grok Build:grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。", + modelAliasesBuildSupport: "Grok Build:grok-4.6 支持 low / medium / high / xhigh;grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。", modelAliasesConsoleSupport: "Grok Console:grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。", modelAliasesUnsupported: "Grok Web、图片模型和视频模型不生成推理等级后缀。", modelAliasesOn: "已开启:可发现并调用当前模型支持的推理等级别名。", @@ -1342,7 +1342,7 @@ const resources = { dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, - keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, + keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.6 supports low / medium / high / xhigh; grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, audits: { title: "Request audits", description: "Successful requests store metadata only. Failed requests retain a redacted and size-limited diagnostic snapshot.", From ee744275964eb6d517008fda3742b942547b1968 Mon Sep 17 00:00:00 2001 From: RIERS <50164130+RIERS@users.noreply.github.com> Date: Thu, 13 Aug 2026 10:08:29 +0800 Subject: [PATCH 03/17] fix: recover Grok Web Statsig meta from index 404 grok.com/index now returns HTTP 404 while still serving HTML that contains grok-site-verification. Parse that body instead of aborting on the status code, and fall back to / when the index page has no usable meta token. --- .../internal/infra/provider/web/statsig.go | 63 ++++++++++++++++--- .../infra/provider/web/statsig_test.go | 61 ++++++++++++++++++ 2 files changed, 114 insertions(+), 10 deletions(-) diff --git a/backend/internal/infra/provider/web/statsig.go b/backend/internal/infra/provider/web/statsig.go index 3f3e85fd..c313eff9 100644 --- a/backend/internal/infra/provider/web/statsig.go +++ b/backend/internal/infra/provider/web/statsig.go @@ -272,9 +272,46 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease * if lease == nil { return "", fmt.Errorf("Statsig 获取缺少出口租约") } + return fetchStatsigMetaContentWithDo(ctx, baseURL, token, lease, lease.Do) +} + +func fetchStatsigMetaContentWithDo(ctx context.Context, baseURL, token string, lease *infraegress.Lease, do func(*http.Request) (*http.Response, error)) (string, error) { + if do == nil { + return "", fmt.Errorf("Statsig 获取缺少出口租约") + } + var indexErr error + for _, path := range []string{"/index", "/"} { + content, err := fetchStatsigMetaContentPath(ctx, baseURL, token, lease, path, do) + if err == nil { + return content, nil + } + if path == "/index" { + indexErr = err + if !shouldFallbackStatsigMeta(err) { + return "", err + } + continue + } + return "", err + } + if indexErr != nil { + return "", indexErr + } + return "", fmt.Errorf("Grok index 缺少 grok-site-verification") +} + +func shouldFallbackStatsigMeta(err error) bool { + if err == nil { + return false + } + message := err.Error() + return strings.Contains(message, "缺少 grok-site-verification") || strings.Contains(message, "Grok index 返回 ") +} + +func fetchStatsigMetaContentPath(ctx context.Context, baseURL, token string, lease *infraegress.Lease, path string, do func(*http.Request) (*http.Response, error)) (string, error) { requestCtx, cancel := context.WithTimeout(infraegress.WithPhysicalCallStage(ctx, "statsig_meta"), 15*time.Second) defer cancel() - request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/index", nil) + request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+path, nil) if err != nil { return "", err } @@ -287,16 +324,15 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease * request.Header.Set("Sec-Fetch-Mode", "navigate") request.Header.Set("Sec-Fetch-Site", "same-origin") request.Header.Set("Upgrade-Insecure-Requests", "1") - request.Header.Set("User-Agent", lease.UserAgent) - request.Header.Set("Cookie", infraegress.BuildSSOCookie(token, lease.CFCookies)) - response, err := lease.Do(request) + if lease != nil { + request.Header.Set("User-Agent", lease.UserAgent) + request.Header.Set("Cookie", infraegress.BuildSSOCookie(token, lease.CFCookies)) + } + response, err := do(request) if err != nil { return "", err } defer response.Body.Close() - if response.StatusCode < 200 || response.StatusCode >= 300 { - return "", fmt.Errorf("Grok index 返回 %d", response.StatusCode) - } body, err := io.ReadAll(io.LimitReader(response.Body, statsigMetaBodyLimit+1)) if err != nil { return "", err @@ -304,11 +340,18 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease * if len(body) > statsigMetaBodyLimit { return "", fmt.Errorf("Grok index 超过安全上限") } + return statsigMetaFromHTTP(response.StatusCode, body) +} + +func statsigMetaFromHTTP(status int, body []byte) (string, error) { content, err := extractStatsigMetaContent(body) - if err != nil { - return "", err + if err == nil { + return content, nil } - return content, nil + if status < 200 || status >= 300 { + return "", fmt.Errorf("Grok index 返回 %d", status) + } + return "", err } func extractStatsigMetaContent(body []byte) (string, error) { diff --git a/backend/internal/infra/provider/web/statsig_test.go b/backend/internal/infra/provider/web/statsig_test.go index d4c0298f..0ac543d3 100644 --- a/backend/internal/infra/provider/web/statsig_test.go +++ b/backend/internal/infra/provider/web/statsig_test.go @@ -19,6 +19,67 @@ type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) } +func TestStatsigMetaFromHTTPAcceptsIndexNotFoundWithVerification(t *testing.T) { + body := []byte(``) + value, err := statsigMetaFromHTTP(http.StatusNotFound, body) + if err != nil || value != "meta-value" { + t.Fatalf("value=%q err=%v", value, err) + } +} + +func TestStatsigMetaFromHTTPKeepsMissingVerificationErrorOnSuccessStatus(t *testing.T) { + if _, err := statsigMetaFromHTTP(http.StatusOK, []byte(``)); err == nil || !strings.Contains(err.Error(), "缺少 grok-site-verification") { + t.Fatalf("err=%v", err) + } +} + +func TestStatsigMetaFromHTTPPreservesStatusWhenVerificationMissing(t *testing.T) { + if _, err := statsigMetaFromHTTP(http.StatusNotFound, []byte(``)); err == nil || !strings.Contains(err.Error(), "Grok index 返回 404") { + t.Fatalf("err=%v", err) + } +} + +func TestFetchStatsigMetaContentFallsBackToRootWhenIndexHasNoVerification(t *testing.T) { + var paths []string + do := func(request *http.Request) (*http.Response, error) { + paths = append(paths, request.URL.Path) + switch request.URL.Path { + case "/index": + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + case "/": + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + default: + t.Fatalf("unexpected path %q", request.URL.Path) + return nil, nil + } + } + value, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err != nil || value != "root-meta" { + t.Fatalf("value=%q err=%v paths=%v", value, err, paths) + } + if len(paths) != 2 || paths[0] != "/index" || paths[1] != "/" { + t.Fatalf("paths=%v", paths) + } +} + +func TestFetchStatsigMetaContentDoesNotFallbackWhenIndex404HasVerification(t *testing.T) { + var paths []string + do := func(request *http.Request) (*http.Response, error) { + paths = append(paths, request.URL.Path) + if request.URL.Path != "/index" { + t.Fatalf("unexpected fallback to %q", request.URL.Path) + } + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + } + value, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err != nil || value != "index-meta" { + t.Fatalf("value=%q err=%v", value, err) + } + if len(paths) != 1 || paths[0] != "/index" { + t.Fatalf("paths=%v", paths) + } +} + func TestExtractStatsigMetaContentAcceptsCurrentMetaName(t *testing.T) { for _, name := range []string{"grok-site―verification", "grok-site-verification"} { body := []byte(``) From 9316fa3ea49183d297347077cf3ef5df52e55583 Mon Sep 17 00:00:00 2001 From: RIERS <50164130+RIERS@users.noreply.github.com> Date: Thu, 13 Aug 2026 12:16:05 +0800 Subject: [PATCH 04/17] fix(accounts): serialize Build detect item observers DetectBuildAccountsWithProgress invoked itemObserver from batch workers. A lock-free observer could race or drop results; serialize callbacks like progress updates. --- .../application/account/build_detect_test.go | 67 +++++++++++++++++++ .../internal/application/account/service.go | 7 +- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/backend/internal/application/account/build_detect_test.go b/backend/internal/application/account/build_detect_test.go index 898de2cf..9fec90f7 100644 --- a/backend/internal/application/account/build_detect_test.go +++ b/backend/internal/application/account/build_detect_test.go @@ -8,7 +8,11 @@ import ( "io" "net/http" "path/filepath" + "strconv" "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/pkg/batch" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" @@ -288,3 +292,66 @@ func TestDetectBuildAccountsStreamsInvalidOnlyForAll(t *testing.T) { _ = okAccount _ = invalidAccount } + +func TestDetectBuildAccountsSerializesItemObserver(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "detect-observer.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + accessToken, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + repo := relational.NewAccountRepository(database) + const accountCount = 8 + for index := range accountCount { + if _, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "invalid-" + strconv.Itoa(index), UserID: "user-invalid-" + strconv.Itoa(index), + SourceKey: "detect-invalid-" + strconv.Itoa(index), EncryptedAccessToken: accessToken, + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, RefreshPermanent: true, Priority: 1, MaxConcurrent: 1, + }); err != nil { + t.Fatal(err) + } + } + service := NewService(repo, nil, nil, nil, provider.NewRegistry(detectResponsesAdapter{ + status: http.StatusUnauthorized, + }), cipher, nil) + service.SetDetectPool(batch.NewPool(accountCount)) + + started := make(chan struct{}, accountCount) + release := make(chan struct{}) + var items []BuildDetectItemResult + errCh := make(chan error, 1) + go func() { + _, _, detectErr := service.DetectBuildAccountsWithProgress(ctx, nil, true, nil, func(item BuildDetectItemResult) error { + started <- struct{}{} + <-release + items = append(items, item) + return nil + }) + errCh <- detectErr + }() + + deadline := time.After(2 * time.Second) + select { + case <-started: + case <-deadline: + t.Fatal("itemObserver was not invoked") + } + close(release) + if detectErr := <-errCh; detectErr != nil { + t.Fatal(detectErr) + } + if len(items) != accountCount { + t.Fatalf("serialized items = %d, want %d", len(items), accountCount) + } +} diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 62931634..4261c6c7 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -3684,7 +3684,7 @@ func (s *Service) BatchRefreshBilling(ctx context.Context, ids []uint64) (int, i // DetectBuildAccountsWithProgress 对指定或全部 Grok Build 账号发起探测请求;all 与 ids 必须且只能提供一个。 // 该方法同时上报批量进度与单账号明细。 -// itemObserver 在每个账号完成后调用:选中检测会推送全部结果,全量检测仅推送已确认失效账号。 +// itemObserver 在每个账号完成后串行调用:选中检测会推送全部结果,全量检测仅推送已确认失效账号。 func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uint64, all bool, progress BatchProgressObserver, itemObserver BuildDetectItemObserver) (int, int, error) { if all == (len(ids) > 0) { return 0, 0, invalidInput("必须明确选择全部账号或提供非空账号 ID") @@ -3725,7 +3725,10 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin summary, err := batch.ForEachObserved(runCtx, ids, batch.Options{Workers: pool.Limit(), Pool: pool}, func(workCtx context.Context, id uint64) (BuildDetectItemResult, error) { item := s.detectBuildAccount(workCtx, id) if itemObserver != nil && (selectedMode || item.Outcome == BuildDetectOutcomeInvalid) { - if notifyErr := itemObserver(item); notifyErr != nil { + progressMu.Lock() + notifyErr := itemObserver(item) + progressMu.Unlock() + if notifyErr != nil { return item, notifyErr } } From 211aa83634c6bd2c5b2f3a510997eb90bc1c31d7 Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Thu, 13 Aug 2026 13:25:54 +0800 Subject: [PATCH 05/17] feat: add degraded-account monitor to quality guard Surface streaming TPS anomalies by account on the quality-guard page so operators can filter repeat offenders and mute them with the existing account batch API. Classification matches the panel formula: output tokens over generation time, with buffered_burst for short windows. --- backend/internal/application/audit/degrade.go | 331 ++++++++++++++++++ .../application/audit/degrade_test.go | 64 ++++ backend/internal/domain/audit/degrade.go | 36 ++ backend/internal/domain/audit/degrade_test.go | 27 ++ .../relational/audit_repository.go | 62 ++++ backend/internal/repository/audit.go | 26 ++ .../internal/transport/http/audit/handler.go | 100 ++++++ .../transport/http/audit/handler_test.go | 37 ++ .../quality-guard/degrade-accounts-panel.tsx | 262 ++++++++++++++ .../quality-guard/quality-guard-api.ts | 69 +++- .../quality-guard/quality-guard-page.tsx | 13 + frontend/src/shared/i18n/index.ts | 35 +- 12 files changed, 1060 insertions(+), 2 deletions(-) create mode 100644 backend/internal/application/audit/degrade.go create mode 100644 backend/internal/application/audit/degrade_test.go create mode 100644 backend/internal/domain/audit/degrade.go create mode 100644 backend/internal/domain/audit/degrade_test.go create mode 100644 frontend/src/features/quality-guard/degrade-accounts-panel.tsx diff --git a/backend/internal/application/audit/degrade.go b/backend/internal/application/audit/degrade.go new file mode 100644 index 00000000..96758715 --- /dev/null +++ b/backend/internal/application/audit/degrade.go @@ -0,0 +1,331 @@ +package audit + +import ( + "context" + "math" + "sort" + "time" + + auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +const ( + degradeWindow1h = "1h" + degradeWindow6h = "6h" + degradeWindow24h = "24h" + degradeWindow7d = "7d" + degradeEventLimit = 20_000 + degradeRecentEventCap = 80 +) + +type DegradeThresholds struct { + SoftTPS float64 + HardTPS float64 + MinGenMS int64 + MinOut int64 +} + +type DegradeSummary struct { + Window string + GeneratedAt time.Time + Thresholds DegradeThresholds + Totals DegradeTotals + Series []DegradeBucket + Nodes []DegradeNode + Accounts []DegradeAccount + Events []DegradeEventView +} + +type DegradeTotals struct { + Hits int + Accounts int + StillEnabled int + Disabled int + Hard int + Soft int + Burst int + MaxTPS float64 +} + +type DegradeBucket struct { + Label string `json:"label"` + Count int `json:"count"` + Severe int `json:"severe"` +} + +type DegradeNode struct { + Name string `json:"name"` + Hits int `json:"hits"` + Accounts int `json:"accounts"` + MaxTPS float64 `json:"maxTPS"` +} + +type DegradeAccount struct { + ID uint64 + Name string + Email string + Hits int + MaxTPS float64 + Classes map[string]int + Nodes []string + Last time.Time + Enabled bool + BFS int + Found bool +} + +type DegradeEventView struct { + ID uint64 + RequestID string + AccountID *uint64 + AccountName string + NodeName string + OutputTokens int64 + TPS float64 + Class string + CreatedAt time.Time + Model string +} + +func (s *Service) DegradeSummary(ctx context.Context, window string, thresholds DegradeThresholds) (DegradeSummary, error) { + window, start, end, err := resolveDegradeWindow(window, s.now().UTC()) + if err != nil { + return DegradeSummary{}, err + } + thresholds = normalizeDegradeThresholds(thresholds) + events, err := s.audits.ListDegradeEvents(ctx, repository.DegradeEventQuery{ + Start: start, End: end, MinOutputTokens: thresholds.MinOut, Limit: degradeEventLimit, + }) + if err != nil { + return DegradeSummary{}, err + } + return buildDegradeSummary(window, end, thresholds, events), nil +} + +func resolveDegradeWindow(value string, now time.Time) (string, time.Time, time.Time, error) { + if value == "" { + value = degradeWindow24h + } + var duration time.Duration + switch value { + case degradeWindow1h: + duration = time.Hour + case degradeWindow6h: + duration = 6 * time.Hour + case degradeWindow24h: + duration = 24 * time.Hour + case degradeWindow7d: + duration = 7 * 24 * time.Hour + default: + return "", time.Time{}, time.Time{}, ErrInvalidPeriod + } + return value, now.Add(-duration), now, nil +} + +func normalizeDegradeThresholds(value DegradeThresholds) DegradeThresholds { + if value.SoftTPS <= 0 || math.IsNaN(value.SoftTPS) || math.IsInf(value.SoftTPS, 0) { + value.SoftTPS = auditdomain.DefaultDegradeSoftTPS + } + if value.HardTPS <= 0 || math.IsNaN(value.HardTPS) || math.IsInf(value.HardTPS, 0) { + value.HardTPS = auditdomain.DefaultDegradeHardTPS + } + if value.SoftTPS >= value.HardTPS { + value.SoftTPS = auditdomain.DefaultDegradeSoftTPS + value.HardTPS = auditdomain.DefaultDegradeHardTPS + } + if value.MinGenMS <= 0 { + value.MinGenMS = auditdomain.DefaultDegradeMinGenMS + } + if value.MinOut <= 0 { + value.MinOut = auditdomain.DefaultDegradeMinOutput + } + return value +} + +func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresholds, events []repository.DegradeEvent) DegradeSummary { + type accAgg struct { + hits int + maxTPS float64 + classes map[string]int + nodes map[string]struct{} + last time.Time + name string + email string + enabled bool + found bool + bfs int + } + type nodeAgg struct { + hits int + accounts map[uint64]struct{} + maxTPS float64 + } + accounts := map[uint64]*accAgg{} + nodes := map[string]*nodeAgg{} + classCounts := map[string]int{} + var classified []DegradeEventView + var maxTPS float64 + + for _, event := range events { + class, tps, _ := auditdomain.ClassifyOutputSpeed(event.OutputTokens, event.FirstTokenMS, event.DurationMS, thresholds.SoftTPS, thresholds.HardTPS, thresholds.MinGenMS) + if class == "" { + continue + } + classCounts[class]++ + if tps > maxTPS { + maxTPS = tps + } + nodeName := event.EgressNodeName + if nodeName == "" { + nodeName = "?" + } + classified = append(classified, DegradeEventView{ + ID: event.ID, RequestID: event.RequestID, AccountID: event.AccountID, AccountName: event.AccountName, + NodeName: nodeName, OutputTokens: event.OutputTokens, TPS: math.Round(tps*100) / 100, Class: class, + CreatedAt: event.CreatedAt, Model: event.Model, + }) + if event.AccountID == nil || *event.AccountID == 0 { + continue + } + id := *event.AccountID + rec := accounts[id] + if rec == nil { + rec = &accAgg{classes: map[string]int{}, nodes: map[string]struct{}{}} + accounts[id] = rec + } + rec.hits++ + if tps > rec.maxTPS { + rec.maxTPS = tps + } + rec.classes[class]++ + rec.nodes[nodeName] = struct{}{} + if event.CreatedAt.After(rec.last) { + rec.last = event.CreatedAt + rec.name = event.AccountName + } + if rec.name == "" { + rec.name = event.AccountName + } + if event.Email != "" { + rec.email = event.Email + } + if event.Enabled != nil { + rec.enabled = *event.Enabled + rec.found = true + } + if event.BuildBotFlagSource > rec.bfs { + rec.bfs = event.BuildBotFlagSource + } + nd := nodes[nodeName] + if nd == nil { + nd = &nodeAgg{accounts: map[uint64]struct{}{}} + nodes[nodeName] = nd + } + nd.hits++ + nd.accounts[id] = struct{}{} + if tps > nd.maxTPS { + nd.maxTPS = tps + } + } + + accountViews := make([]DegradeAccount, 0, len(accounts)) + enabled, disabled := 0, 0 + for id, rec := range accounts { + if rec.found && rec.enabled { + enabled++ + } else { + disabled++ + } + nodeNames := make([]string, 0, len(rec.nodes)) + for name := range rec.nodes { + nodeNames = append(nodeNames, name) + } + sort.Strings(nodeNames) + email := rec.email + if email == "" { + email = rec.name + } + accountViews = append(accountViews, DegradeAccount{ + ID: id, Name: rec.name, Email: email, Hits: rec.hits, MaxTPS: math.Round(rec.maxTPS*10) / 10, + Classes: rec.classes, Nodes: nodeNames, Last: rec.last, Enabled: rec.found && rec.enabled, BFS: rec.bfs, Found: rec.found, + }) + } + sort.Slice(accountViews, func(i, j int) bool { + if accountViews[i].Hits != accountViews[j].Hits { + return accountViews[i].Hits > accountViews[j].Hits + } + return accountViews[i].MaxTPS > accountViews[j].MaxTPS + }) + + nodeViews := make([]DegradeNode, 0, len(nodes)) + for name, rec := range nodes { + nodeViews = append(nodeViews, DegradeNode{Name: name, Hits: rec.hits, Accounts: len(rec.accounts), MaxTPS: math.Round(rec.maxTPS*10) / 10}) + } + sort.Slice(nodeViews, func(i, j int) bool { return nodeViews[i].Hits > nodeViews[j].Hits }) + + recent := classified + if len(recent) > degradeRecentEventCap { + recent = recent[:degradeRecentEventCap] + } + + return DegradeSummary{ + Window: window, GeneratedAt: now, Thresholds: thresholds, + Totals: DegradeTotals{ + Hits: len(classified), Accounts: len(accounts), StillEnabled: enabled, Disabled: disabled, + Hard: classCounts[auditdomain.DegradeClassHard], Soft: classCounts[auditdomain.DegradeClassSoft], + Burst: classCounts[auditdomain.DegradeClassBurst], MaxTPS: maxTPS, + }, + Series: bucketDegradeSeries(classified, window, now), + Nodes: nodeViews, Accounts: accountViews, Events: recent, + } +} + +func bucketDegradeSeries(events []DegradeEventView, window string, now time.Time) []DegradeBucket { + var step time.Duration + var start time.Time + var label func(time.Time) string + switch window { + case degradeWindow7d: + step = 2 * time.Hour + start = now.Add(-7 * 24 * time.Hour) + label = func(t time.Time) string { return t.Format("01-02 15:00") } + case degradeWindow24h: + step = time.Hour + start = now.Add(-24 * time.Hour) + label = func(t time.Time) string { return t.Format("15:00") } + case degradeWindow6h: + step = 20 * time.Minute + start = now.Add(-6 * time.Hour) + label = func(t time.Time) string { return t.Format("15:04") } + default: + step = 5 * time.Minute + start = now.Add(-time.Hour) + label = func(t time.Time) string { return t.Format("15:04") } + } + var buckets []time.Time + for cursor := start; cursor.Before(now); cursor = cursor.Add(step) { + buckets = append(buckets, cursor) + } + if len(buckets) == 0 { + return nil + } + counts := make([]int, len(buckets)) + severe := make([]int, len(buckets)) + stepSeconds := step.Seconds() + for _, event := range events { + idx := int(event.CreatedAt.Sub(start).Seconds() / stepSeconds) + if idx < 0 || idx >= len(counts) { + continue + } + counts[idx]++ + if event.Class == auditdomain.DegradeClassHard || event.Class == auditdomain.DegradeClassBurst { + severe[idx]++ + } + } + out := make([]DegradeBucket, len(buckets)) + for i, bucket := range buckets { + out[i] = DegradeBucket{Label: label(bucket), Count: counts[i], Severe: severe[i]} + } + return out +} diff --git a/backend/internal/application/audit/degrade_test.go b/backend/internal/application/audit/degrade_test.go new file mode 100644 index 00000000..24d40fe7 --- /dev/null +++ b/backend/internal/application/audit/degrade_test.go @@ -0,0 +1,64 @@ +package audit + +import ( + "context" + "log/slog" + "path/filepath" + "testing" + "time" + + auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" +) + +func TestDegradeSummaryClassifiesStreamingAnomalies(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + accountID := uint64(7) + records := []auditdomain.Record{ + {RequestID: "hard-1", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, AccountName: "hot", EgressNodeName: "node-a", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)}, + {RequestID: "quality_skip_me", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)}, + {RequestID: "non-stream", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: false, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)}, + } + if err := repo.CreateBatch(ctx, records); err != nil { + t.Fatal(err) + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}) + if err != nil { + t.Fatal(err) + } + if summary.Totals.Hits != 1 || summary.Totals.Accounts != 1 || summary.Totals.Hard != 1 { + t.Fatalf("totals = %#v", summary.Totals) + } + if len(summary.Accounts) != 1 || summary.Accounts[0].ID != 7 || summary.Accounts[0].Hits != 1 { + t.Fatalf("accounts = %#v", summary.Accounts) + } +} + +func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-window.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second) + if _, err := service.DegradeSummary(ctx, "3h", DegradeThresholds{}); err != ErrInvalidPeriod { + t.Fatalf("error = %v", err) + } +} diff --git a/backend/internal/domain/audit/degrade.go b/backend/internal/domain/audit/degrade.go new file mode 100644 index 00000000..f1b57113 --- /dev/null +++ b/backend/internal/domain/audit/degrade.go @@ -0,0 +1,36 @@ +package audit + +const ( + DegradeClassBurst = "buffered_burst" + DegradeClassSoft = "soft_tps" + DegradeClassHard = "hard_tps" +) + +const ( + DefaultDegradeSoftTPS = 500.0 + DefaultDegradeHardTPS = 1000.0 + DefaultDegradeMinGenMS = int64(1000) + DefaultDegradeMinOutput = int64(32) +) + +// ClassifyOutputSpeed matches the quality-guard panel formula: +// output tokens / (durationMs - firstTokenMs). Short generation windows with +// a soft-or-higher rate are buffered_burst; otherwise the hard and soft +// thresholds apply in that order. +func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64) (class string, tps float64, genMS int64) { + genMS = durationMS - firstTokenMS + if genMS <= 0 || outputTokens <= 0 { + return "", 0, genMS + } + tps = float64(outputTokens) * 1000 / float64(genMS) + if minGenMS > 0 && genMS < minGenMS && tps >= softTPS { + return DegradeClassBurst, tps, genMS + } + if tps >= hardTPS { + return DegradeClassHard, tps, genMS + } + if tps >= softTPS { + return DegradeClassSoft, tps, genMS + } + return "", tps, genMS +} diff --git a/backend/internal/domain/audit/degrade_test.go b/backend/internal/domain/audit/degrade_test.go new file mode 100644 index 00000000..24ac8c81 --- /dev/null +++ b/backend/internal/domain/audit/degrade_test.go @@ -0,0 +1,27 @@ +package audit + +import "testing" + +func TestClassifyOutputSpeed(t *testing.T) { + tests := []struct { + name string + output, first, duration int64 + soft, hard float64 + minGen int64 + wantClass string + }{ + {name: "hard", output: 2000, first: 200, duration: 1200, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard}, + {name: "soft", output: 600, first: 200, duration: 1400, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassSoft}, + {name: "burst short window", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassBurst}, + {name: "healthy", output: 100, first: 200, duration: 2200, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, + {name: "zero generation", output: 100, first: 500, duration: 500, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen) + if class != test.wantClass { + t.Fatalf("class = %q, want %q", class, test.wantClass) + } + }) + } +} diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 820824e3..6b2e8cde 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -683,6 +683,68 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS return result, nil } +const degradeEventScanLimit = 20_000 + +type degradeEventRow struct { + ID uint64 `gorm:"column:id"` + RequestID string `gorm:"column:request_id"` + AccountID *uint64 `gorm:"column:account_id"` + AccountName string `gorm:"column:account_name"` + Email string `gorm:"column:email"` + Enabled *bool `gorm:"column:enabled"` + BuildBotFlagSource int `gorm:"column:build_bot_flag_source"` + EgressNodeID *uint64 `gorm:"column:egress_node_id"` + EgressNodeName string `gorm:"column:egress_node_name"` + OutputTokens int64 `gorm:"column:output_tokens"` + FirstTokenMS int64 `gorm:"column:first_token_ms"` + DurationMS int64 `gorm:"column:duration_ms"` + CreatedAt time.Time `gorm:"column:created_at"` + Model string `gorm:"column:model_upstream_model"` +} + +func (r *AuditRepository) ListDegradeEvents(ctx context.Context, input repository.DegradeEventQuery) ([]repository.DegradeEvent, error) { + limit := input.Limit + if limit <= 0 || limit > degradeEventScanLimit { + limit = degradeEventScanLimit + } + minOut := input.MinOutputTokens + if minOut <= 0 { + minOut = audit.DefaultDegradeMinOutput + } + var rows []degradeEventRow + query := r.db.db.WithContext(ctx).Table("request_audits AS a"). + Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.first_token_ms, a.duration_ms, a.created_at, a.model_upstream_model, p.email, p.enabled, COALESCE(c.build_bot_flag_source, 0) AS build_bot_flag_source"). + Joins("LEFT JOIN provider_accounts p ON p.id = a.account_id"). + Joins("LEFT JOIN account_credentials c ON c.account_id = a.account_id"). + Where("a.provider = ?", "grok_build"). + Where("a.streaming = ?", true). + Where(auditSuccessPredicate). + Where("a.output_tokens >= ?", minOut). + Where("a.first_token_ms IS NOT NULL"). + Where("a.duration_ms > a.first_token_ms"). + Where("a.request_id NOT LIKE ?", "quality_%") + if !input.Start.IsZero() { + query = query.Where("a.created_at >= ?", input.Start) + } + if !input.End.IsZero() { + query = query.Where("a.created_at < ?", input.End) + } + if err := query.Order("a.created_at DESC").Limit(limit).Scan(&rows).Error; err != nil { + return nil, err + } + out := make([]repository.DegradeEvent, 0, len(rows)) + for _, row := range rows { + out = append(out, repository.DegradeEvent{ + ID: row.ID, RequestID: row.RequestID, AccountID: row.AccountID, AccountName: row.AccountName, + Email: row.Email, Enabled: row.Enabled, BuildBotFlagSource: row.BuildBotFlagSource, + EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, + OutputTokens: row.OutputTokens, FirstTokenMS: row.FirstTokenMS, DurationMS: row.DurationMS, + CreatedAt: row.CreatedAt, Model: row.Model, + }) + } + return out, nil +} + func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter repository.AuditListFilter) *gorm.DB { if value := strings.TrimSpace(search); value != "" { pattern := "%" + strings.ToLower(value) + "%" diff --git a/backend/internal/repository/audit.go b/backend/internal/repository/audit.go index a29e56d0..4be019aa 100644 --- a/backend/internal/repository/audit.go +++ b/backend/internal/repository/audit.go @@ -16,4 +16,30 @@ type AuditRepository interface { ListCursor(ctx context.Context, query AuditCursorQuery) ([]audit.Record, bool, error) Summarize(ctx context.Context, query AuditSummaryQuery) (audit.Summary, error) SumTokensByAccountsSince(ctx context.Context, accountIDs []uint64, since time.Time) (map[uint64]int64, error) + ListDegradeEvents(ctx context.Context, query DegradeEventQuery) ([]DegradeEvent, error) +} + +type DegradeEventQuery struct { + Start time.Time + End time.Time + MinOutputTokens int64 + Limit int +} + +// DegradeEvent is a slim streaming-success audit plus optional account flags. +type DegradeEvent struct { + ID uint64 + RequestID string + AccountID *uint64 + AccountName string + Email string + Enabled *bool + BuildBotFlagSource int + EgressNodeID *uint64 + EgressNodeName string + OutputTokens int64 + FirstTokenMS int64 + DurationMS int64 + CreatedAt time.Time + Model string } diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index d3dd2f0b..ccdb4500 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -29,6 +29,7 @@ func NewQualityGuardHandler(service *auditapp.Service, clientKeyID uint64) *Hand func (h *Handler) Register(router *gin.RouterGroup) { router.GET("/request-audits", h.list) router.GET("/request-audits/summary", h.summary) + router.GET("/request-audits/degrade-accounts", h.degradeAccounts) router.GET("/request-audits/:id", h.get) } @@ -333,6 +334,105 @@ func (h *Handler) summary(c *gin.Context) { }) } +func (h *Handler) degradeAccounts(c *gin.Context) { + softTPS, _ := strconv.ParseFloat(c.Query("softTPS"), 64) + hardTPS, _ := strconv.ParseFloat(c.Query("hardTPS"), 64) + result, err := h.service.DegradeSummary(c.Request.Context(), c.DefaultQuery("window", "24h"), auditapp.DegradeThresholds{SoftTPS: softTPS, HardTPS: hardTPS}) + if errors.Is(err, auditapp.ErrInvalidPeriod) { + response.Error(c, http.StatusBadRequest, "invalidAuditPeriod", "window 仅支持 1h、6h、24h、7d") + return + } + if err != nil { + response.Error(c, http.StatusInternalServerError, "auditDegradeFailed", "读取降智账号失败") + return + } + accounts := make([]degradeAccountResponse, 0, len(result.Accounts)) + for _, account := range result.Accounts { + accounts = append(accounts, degradeAccountResponse{ + ID: strconv.FormatUint(account.ID, 10), Name: account.Name, Email: account.Email, Hits: account.Hits, + MaxTPS: account.MaxTPS, Classes: account.Classes, Nodes: account.Nodes, Last: account.Last, + Enabled: account.Enabled, BFS: account.BFS, + }) + } + events := make([]degradeEventResponse, 0, len(result.Events)) + for _, event := range result.Events { + item := degradeEventResponse{ + ID: strconv.FormatUint(event.ID, 10), RequestID: event.RequestID, AccountName: event.AccountName, + NodeName: event.NodeName, OutputTokens: event.OutputTokens, TPS: event.TPS, Class: event.Class, + CreatedAt: event.CreatedAt, Model: event.Model, + } + if event.AccountID != nil { + id := strconv.FormatUint(*event.AccountID, 10) + item.AccountID = &id + } + events = append(events, item) + } + response.Success(c, http.StatusOK, degradeSummaryResponse{ + Window: result.Window, GeneratedAt: result.GeneratedAt, + Thresholds: degradeThresholdsResponse{SoftTPS: result.Thresholds.SoftTPS, HardTPS: result.Thresholds.HardTPS, MinGenMS: result.Thresholds.MinGenMS, MinOut: result.Thresholds.MinOut}, + Totals: degradeTotalsResponse{ + Hits: result.Totals.Hits, Accounts: result.Totals.Accounts, StillEnabled: result.Totals.StillEnabled, + Disabled: result.Totals.Disabled, Hard: result.Totals.Hard, Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS, + }, + Series: result.Series, Nodes: result.Nodes, Accounts: accounts, Events: events, + }) +} + +type degradeSummaryResponse struct { + Window string `json:"window"` + GeneratedAt time.Time `json:"generatedAt"` + Thresholds degradeThresholdsResponse `json:"thresholds"` + Totals degradeTotalsResponse `json:"totals"` + Series []auditapp.DegradeBucket `json:"series"` + Nodes []auditapp.DegradeNode `json:"nodes"` + Accounts []degradeAccountResponse `json:"accounts"` + Events []degradeEventResponse `json:"events"` +} + +type degradeThresholdsResponse struct { + SoftTPS float64 `json:"softTPS"` + HardTPS float64 `json:"hardTPS"` + MinGenMS int64 `json:"minGenMs"` + MinOut int64 `json:"minOutputTokens"` +} + +type degradeTotalsResponse struct { + Hits int `json:"hits"` + Accounts int `json:"accounts"` + StillEnabled int `json:"stillEnabled"` + Disabled int `json:"disabled"` + Hard int `json:"hard"` + Soft int `json:"soft"` + Burst int `json:"burst"` + MaxTPS float64 `json:"maxTPS"` +} + +type degradeAccountResponse struct { + ID string `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + Hits int `json:"hits"` + MaxTPS float64 `json:"maxTPS"` + Classes map[string]int `json:"classes"` + Nodes []string `json:"nodes"` + Last time.Time `json:"last"` + Enabled bool `json:"enabled"` + BFS int `json:"bfs"` +} + +type degradeEventResponse struct { + ID string `json:"id"` + RequestID string `json:"requestId"` + AccountID *string `json:"accountId,omitempty"` + AccountName string `json:"accountName"` + NodeName string `json:"nodeName"` + OutputTokens int64 `json:"outputTokens"` + TPS float64 `json:"tps"` + Class string `json:"class"` + CreatedAt time.Time `json:"createdAt"` + Model string `json:"model"` +} + func newListFilter(c *gin.Context) auditapp.ListFilter { return auditapp.ListFilter{ Model: c.Query("model"), Status: c.Query("status"), Mode: c.Query("mode"), diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go index 0a9a6822..7e139f09 100644 --- a/backend/internal/transport/http/audit/handler_test.go +++ b/backend/internal/transport/http/audit/handler_test.go @@ -163,3 +163,40 @@ func TestAuditResponseExplainsBillingWithoutChangingStoredTotal(t *testing.T) { t.Fatalf("historical billing = %#v", historical.Billing) } } + +func TestDegradeAccountsListsHardHitsAndRejectsUnknownWindow(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-handler.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + accountID := uint64(11) + if err := repo.Create(ctx, auditdomain.Record{ + RequestID: "degrade-hard", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, AccountName: "noisy", + EgressNodeName: "edge-1", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Minute), + }); err != nil { + t.Fatal(err) + } + router := gin.New() + NewHandler(auditapp.NewService(repo, slog.Default(), 8, 4, time.Second)).Register(router.Group("/api/admin/v1")) + + ok := httptest.NewRecorder() + router.ServeHTTP(ok, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=24h&softTPS=500&hardTPS=1000", nil)) + if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"id":"11"`) || !strings.Contains(ok.Body.String(), `"hard":1`) { + t.Fatalf("status=%d body=%s", ok.Code, ok.Body.String()) + } + + bad := httptest.NewRecorder() + router.ServeHTTP(bad, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=3h", nil)) + if bad.Code != http.StatusBadRequest || !strings.Contains(bad.Body.String(), "invalidAuditPeriod") { + t.Fatalf("bad window status=%d body=%s", bad.Code, bad.Body.String()) + } +} diff --git a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx new file mode 100644 index 00000000..e8d2da7b --- /dev/null +++ b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx @@ -0,0 +1,262 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { AlertTriangle, Gauge, PowerOff, RefreshCw, Search, Users } from "lucide-react"; +import { useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { updateAccountsEnabled } from "@/features/accounts/accounts-api"; +import { getDegradeAccounts, type DegradeAccountDTO, type DegradeClass, type DegradeSummaryDTO, type DegradeWindow } from "@/features/quality-guard/quality-guard-api"; +import { EmptyState, ErrorState } from "@/shared/components/data-state"; +import { cn } from "@/shared/lib/cn"; +import { formatCompactDateTime } from "@/shared/lib/format"; + +const MUTE_TOAST_ID = "quality-guard-degrade-mute"; + +export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; hardTPS?: number }) { + const { t, i18n } = useTranslation(); + const queryClient = useQueryClient(); + const [window, setWindow] = useState("24h"); + const [search, setSearch] = useState(""); + const [status, setStatus] = useState<"all" | "on" | "off">("all"); + const [cls, setCls] = useState<"all" | DegradeClass>("all"); + const [hitsMin, setHitsMin] = useState(1); + const [selected, setSelected] = useState>(() => new Set()); + + const query = useQuery({ + queryKey: ["quality-guard-degrade-accounts", window, softTPS, hardTPS], + queryFn: () => getDegradeAccounts({ window, softTPS, hardTPS }), + refetchInterval: 15_000, + }); + + const data = query.data; + const rows = useMemo(() => filterAccounts(data, { search, status, cls, hitsMin }), [data, search, status, cls, hitsMin]); + const selectable = rows.filter((account) => account.enabled); + const selectedEnabled = selectable.filter((account) => selected.has(account.id)); + const allSelected = selectable.length > 0 && selectedEnabled.length === selectable.length; + + const muteMutation = useMutation({ + mutationFn: (ids: string[]) => updateAccountsEnabled(ids, false, "grok_build"), + onMutate: () => toast.loading(t("qualityGuard.degrade.muting"), { id: MUTE_TOAST_ID }), + onSuccess: (_, ids) => { + setSelected(new Set()); + void queryClient.invalidateQueries({ queryKey: ["quality-guard-degrade-accounts"] }); + void queryClient.invalidateQueries({ queryKey: ["accounts"] }); + toast.success(t("qualityGuard.degrade.muted", { count: ids.length }), { id: MUTE_TOAST_ID }); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.muteFailed"), { id: MUTE_TOAST_ID }), + }); + + const toggleAll = (checked: boolean) => { + setSelected((current) => { + const next = new Set(current); + selectable.forEach((account) => { + if (checked) next.add(account.id); + else next.delete(account.id); + }); + return next; + }); + }; + + if (query.isError && !data) return void query.refetch()} />; + if (!data) return null; + + return ( +
+
+ + + + = data.thresholds.hardTPS ? "bad" : undefined} /> +
+ +
+ + +
+ +
+
+
+

{t("qualityGuard.degrade.accountsTitle")}

+

+ {hitsMin > 1 + ? t("qualityGuard.degrade.accountsHintFiltered", { shown: rows.length, total: data.accounts.length, min: hitsMin }) + : t("qualityGuard.degrade.accountsHint", { shown: rows.length, total: data.accounts.length })} +

+
+
+
+ + setSearch(event.target.value)} placeholder={t("qualityGuard.degrade.search")} /> +
+ { setSelected(new Set()); setWindow(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> + setStatus(value as "all" | "on" | "off")} items={[["all", t("qualityGuard.degrade.statusAll")], ["on", t("qualityGuard.degrade.statusOn")], ["off", t("qualityGuard.degrade.statusOff")]]} /> + setCls(value as "all" | DegradeClass)} items={[["all", t("qualityGuard.degrade.classAll")], ["buffered_burst", "burst"], ["soft_tps", "soft"], ["hard_tps", "hard"]]} /> + setHitsMin(Number(value))} items={[["1", t("qualityGuard.degrade.hitsAll")], ["2", t("qualityGuard.degrade.hitsMin", { count: 2 })], ["3", t("qualityGuard.degrade.hitsMin", { count: 3 })], ["5", t("qualityGuard.degrade.hitsMin", { count: 5 })], ["10", t("qualityGuard.degrade.hitsMin", { count: 10 })]]} /> + + +
+
+
+ + + + 0 ? "indeterminate" : false} disabled={selectable.length === 0} onCheckedChange={(checked) => toggleAll(checked === true)} aria-label={t("common.selectPage")} /> + {t("qualityGuard.degrade.account")} + {t("qualityGuard.degrade.status")} + {t("qualityGuard.degrade.hitCount")} + {t("qualityGuard.outputTPS")} + {t("qualityGuard.degrade.class")} + {t("qualityGuard.node")} + {t("qualityGuard.lastObserved")} + + + + {rows.length === 0 ? ( + + ) : rows.map((account) => ( + + setSelected((current) => { + const next = new Set(current); + if (checked === true) next.add(account.id); + else next.delete(account.id); + return next; + })} /> + +
#{account.id}
+
{account.email || account.name || "-"}
+
+ + {account.enabled ? {t("qualityGuard.degrade.scheduling")} : {t("qualityGuard.degrade.mutedStatus")}} + {account.bfs ? bfs {account.bfs} : null} + + {account.hits} + = data.thresholds.hardTPS ? "text-destructive" : account.maxTPS >= data.thresholds.softTPS ? "text-amber-600 dark:text-amber-400" : "")}>{account.maxTPS} + {classSummary(account.classes)} + {account.nodes.join(" · ") || "-"} + {account.last ? formatCompactDateTime(account.last, i18n.language) : "-"} +
+ ))} +
+
+
+
+ +
+
+

{t("qualityGuard.degrade.events")}

+

{t("qualityGuard.degrade.eventsHelp")}

+
+
+ {data.events.length === 0 ? : data.events.map((event) => ( +
+
{formatCompactDateTime(event.createdAt, i18n.language)}
+
#{event.accountId ?? "-"} {event.accountName} · {event.nodeName} · out {event.outputTokens} · {event.requestId}
+
{classBadge(event.class)}{event.tps}
+
+ ))} +
+
+
+ ); +} + +function filterAccounts(data: DegradeSummaryDTO | undefined, filters: { search: string; status: "all" | "on" | "off"; cls: "all" | DegradeClass; hitsMin: number }) { + if (!data) return []; + const search = filters.search.trim().toLowerCase(); + return data.accounts.filter((account) => { + if (account.hits < filters.hitsMin) return false; + if (filters.status === "on" && !account.enabled) return false; + if (filters.status === "off" && account.enabled) return false; + if (filters.cls !== "all" && (account.classes[filters.cls] ?? 0) <= 0) return false; + if (search && !`${account.id} ${account.email} ${account.name}`.toLowerCase().includes(search)) return false; + return true; + }); +} + +function classSummary(classes: DegradeAccountDTO["classes"]) { + return [ + classes.buffered_burst ? `burst ${classes.buffered_burst}` : "", + classes.soft_tps ? `soft ${classes.soft_tps}` : "", + classes.hard_tps ? `hard ${classes.hard_tps}` : "", + ].filter(Boolean).join(" · ") || "-"; +} + +function classBadge(cls: DegradeClass) { + if (cls === "hard_tps") return hard; + if (cls === "buffered_burst") return burst; + return soft; +} + +function FilterSelect({ value, onChange, items }: { value: string; onChange: (value: string) => void; items: string[][] }) { + return ( + + ); +} + +function Metric({ icon: Icon, label, value, detail, tone }: { icon: typeof AlertTriangle; label: string; value: string; detail: string; tone?: "good" | "bad" }) { + return ( +
+ +
+

{label}

+

{value}

+

{detail}

+
+
+ ); +} + +function SeriesChart({ series, empty, title }: { series: DegradeSummaryDTO["series"]; empty: string; title: string }) { + const max = Math.max(1, ...series.map((item) => item.count)); + return ( +
+

{title}

+
+ {series.length === 0 ?

{empty}

: series.map((item) => ( +
+
0 && item.severe >= item.count * 0.5 ? "bg-destructive" : "bg-amber-500/80")} style={{ height: `${Math.max(2, Math.round(item.count / max * 100))}%` }} /> +
{item.label}
+
+ ))} +
+
+ ); +} + +function NodeList({ nodes, empty, title }: { nodes: DegradeSummaryDTO["nodes"]; empty: string; title: string }) { + const max = Math.max(1, ...nodes.map((node) => node.hits)); + return ( +
+

{title}

+
+ {nodes.length === 0 ?

{empty}

: nodes.map((node) => ( +
+
+
{node.name}
+
+
+ {node.hits} / {node.accounts} + {node.maxTPS} +
+ ))} +
+
+ ); +} diff --git a/frontend/src/features/quality-guard/quality-guard-api.ts b/frontend/src/features/quality-guard/quality-guard-api.ts index 19223564..0ddffa14 100644 --- a/frontend/src/features/quality-guard/quality-guard-api.ts +++ b/frontend/src/features/quality-guard/quality-guard-api.ts @@ -1,5 +1,5 @@ import { apiRequest } from "@/shared/api/client"; -import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder"; +import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isObject, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder"; export type QualityGuardPolicy = { mode: "active" | "passive" | "hybrid"; @@ -151,3 +151,70 @@ export function runQualityTest(nodeId: string, status: QualityGuardStatus): Prom export function updateQualityGuardPolicy(policy: QualityGuardPolicy): Promise<{ saved: boolean }> { return apiRequest("/api/admin/v1/egress-quality-guard/config", { method: "PUT", body: policy }, createObjectDecoder("quality guard config update", { saved: isBoolean })); } + +export type DegradeWindow = "1h" | "6h" | "24h" | "7d"; +export type DegradeClass = "buffered_burst" | "soft_tps" | "hard_tps"; + +export type DegradeAccountDTO = { + id: string; + name: string; + email: string; + hits: number; + maxTPS: number; + classes: Partial>; + nodes: string[]; + last: string; + enabled: boolean; + bfs: number; +}; + +export type DegradeEventDTO = { + id: string; + requestId: string; + accountId?: string; + accountName: string; + nodeName: string; + outputTokens: number; + tps: number; + class: DegradeClass; + createdAt: string; + model: string; +}; + +export type DegradeSummaryDTO = { + window: DegradeWindow; + generatedAt: string; + thresholds: { softTPS: number; hardTPS: number; minGenMs: number; minOutputTokens: number }; + totals: { hits: number; accounts: number; stillEnabled: number; disabled: number; hard: number; soft: number; burst: number; maxTPS: number }; + series: { label: string; count: number; severe: number }[]; + nodes: { name: string; hits: number; accounts: number; maxTPS: number }[]; + accounts: DegradeAccountDTO[]; + events: DegradeEventDTO[]; +}; + +const degradeClassValidator = isOneOf("buffered_burst", "soft_tps", "hard_tps"); + +const decodeDegradeSummary = createObjectDecoder("degrade accounts", { + window: isOneOf("1h", "6h", "24h", "7d"), + generatedAt: isString, + thresholds: hasShape({ softTPS: isNumber, hardTPS: isNumber, minGenMs: isNumber, minOutputTokens: isNumber }), + totals: hasShape({ hits: isNumber, accounts: isNumber, stillEnabled: isNumber, disabled: isNumber, hard: isNumber, soft: isNumber, burst: isNumber, maxTPS: isNumber }), + series: isArrayOf(hasShape({ label: isString, count: isNumber, severe: isNumber })), + nodes: isArrayOf(hasShape({ name: isString, hits: isNumber, accounts: isNumber, maxTPS: isNumber })), + accounts: isArrayOf(hasShape({ + id: isString, name: isString, email: isString, hits: isNumber, maxTPS: isNumber, + classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, bfs: isNumber, + })), + events: isArrayOf(hasShape({ + id: isString, requestId: isString, accountId: isOptional(isString), accountName: isString, + nodeName: isString, outputTokens: isNumber, tps: isNumber, class: degradeClassValidator, + createdAt: isString, model: isString, + })), +}); + +export function getDegradeAccounts(input: { window: DegradeWindow; softTPS?: number; hardTPS?: number }): Promise { + const query = new URLSearchParams({ window: input.window }); + if (input.softTPS) query.set("softTPS", String(input.softTPS)); + if (input.hardTPS) query.set("hardTPS", String(input.hardTPS)); + return apiRequest(`/api/admin/v1/request-audits/degrade-accounts?${query}`, {}, decodeDegradeSummary); +} diff --git a/frontend/src/features/quality-guard/quality-guard-page.tsx b/frontend/src/features/quality-guard/quality-guard-page.tsx index 65551e62..ce682c16 100644 --- a/frontend/src/features/quality-guard/quality-guard-page.tsx +++ b/frontend/src/features/quality-guard/quality-guard-page.tsx @@ -18,6 +18,8 @@ import { Label } from "@/components/ui/label"; import { Spinner } from "@/components/ui/spinner"; import { Switch } from "@/components/ui/switch"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { DegradeAccountsPanel } from "@/features/quality-guard/degrade-accounts-panel"; import { getQualityGuardStatus, runQualityTest, updateQualityGuardPolicy, type QualityGuardEvent, type QualityGuardNodeState, type QualityGuardPolicy, type QualityGuardStatistics, type QualityGuardStatus, type QualityTestResult } from "@/features/quality-guard/quality-guard-api"; import { createEgressNode, deleteEgressNodes, listAllEgressNodes, updateEgressNode, updateEgressNodesEnabled, type EgressNodeDTO, type EgressNodeInput } from "@/features/settings/settings-api"; import { ErrorState } from "@/shared/components/data-state"; @@ -159,6 +161,15 @@ export function QualityGuardPage() { )} /> + + + {t("qualityGuard.nodesTab")} + {t("qualityGuard.degrade.tab")} + + + + + {!status?.available ? : ( <>
@@ -224,6 +235,8 @@ export function QualityGuardPage() { )} + + ); } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..88fea127 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -443,6 +443,22 @@ const resources = { reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", passive_hard_tps: "请求速度超过硬阈值", passive_soft_tps: "请求速度连续超过软阈值", quality_probe_healthy: "模型质量检测恢复正常", expected_marker_missing: "响应标记缺失", insufficient_output_tokens: "输出 Token 不足", insufficient_visible_tokens: "可见 Token 不足", insufficient_generation_window: "有效生成窗口不足", probe_errors: "主动检测连续失败", probe_no_account: "暂无可调度账号,已延后复测", recovery_probe_error: "恢复检测失败", rotation_error: "更换 IP 失败" }, policy: "当前策略", editPolicy: "编辑策略", editPolicyTitle: "编辑质量守护策略", editPolicyDescription: "保存后由守护进程热加载,无需重启服务。", restoreDefaults: "恢复默认值", policySaved: "策略已保存,正在热加载", invalidPolicyValue: "数值超出允许范围", softThresholdMustBeLower: "软阈值必须低于硬阈值", activeIntervalSeconds: "主动检测间隔(秒)", passiveIntervalSeconds: "被动审计间隔(秒)", consecutiveSoft: "软阈值连续次数", consecutiveErrors: "检测错误连续次数", quarantineSeconds: "隔离时长(秒)", softThreshold: "软阈值", hardThreshold: "硬阈值", activeInterval: "主动间隔", passiveInterval: "审计间隔", quarantineDuration: "隔离时长", minimumNodes: "最少保留节点", unavailable: "质量守护尚未连接", unavailableHelp: "在 config.yaml 中启用 qualityGuard,并启动 quality-guard Compose profile 后,这里会显示实时状态。", testing: "正在检测节点质量", testComplete: "检测完成:{{speed}}", testFailed: "质量检测暂不可用,请稍后重试", + nodesTab: "节点质量", + degrade: { + tab: "降智账号", overview: "降智账号概览", series: "降智时序", nodes: "按出口节点", + hits: "降智次数", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", + accounts: "涉及账号", accountsHelp: "窗口内去重", stillEnabled: "仍在调度", stillEnabledHelp: "漏网,可批量禁", + maxTPS: "峰值 TPS", maxTPSHelp: "单次请求最高", + accountsTitle: "降智账号", accountsHint: "显示 {{shown}} / {{total}}", accountsHintFiltered: "显示 {{shown}} / {{total}} · 命中≥{{min}}", + search: "搜邮箱 / ID", statusAll: "全部状态", statusOn: "仍在调度", statusOff: "已禁言", + classAll: "全部类型", class: "类型", account: "账号", status: "状态", hitCount: "命中", + hitsAll: "全部次数", hitsMin: "命中 ≥ {{count}}", + windows: { "1h": "近 1 小时", "6h": "近 6 小时", "24h": "近 24 小时", "7d": "近 7 天" }, + muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", + scheduling: "调度中", mutedStatus: "已禁", + events: "最近事件", eventsHelp: "用户请求,不含 quality-test 探针", + noHits: "这个窗口没有降智请求", noNodes: "无节点数据", noAccounts: "没有匹配账号", noEvents: "无事件", + }, refreshNodes: "刷新节点", nodeEnabled: "节点已启用", nodeDisabled: "节点已停用", nodesEnabled: "所选节点已启用", nodesDisabled: "所选节点已停用", enableNode: "启用节点 {{name}}", disableNode: "停用节点 {{name}}", nodeEditorDescription: "管理质量守护使用的 Grok Build 出口。代理地址仅写入;编辑时留空会保留现有配置。", nodeCapacityHelp: "最多可绑定的账号数,0 表示不限制。", deleteNodeTitle: "删除代理节点?", deleteNodeDescription: "将永久删除节点“{{name}}”。此操作无法撤销。", deleteNodesTitle: "删除所选 {{count}} 个节点?", deleteNodesDescription: "所选代理节点将被永久删除,此操作无法撤销。", }, @@ -1335,7 +1351,24 @@ const resources = { media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", totalImages: "Total images", totalBytes: "Storage", pageSummary: "Showing {{count}} / {{total}}", openImage: "Open image {{id}}", deleteTitle: "Delete {{count}} selected images?", deleteDescription: "The image files and gallery records will be permanently removed, and existing image links will stop working. This cannot be undone.", deleted: "Deleted {{count}} images" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", statusProgress: "Status / progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", time: "Time", createdShort: "Created", completedShort: "Done", preview: "Preview video", previewTitle: "Video preview", previewUnavailable: "Local video unavailable", deleteTitle: "Delete {{count}} video records?", deleteDescription: "The task records and their local videos will be permanently removed, and existing video links will stop working. This cannot be undone.", deleted: "Deleted {{count}} video records", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } }, auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" }, shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" }, - qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone." }, + qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.", + nodesTab: "Node quality", + degrade: { + tab: "Degraded accounts", overview: "Degraded account overview", series: "Degrade timeline", nodes: "By egress node", + hits: "Degrade hits", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", + accounts: "Accounts", accountsHelp: "Unique in this window", stillEnabled: "Still scheduled", stillEnabledHelp: "Still enabled; can be muted in bulk", + maxTPS: "Peak TPS", maxTPSHelp: "Highest single request", + accountsTitle: "Degraded accounts", accountsHint: "Showing {{shown}} / {{total}}", accountsHintFiltered: "Showing {{shown}} / {{total}} · hits ≥ {{min}}", + search: "Search email / ID", statusAll: "All statuses", statusOn: "Still scheduled", statusOff: "Muted", + classAll: "All classes", class: "Class", account: "Account", status: "Status", hitCount: "Hits", + hitsAll: "Any hit count", hitsMin: "Hits ≥ {{count}}", + windows: { "1h": "Last 1 hour", "6h": "Last 6 hours", "24h": "Last 24 hours", "7d": "Last 7 days" }, + muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", + scheduling: "Scheduled", mutedStatus: "Muted", + events: "Recent events", eventsHelp: "User requests; quality-test probes are excluded", + noHits: "No degrade requests in this window", noNodes: "No node data", noAccounts: "No matching accounts", noEvents: "No events", + }, + }, accountQuotaReset: { action: "Reset quota", description: "This clears only local waiting-reset and model quota blocks. It does not change upstream Billing or audit history. Accounts that remain exhausted will be marked again by real traffic.", completed: "Reset local quota state for {{reset}} accounts" }, accountQuotaTask: { title: "Process quota for {{count}} selected accounts", description: "Choose the quota task to run for the selected Grok Build accounts.", allTitle: "Process quota for all accounts", allDescription: "Choose the quota task to run for all enabled Grok Build accounts.", syncDescription: "Request upstream Billing and update local quota snapshots, account tiers, and recovery state.", resetAllDescription: "Clear local waiting-reset and exhausted-quota blocks for all enabled Grok Build accounts without changing upstream Billing or audit history.", execute: "Run task" }, accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" }, From 277f2879bd3f9a1606766335f3375a65a71c561f Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Thu, 13 Aug 2026 15:21:26 +0800 Subject: [PATCH 06/17] fix: polish degraded-account panel controls Allow selecting muted accounts, unmute them in bulk, keep status badges on one line, and grow the timeline bars from the bottom of the card. --- .../quality-guard/degrade-accounts-panel.tsx | 110 +++++++++++++----- frontend/src/shared/i18n/index.ts | 6 +- 2 files changed, 82 insertions(+), 34 deletions(-) diff --git a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx index e8d2da7b..66dd821c 100644 --- a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx +++ b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { AlertTriangle, Gauge, PowerOff, RefreshCw, Search, Users } from "lucide-react"; +import { AlertTriangle, Gauge, Power, PowerOff, RefreshCw, Search, Users } from "lucide-react"; import { useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; @@ -21,7 +21,7 @@ const MUTE_TOAST_ID = "quality-guard-degrade-mute"; export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; hardTPS?: number }) { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); - const [window, setWindow] = useState("24h"); + const [period, setPeriod] = useState("24h"); const [search, setSearch] = useState(""); const [status, setStatus] = useState<"all" | "on" | "off">("all"); const [cls, setCls] = useState<"all" | DegradeClass>("all"); @@ -29,16 +29,18 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h const [selected, setSelected] = useState>(() => new Set()); const query = useQuery({ - queryKey: ["quality-guard-degrade-accounts", window, softTPS, hardTPS], - queryFn: () => getDegradeAccounts({ window, softTPS, hardTPS }), + queryKey: ["quality-guard-degrade-accounts", period, softTPS, hardTPS], + queryFn: () => getDegradeAccounts({ window: period, softTPS, hardTPS }), refetchInterval: 15_000, }); const data = query.data; const rows = useMemo(() => filterAccounts(data, { search, status, cls, hitsMin }), [data, search, status, cls, hitsMin]); - const selectable = rows.filter((account) => account.enabled); - const selectedEnabled = selectable.filter((account) => selected.has(account.id)); - const allSelected = selectable.length > 0 && selectedEnabled.length === selectable.length; + const selectable = rows; + const selectedRows = selectable.filter((account) => selected.has(account.id)); + const selectedEnabled = selectedRows.filter((account) => account.enabled); + const selectedMuted = selectedRows.filter((account) => !account.enabled); + const allSelected = selectable.length > 0 && selectedRows.length === selectable.length; const muteMutation = useMutation({ mutationFn: (ids: string[]) => updateAccountsEnabled(ids, false, "grok_build"), @@ -51,6 +53,18 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h }, onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.muteFailed"), { id: MUTE_TOAST_ID }), }); + const unmuteMutation = useMutation({ + mutationFn: (ids: string[]) => updateAccountsEnabled(ids, true, "grok_build"), + onMutate: () => toast.loading(t("qualityGuard.degrade.unmuting"), { id: MUTE_TOAST_ID }), + onSuccess: (_, ids) => { + setSelected(new Set()); + void queryClient.invalidateQueries({ queryKey: ["quality-guard-degrade-accounts"] }); + void queryClient.invalidateQueries({ queryKey: ["accounts"] }); + toast.success(t("qualityGuard.degrade.unmuted", { count: ids.length }), { id: MUTE_TOAST_ID }); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.unmuteFailed"), { id: MUTE_TOAST_ID }), + }); + const busy = muteMutation.isPending || unmuteMutation.isPending; const toggleAll = (checked: boolean) => { setSelected((current) => { @@ -75,7 +89,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h = data.thresholds.hardTPS ? "bad" : undefined} />
-
+
@@ -95,16 +109,22 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h setSearch(event.target.value)} placeholder={t("qualityGuard.degrade.search")} />
- { setSelected(new Set()); setWindow(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> + { setSelected(new Set()); setPeriod(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> setStatus(value as "all" | "on" | "off")} items={[["all", t("qualityGuard.degrade.statusAll")], ["on", t("qualityGuard.degrade.statusOn")], ["off", t("qualityGuard.degrade.statusOff")]]} /> setCls(value as "all" | DegradeClass)} items={[["all", t("qualityGuard.degrade.classAll")], ["buffered_burst", "burst"], ["soft_tps", "soft"], ["hard_tps", "hard"]]} /> setHitsMin(Number(value))} items={[["1", t("qualityGuard.degrade.hitsAll")], ["2", t("qualityGuard.degrade.hitsMin", { count: 2 })], ["3", t("qualityGuard.degrade.hitsMin", { count: 3 })], ["5", t("qualityGuard.degrade.hitsMin", { count: 5 })], ["10", t("qualityGuard.degrade.hitsMin", { count: 10 })]]} /> - + @@ -114,7 +134,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h - 0 ? "indeterminate" : false} disabled={selectable.length === 0} onCheckedChange={(checked) => toggleAll(checked === true)} aria-label={t("common.selectPage")} /> + 0 ? "indeterminate" : false} disabled={selectable.length === 0} onCheckedChange={(checked) => toggleAll(checked === true)} aria-label={t("common.selectPage")} /> {t("qualityGuard.degrade.account")} {t("qualityGuard.degrade.status")} {t("qualityGuard.degrade.hitCount")} @@ -128,20 +148,31 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h {rows.length === 0 ? ( ) : rows.map((account) => ( - - setSelected((current) => { + { + setSelected((current) => { const next = new Set(current); - if (checked === true) next.add(account.id); - else next.delete(account.id); + if (next.has(account.id)) next.delete(account.id); + else next.add(account.id); return next; - })} /> + }); + }}> + event.stopPropagation()}> + +
#{account.id}
{account.email || account.name || "-"}
- - {account.enabled ? {t("qualityGuard.degrade.scheduling")} : {t("qualityGuard.degrade.mutedStatus")}} - {account.bfs ? bfs {account.bfs} : null} + + {account.enabled ? {t("qualityGuard.degrade.scheduling")} : {t("qualityGuard.degrade.mutedStatus")}} + {account.bfs ? bfs {account.bfs} : null} {account.hits} = data.thresholds.hardTPS ? "text-destructive" : account.maxTPS >= data.thresholds.softTPS ? "text-amber-600 dark:text-amber-400" : "")}>{account.maxTPS} @@ -225,27 +256,44 @@ function Metric({ icon: Icon, label, value, detail, tone }: { icon: typeof Alert function SeriesChart({ series, empty, title }: { series: DegradeSummaryDTO["series"]; empty: string; title: string }) { const max = Math.max(1, ...series.map((item) => item.count)); + const labelStep = series.length > 12 ? Math.ceil(series.length / 8) : 1; return ( -
-

{title}

-
- {series.length === 0 ?

{empty}

: series.map((item) => ( -
-
0 && item.severe >= item.count * 0.5 ? "bg-destructive" : "bg-amber-500/80")} style={{ height: `${Math.max(2, Math.round(item.count / max * 100))}%` }} /> -
{item.label}
-
- ))} +
+

{title}

+
+ {series.length === 0 ?

{empty}

: series.map((item, index) => { + const height = item.count <= 0 ? 0 : Math.max(6, Math.round((item.count / max) * 100)); + const showLabel = index % labelStep === 0 || index === series.length - 1; + return ( +
+
+
0 && item.severe >= item.count * 0.5 ? "bg-destructive" : "bg-amber-500")} + style={{ height: `${height}%` }} + /> +
+
+ {showLabel ? shortSeriesLabel(item.label) : ""} +
+
+ ); + })}
); } +function shortSeriesLabel(label: string) { + const hour = label.match(/(\d{1,2})(?::\d{2})?$/); + return hour ? hour[1].padStart(2, "0") : label; +} + function NodeList({ nodes, empty, title }: { nodes: DegradeSummaryDTO["nodes"]; empty: string; title: string }) { const max = Math.max(1, ...nodes.map((node) => node.hits)); return ( -
-

{title}

-
+
+

{title}

+
{nodes.length === 0 ?

{empty}

: nodes.map((node) => (
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 88fea127..169df231 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -454,8 +454,8 @@ const resources = { classAll: "全部类型", class: "类型", account: "账号", status: "状态", hitCount: "命中", hitsAll: "全部次数", hitsMin: "命中 ≥ {{count}}", windows: { "1h": "近 1 小时", "6h": "近 6 小时", "24h": "近 24 小时", "7d": "近 7 天" }, - muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", - scheduling: "调度中", mutedStatus: "已禁", + muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", unmuteSelected: "解除禁用", unmuteSelectedCount: "解除禁用 ({{count}})", unmuteConfirm: "确认恢复 {{count}} 个已禁账号到调度?", unmuting: "正在恢复账号", unmuted: "已恢复 {{count}} 个账号", unmuteFailed: "恢复失败", + scheduling: "调度", mutedStatus: "已禁", events: "最近事件", eventsHelp: "用户请求,不含 quality-test 探针", noHits: "这个窗口没有降智请求", noNodes: "无节点数据", noAccounts: "没有匹配账号", noEvents: "无事件", }, @@ -1363,7 +1363,7 @@ const resources = { classAll: "All classes", class: "Class", account: "Account", status: "Status", hitCount: "Hits", hitsAll: "Any hit count", hitsMin: "Hits ≥ {{count}}", windows: { "1h": "Last 1 hour", "6h": "Last 6 hours", "24h": "Last 24 hours", "7d": "Last 7 days" }, - muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", + muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", unmuteSelected: "Unmute selected", unmuteSelectedCount: "Unmute selected ({{count}})", unmuteConfirm: "Restore {{count}} muted accounts to scheduling?", unmuting: "Restoring accounts", unmuted: "Restored {{count}} accounts", unmuteFailed: "Failed to restore accounts", scheduling: "Scheduled", mutedStatus: "Muted", events: "Recent events", eventsHelp: "User requests; quality-test probes are excluded", noHits: "No degrade requests in this window", noNodes: "No node data", noAccounts: "No matching accounts", noEvents: "No events", From 02c4014d6dcaca19bef91f37044912deb9390346 Mon Sep 17 00:00:00 2001 From: 2164312714-svg <2164312714-svg@users.noreply.github.com> Date: Thu, 13 Aug 2026 19:51:37 +0800 Subject: [PATCH 07/17] fix(web): isolate image prompts from chat history Use only the latest user turn for stateless image generation, support both Web image generation models through Chat Completions and Responses, and direct current-turn image inputs to the image edits endpoint. Refs #911 --- backend/internal/infra/provider/web/chat.go | 81 +++++++++++++++++-- backend/internal/infra/provider/web/image.go | 76 ++++++++++++++--- .../infra/provider/web/protocol_test.go | 72 +++++++++++++++++ 3 files changed, 214 insertions(+), 15 deletions(-) diff --git a/backend/internal/infra/provider/web/chat.go b/backend/internal/infra/provider/web/chat.go index 9549be88..a6f94462 100644 --- a/backend/internal/infra/provider/web/chat.go +++ b/backend/internal/infra/provider/web/chat.go @@ -20,6 +20,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" @@ -62,6 +63,8 @@ type openAIRequest struct { ImageConfig *struct { Count *int `json:"n"` ResponseFormat string `json:"response_format"` + AspectRatio string `json:"aspect_ratio"` + Resolution string `json:"resolution"` } `json:"image_config"` } @@ -209,7 +212,14 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if len(input.Include) > 0 { conversationOptions.Include = append([]string{}, input.Include...) } - normalized, err := normalizeOpenAIInput(input, request.Operation) + spec, modelKnown := Resolve(request.Model) + var normalized normalizedChatInput + var err error + if modelKnown && spec.Capability == modeldomain.CapabilityImage { + normalized, err = normalizeLatestImageInput(input, request.Operation) + } else { + normalized, err = normalizeOpenAIInput(input, request.Operation) + } if err != nil { return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"message": err.Error(), "type": "invalid_request_error"}}), nil } @@ -221,14 +231,16 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if input.ParallelToolCalls != nil { parallelTools = *input.ParallelToolCalls } - spec, ok := Resolve(request.Model) - if ok && spec.ProtocolModel == "imagine-lite" && request.Operation == "chat" { + if modelKnown && spec.Capability == modeldomain.CapabilityImage { if len(tools.ResponseTools) > 0 { - return invalidImageRequest("grok-imagine-image-lite 不支持 tools") + return invalidImageRequest("图片生成模型不支持 tools") } - return a.forwardLiteChatCompletion(ctx, request, input, normalized, spec) + return a.forwardImageChatCompletion(ctx, request, input, normalized, spec) } - if !ok || spec.Capability != "chat" { + if modelKnown && spec.Capability == modeldomain.CapabilityImageEdit { + return invalidImageRequest("图片编辑模型请使用 /v1/images/edits,并在当前请求中显式提供输入图片") + } + if !modelKnown || spec.Capability != modeldomain.CapabilityChat { return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"message": "模型不支持文本对话", "type": "invalid_request_error"}}), nil } @@ -736,6 +748,63 @@ func normalizeOpenAIInput(input openAIRequest, operation string) (normalizedChat return normalizedChatInput{Prompt: value, Attachments: attachments}, nil } +// Image generation is stateless: only the latest user turn is a prompt. In +// particular, assistant images from an OpenAI-compatible client's history must +// not be reinterpreted as image-edit inputs on the next generation request. +func normalizeLatestImageInput(input openAIRequest, operation string) (normalizedChatInput, error) { + if operation == conversation.OperationChat { + for index := len(input.Messages) - 1; index >= 0; index-- { + message := input.Messages[index] + if !strings.EqualFold(strings.TrimSpace(message.Role), "user") { + continue + } + return normalizeImageMessage(message.Content) + } + return normalizedChatInput{}, errors.New("messages 中缺少用户消息") + } + + trimmed := bytes.TrimSpace(input.Input) + if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) { + return normalizedChatInput{}, errors.New("input 不能为空") + } + if trimmed[0] == '"' { + var prompt string + if json.Unmarshal(trimmed, &prompt) != nil { + return normalizedChatInput{}, errors.New("input 格式无效") + } + prompt = strings.TrimSpace(prompt) + if prompt == "" { + return normalizedChatInput{}, errors.New("图片生成提示词不能为空") + } + return normalizedChatInput{Prompt: prompt}, nil + } + + var messages []chatMessage + if json.Unmarshal(trimmed, &messages) != nil { + return normalizedChatInput{}, errors.New("input 必须是字符串或消息数组") + } + for index := len(messages) - 1; index >= 0; index-- { + message := messages[index] + typeName := strings.ToLower(strings.TrimSpace(message.Type)) + if (typeName == "" || typeName == "message") && strings.EqualFold(strings.TrimSpace(message.Role), "user") { + return normalizeImageMessage(message.Content) + } + } + return normalizedChatInput{}, errors.New("input 中缺少用户消息") +} + +func normalizeImageMessage(content json.RawMessage) (normalizedChatInput, error) { + prompt, attachments, err := contentTextAndAttachments(content) + if err != nil { + return normalizedChatInput{}, err + } + prompt = strings.TrimSpace(prompt) + if prompt == "" && len(attachments) == 0 { + return normalizedChatInput{}, errors.New("图片生成提示词不能为空") + } + return normalizedChatInput{Prompt: prompt, Attachments: attachments}, nil +} + func rawTextValue(raw json.RawMessage) (string, error) { trimmed := bytes.TrimSpace(raw) if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) { diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index a94f198a..ced5e2b5 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -470,9 +470,9 @@ func (a *Adapter) generateLiteImageURL(ctx context.Context, credential account.C return "", fmt.Errorf("Grok Web Lite 图片签名刷新失败") } -func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, spec ModelSpec) (*provider.Response, error) { +func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, spec ModelSpec) (*provider.Response, error) { if len(normalized.Attachments) > 0 { - return invalidImageRequest("grok-imagine-image-lite 只支持纯文本生图;附件请使用对应的图片编辑或对话模型") + return invalidImageRequest("文生图模型只接受当前用户消息中的纯文本;图生图请使用 grok-imagine-image-edit 和 /v1/images/edits") } count := 1 format := "url" @@ -490,12 +490,15 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide if format != "url" && format != "b64_json" { return invalidImageRequest("image_config.response_format 必须是 url 或 b64_json") } + if spec.ProtocolModel != "imagine-lite" { + return a.forwardQualityImageChatCompletion(ctx, request, input, normalized, count, format) + } responseID := newWebID("resp") streaming := input.Stream || request.Streaming if streaming { reader, writer := io.Pipe() streamCtx, cancel := context.WithCancel(ctx) - go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, normalized.Prompt, count, format) + go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, request.Operation, normalized.Prompt, count, format) return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil } parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(normalized.Prompt)} @@ -517,7 +520,7 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide } parsed.appendText(liteImageMarkdown(item)) } - payload := buildOpenAIResult("chat", responseID, input.Model, parsed, false) + payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) data, err := json.Marshal(payload) if err != nil { return nil, err @@ -525,9 +528,9 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: count}, nil } -func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, prompt string, count int, format string) { +func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, operation, prompt string, count int, format string) { parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(prompt)} - writeStreamStart(writer, "chat", responseID, model, parsed.InputTokens) + writeStreamStart(writer, operation, responseID, model, parsed.InputTokens) for range count { rawURL, err := a.generateLiteImageURL(ctx, credential, spec, prompt) if err != nil { @@ -544,16 +547,71 @@ func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWrite delta = "\n\n" + delta } parsed.appendText(delta) - if err := writeStreamDelta(writer, "chat", responseID, model, "text", delta); err != nil { + if err := writeStreamDelta(writer, operation, responseID, model, "text", delta); err != nil { _ = writer.CloseWithError(err) return } } - payload := buildOpenAIResult("chat", responseID, model, parsed, false) - writeStreamDone(writer, "chat", responseID, model, parsed, payload) + payload := buildOpenAIResult(operation, responseID, model, parsed, false) + writeStreamDone(writer, operation, responseID, model, parsed, payload) _ = writer.Close() } +func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, count int, format string) (*provider.Response, error) { + aspectRatio := "" + resolution := "" + if input.ImageConfig != nil { + aspectRatio = input.ImageConfig.AspectRatio + resolution = input.ImageConfig.Resolution + } + generated, err := a.GenerateImage(ctx, provider.ImageGenerationRequest{ + Credential: request.Credential, Model: request.Model, Prompt: normalized.Prompt, + Count: count, AspectRatio: aspectRatio, Resolution: resolution, ResponseFormat: format, + }) + if err != nil { + return nil, err + } + if generated.StatusCode < http.StatusOK || generated.StatusCode >= http.StatusMultipleChoices { + return generated, nil + } + defer generated.Body.Close() + var payload struct { + Data []map[string]any `json:"data"` + } + if err := json.NewDecoder(generated.Body).Decode(&payload); err != nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, fmt.Errorf("图片生成兼容响应解析失败: %w", err)) + } + parsed := parsedChat{ResponseID: newWebID("resp"), InputTokens: estimateTokens(normalized.Prompt)} + for _, item := range payload.Data { + markdown := liteImageMarkdown(item) + if markdown == "" { + continue + } + if parsed.Text.Len() > 0 { + parsed.appendText("\n\n") + } + parsed.appendText(markdown) + } + if parsed.Text.Len() == 0 { + return nil, fmt.Errorf("图片生成兼容响应中没有图片") + } + result := buildOpenAIResult(request.Operation, parsed.ResponseID, input.Model, parsed, false) + if input.Stream || request.Streaming { + var stream bytes.Buffer + writeStreamStart(&stream, request.Operation, parsed.ResponseID, input.Model, parsed.InputTokens) + if err := writeStreamDelta(&stream, request.Operation, parsed.ResponseID, input.Model, "text", parsed.Text.String()); err != nil { + return nil, err + } + writeStreamDone(&stream, request.Operation, parsed.ResponseID, input.Model, parsed, result) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: generated.QuotaUnits}, nil + } + data, err := json.Marshal(result) + if err != nil { + return nil, err + } + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: generated.QuotaUnits}, nil +} + func liteImageMarkdown(item map[string]any) string { if value, _ := item["url"].(string); value != "" { return "![image](" + value + ")" diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 2377d375..cdbe6991 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -143,6 +143,78 @@ func TestNormalizeOpenAIInputSeparatesTextAndImages(t *testing.T) { } } +func TestNormalizeLatestImageInputIgnoresHistoricalAssistantImage(t *testing.T) { + historical, _ := json.Marshal([]any{ + map[string]any{"type": "text", "text": "first result"}, + map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/first.png"}}, + }) + latest, _ := json.Marshal("生成另一张蓝色的图片") + value, err := normalizeLatestImageInput(openAIRequest{Messages: []chatMessage{ + {Role: "user", Content: json.RawMessage(`"生成第一张图片"`)}, + {Role: "assistant", Content: historical}, + {Role: "user", Content: latest}, + }}, conversation.OperationChat) + if err != nil { + t.Fatal(err) + } + if value.Prompt != "生成另一张蓝色的图片" || len(value.Attachments) != 0 { + t.Fatalf("normalized latest image input = %#v", value) + } +} + +func TestNormalizeLatestResponsesImageInputIgnoresHistory(t *testing.T) { + input, _ := json.Marshal([]any{ + map[string]any{"type": "message", "role": "assistant", "content": []any{ + map[string]any{"type": "output_text", "text": "![image](https://example.com/first.png)"}, + map[string]any{"type": "input_image", "image_url": "https://example.com/first.png"}, + }}, + map[string]any{"role": "user", "content": []any{ + map[string]any{"type": "input_text", "text": "generate a different image"}, + }}, + }) + value, err := normalizeLatestImageInput(openAIRequest{Input: input}, conversation.OperationResponses) + if err != nil { + t.Fatal(err) + } + if value.Prompt != "generate a different image" || len(value.Attachments) != 0 { + t.Fatalf("normalized latest responses input = %#v", value) + } +} + +func TestImageChatRejectsOnlyCurrentTurnAttachment(t *testing.T) { + content, _ := json.Marshal([]any{ + map[string]any{"type": "text", "text": "make it blue"}, + map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/input.png"}}, + }) + response, err := (&Adapter{}).ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Method: http.MethodPost, Model: "grok-imagine-image", Operation: conversation.OperationChat, + Body: []byte(fmt.Sprintf(`{"model":"grok-imagine-image-lite","messages":[{"role":"user","content":%s}]}`, content)), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, _ := io.ReadAll(response.Body) + if response.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "/v1/images/edits") { + t.Fatalf("status=%d body=%s", response.StatusCode, body) + } +} + +func TestQualityImageResponsesUsesImageCompatibilityValidation(t *testing.T) { + response, err := (&Adapter{}).ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Method: http.MethodPost, Model: "grok-imagine-image-quality", Operation: conversation.OperationResponses, + Body: []byte(`{"model":"grok-imagine-image-quality-lite","input":[{"role":"user","content":[{"type":"input_text","text":"draw"}]}],"image_config":{"n":0}}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, _ := io.ReadAll(response.Body) + if response.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "image_config.n") || strings.Contains(string(body), "模型不支持文本对话") { + t.Fatalf("status=%d body=%s", response.StatusCode, body) + } +} + func TestNormalizeResponsesInputImage(t *testing.T) { dataURI := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" input, _ := json.Marshal([]any{map[string]any{ From a2e4abb558315bc79435214cd5042b70f497d5db Mon Sep 17 00:00:00 2001 From: 2164312714-svg <2164312714-svg@users.noreply.github.com> Date: Thu, 13 Aug 2026 20:27:34 +0800 Subject: [PATCH 08/17] fix(web): surface lite image stream failures --- backend/internal/infra/provider/web/image.go | 45 ++++------------- .../infra/provider/web/protocol_test.go | 50 +++++++++++++++++++ 2 files changed, 59 insertions(+), 36 deletions(-) diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index ced5e2b5..fb759985 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -494,13 +494,6 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid return a.forwardQualityImageChatCompletion(ctx, request, input, normalized, count, format) } responseID := newWebID("resp") - streaming := input.Stream || request.Streaming - if streaming { - reader, writer := io.Pipe() - streamCtx, cancel := context.WithCancel(ctx) - go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, request.Operation, normalized.Prompt, count, format) - return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil - } parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(normalized.Prompt)} for range count { rawURL, err := a.generateLiteImageURL(ctx, request.Credential, spec, normalized.Prompt) @@ -521,6 +514,15 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid parsed.appendText(liteImageMarkdown(item)) } payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) + if input.Stream || request.Streaming { + var stream bytes.Buffer + writeStreamStart(&stream, request.Operation, responseID, input.Model, parsed.InputTokens) + if err := writeStreamDelta(&stream, request.Operation, responseID, input.Model, "text", parsed.Text.String()); err != nil { + return nil, err + } + writeStreamDone(&stream, request.Operation, responseID, input.Model, parsed, payload) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: count}, nil + } data, err := json.Marshal(payload) if err != nil { return nil, err @@ -528,35 +530,6 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: count}, nil } -func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, operation, prompt string, count int, format string) { - parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(prompt)} - writeStreamStart(writer, operation, responseID, model, parsed.InputTokens) - for range count { - rawURL, err := a.generateLiteImageURL(ctx, credential, spec, prompt) - if err != nil { - _ = writer.CloseWithError(err) - return - } - item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, format) - if err != nil { - _ = writer.CloseWithError(err) - return - } - delta := liteImageMarkdown(item) - if parsed.Text.Len() > 0 { - delta = "\n\n" + delta - } - parsed.appendText(delta) - if err := writeStreamDelta(writer, operation, responseID, model, "text", delta); err != nil { - _ = writer.CloseWithError(err) - return - } - } - payload := buildOpenAIResult(operation, responseID, model, parsed, false) - writeStreamDone(writer, operation, responseID, model, parsed, payload) - _ = writer.Close() -} - func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, count int, format string) (*provider.Response, error) { aspectRatio := "" resolution := "" diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index cdbe6991..3c848f22 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -657,6 +657,56 @@ func TestLiteChatRejectsInvalidImageConfigBeforeUpstream(t *testing.T) { } } +func TestLiteChatStreamFailsBeforeReturningSuccessResponse(t *testing.T) { + server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { + if request.URL.Path != "/ws/mgw/" { + fhttp.NotFound(writer, request) + return + } + connection, err := (&websocket.Upgrader{CheckOrigin: func(*fhttp.Request) bool { return true }}).Upgrade(writer, request, nil) + if err != nil { + t.Errorf("upgrade: %v", err) + return + } + defer connection.Close() + var initial map[string]any + if err := connection.ReadJSON(&initial); err != nil { + t.Errorf("read session.create: %v", err) + return + } + initialID := initial["event"].(map[string]any)["event_id"].(string) + _ = connection.WriteJSON(map[string]any{"session_id": "conv_1", "event": map[string]any{"type": "session.created", "client_event_id": initialID}}) + _ = connection.WriteJSON(map[string]any{"session_id": "conv_1", "event": map[string]any{"type": "conversation.attached", "conversation": map[string]any{"id": "conv_1"}}}) + for range 2 { + var event map[string]any + if err := connection.ReadJSON(&event); err != nil { + t.Errorf("read turn event: %v", err) + return + } + } + _ = connection.WriteJSON(map[string]any{"session_id": "conv_1", "event": map[string]any{"type": "response.done", "response": map[string]any{"id": "parent_1", "status": "completed"}}}) + })) + defer server.Close() + + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("test-sso") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{BaseURL: server.URL, StatsigMode: "manual"}, infraegress.NewManager(egressRepositoryStub{}, cipher), cipher, nil, imageAssetStoreStub{}) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderWeb, UserID: "497f19f8-49d4-458a-bee4-43ec3dcaf8ca", EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/v1/chat/completions", Model: "grok-imagine-image", Operation: conversation.OperationChat, + Body: []byte(`{"model":"grok-imagine-image-lite","stream":true,"messages":[{"role":"user","content":"draw a cat"}]}`), Streaming: true, + }) + if err == nil || response != nil || !strings.Contains(err.Error(), "未解析到最终图片") { + t.Fatalf("response=%#v error=%v", response, err) + } +} + func TestParseLiteImageCardAttachment(t *testing.T) { parsed := &parsedChat{} frame := map[string]any{"result": map[string]any{"response": map[string]any{ From 0ec941bf3c9380894e4c140ec0d2439f8b7fdc4d Mon Sep 17 00:00:00 2001 From: 741075810 <31341354+741075810@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:45:43 +0800 Subject: [PATCH 09/17] docs(api): state measured Console video input limits --- frontend/src/shared/i18n/index.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bdf47d9c..08ae7f32 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1100,20 +1100,20 @@ const resources = { fieldPrompt: "用于生成或编辑图片的自然语言描述。", fieldImageCount: "需要返回的图片数量;网关会选择可满足数量的最小上游批次。", fieldAspectRatio: "输出媒体的宽高比,例如 1:1、2:3 或 16:9。", - fieldResolution: "输出分辨率;图片支持 1k/2k,视频按模型能力校验。", + fieldResolution: "输出分辨率;图片支持 1k/2k。视频 grok-imagine-video 支持 480p/720p,grok-imagine-video-1.5 额外支持 1080p,但 1080p 不能用于参考图生视频。", fieldQuality: "Image 2.0 的生成质量,可选 low 或 medium;默认 medium。", fieldResponseFormat: "图片返回格式,支持 url 或 b64_json。", fieldImageStream: "是否使用图片生成扩展 SSE 流;默认 false。", fieldEditImages: "待编辑图片,使用 image 或 images 传入 URL、Data URL 或已支持的图片引用。", fieldVideoPrompt: "视频描述;使用图片输入时可作为运动或镜头指令。", - fieldDuration: "视频时长,按上游模型支持范围校验。", - fieldVideoImage: "可选首帧图片引用,用于图生视频。", + fieldDuration: "视频时长(秒)。文生视频与首帧图生视频最长 15 秒;参考图生视频 grok-imagine-video 最长 10 秒、grok-imagine-video-1.5 最长 15 秒。", + fieldVideoImage: "可选首帧图片引用,用于图生视频;最多 1 张,不可与 reference_images 同时使用。", fieldVideoEditPrompt: "描述希望如何修改原视频。", fieldVideoExtendPrompt: "描述视频接下来应发生的内容。", fieldVideoInput: "输入视频,支持 url 或本地上传后的 file_id。", fieldVideoExtendDuration: "延长片段时长,单位秒,范围 2 到 10,默认 6。", - fieldReferenceImages: "可选参考图片数组,用于参考图视频;每项提供 url 或 file_id,不可与 image 同时使用。", - fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。", + fieldReferenceImages: "可选参考图片数组,用于参考图视频;最多 7 张,每项提供 url 或 file_id,不可与 image 同时使用。", + fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。需上游团队开启该能力,未开启时上游返回 403。", fieldRequestId: "创建视频任务时返回的 request_id。", noteChatProviders: "Build、Web 与 Console 使用独立账号池和上游协议,但向客户端返回统一的 Chat Completions 结构。", noteChatImages: "对话图片会先完成校验与上传,再绑定到本次选择的账号;不会在流开始后切换账号。", @@ -1131,7 +1131,7 @@ const resources = { noteEditSources: "远程图片会经过 SSRF、防体积超限和内容类型校验后再上传到上游。", noteVideoAsync: "创建接口只返回 request_id;生成过程异步执行并持久化任务状态。", noteVideoDuration: "时长、比例、分辨率和图片输入按当前视频模型能力校验。", - noteVideoReference: "参考图视频走 /videos/generations + reference_images;不可与 image 同用,resolution 最高 720p;reference_audios 使用内置 voice_id。", + noteVideoReference: "参考图视频走 /videos/generations + reference_images,最多 7 张;只传 1 张也保持参考图语义,不会被当成首帧。不可与 image 同用。参考图模式 resolution 最高 720p,grok-imagine-video-1.5 也不例外。reference_audios 使用内置 voice_id,需团队开启该能力。", noteVideoStrict: "视频接口严格使用当前官方字段,不保留旧项目的兼容别名。", noteVideoEditModel: "视频编辑与延长的实际路由必须指向 Console/grok-imagine-video;对外模型名可以自定义。", noteVideoBilling: "视频编辑与延长暂未返回可可靠结算的输入视频时长,因此保持可调用,并在请求审计中标记为未计费;不会消耗 API Key 的金额额度。", @@ -1730,20 +1730,20 @@ const resources = { fieldPrompt: "Natural-language instructions for image generation or editing.", fieldImageCount: "Number of images to return. The gateway selects the smallest upstream batch that can satisfy it.", fieldAspectRatio: "Output aspect ratio such as 1:1, 2:3, or 16:9.", - fieldResolution: "Output resolution. Images support 1k/2k; video values are validated by model capability.", + fieldResolution: "Output resolution. Images support 1k/2k. For video, grok-imagine-video supports 480p/720p and grok-imagine-video-1.5 also supports 1080p, but 1080p cannot be used for reference-to-video.", fieldQuality: "Generation quality for Image 2.0: low or medium. Defaults to medium.", fieldResponseFormat: "Image response format: url or b64_json.", fieldImageStream: "Enable the image-generation SSE extension. Defaults to false.", fieldEditImages: "Source image or images supplied as URLs, data URLs, or another supported image reference.", fieldVideoPrompt: "Video description, or motion and camera instructions when an image is supplied.", - fieldDuration: "Video duration validated against the upstream model's supported range.", - fieldVideoImage: "Optional first-frame image reference for image-to-video generation.", + fieldDuration: "Video duration in seconds. Text-to-video and first-frame image-to-video allow up to 15s. For reference-to-video, grok-imagine-video allows up to 10s and grok-imagine-video-1.5 up to 15s.", + fieldVideoImage: "Optional first-frame image reference for image-to-video generation. At most one image, and it cannot be combined with reference_images.", fieldVideoEditPrompt: "Describe how the source video should change.", fieldVideoExtendPrompt: "Describe what should happen next in the video.", fieldVideoInput: "Source video input. Provide either url or an uploaded file_id.", fieldVideoExtendDuration: "Extension length in seconds. Allowed range is 2 to 10; defaults to 6.", - fieldReferenceImages: "Optional reference image array for reference-to-video. Each item uses url or file_id and cannot be combined with image.", - fieldReferenceAudios: "Optional reference audio array of up to 3 built-in voice_id values. Can be used alone or with reference_images.", + fieldReferenceImages: "Optional reference image array for reference-to-video, up to 7 items. Each item uses url or file_id and cannot be combined with image.", + fieldReferenceAudios: "Optional reference audio array of up to 3 built-in voice_id values. Can be used alone or with reference_images. The upstream team must have the capability enabled; otherwise upstream returns 403.", fieldRequestId: "The request_id returned when the video job is created.", noteChatProviders: "Build, Web, and Console use separate account pools and upstream protocols while returning the same Chat Completions shape.", noteChatImages: "Conversation images are validated and uploaded before being bound to the selected account. Accounts never switch after streaming begins.", @@ -1761,7 +1761,7 @@ const resources = { noteEditSources: "Remote images pass SSRF, size, and content-type checks before upload to the upstream service.", noteVideoAsync: "Creation returns only request_id. Generation runs asynchronously with persistent job state.", noteVideoDuration: "Duration, aspect ratio, resolution, and image inputs are validated against the selected video model.", - noteVideoReference: "Reference-to-video uses /videos/generations with reference_images. Do not combine with image; resolution tops out at 720p. reference_audios accepts built-in voice_id values.", + noteVideoReference: "Reference-to-video uses /videos/generations with reference_images, up to 7 items. A single item still keeps reference semantics and is not promoted to a first frame. Do not combine with image. Resolution tops out at 720p in reference mode, including grok-imagine-video-1.5. reference_audios accepts built-in voice_id values and requires team entitlement.", noteVideoStrict: "Video endpoints use the current official fields without non-standard aliases.", noteVideoEditModel: "The resolved route for video edits and extensions must target Console/grok-imagine-video; the public model name may be customized.", noteVideoBilling: "Video edits and extensions do not yet expose a reliably billable input-video duration. They remain callable, are audited as unpriced, and do not consume the API key spend limit.", From e257f3db4478b08c4602ba22710786df1c60b7ac Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:13:54 +0800 Subject: [PATCH 10/17] feat: add progress reporting to model sync process with event streaming --- backend/internal/application/model/service.go | 29 +++-- .../internal/transport/http/model/handler.go | 100 +++++++++++++++++- .../transport/http/model/handler_test.go | 25 +++++ frontend/src/entities/model/model-api.ts | 47 +++++++- frontend/src/features/models/models-page.tsx | 15 ++- frontend/src/shared/i18n/index.ts | 4 +- 6 files changed, 199 insertions(+), 21 deletions(-) diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 706b359d..57669170 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -6,6 +6,7 @@ import ( "fmt" "log/slog" "strings" + "sync/atomic" "time" accountapp "github.com/chenyme/grok2api/backend/internal/application/account" @@ -64,6 +65,8 @@ type ListFilter struct { Sort repository.SortQuery } +type SyncProgressObserver func(completed, total int) + // Service 负责上游模型发现、内部来源路由与对外模型名称维护。 type Service struct { models repository.ModelRepository @@ -398,8 +401,13 @@ func (s *Service) BatchSetEnabled(ctx context.Context, ids []uint64, enabled boo // Sync 从全部启用账号同步模型能力,并按 Provider 幂等更新公开路由表。 func (s *Service) Sync(ctx context.Context) (int, error) { + return s.SyncObserved(ctx, nil) +} + +// SyncObserved 执行全量模型同步,并按已完成账号数报告进度。 +func (s *Service) SyncObserved(ctx context.Context, observer SyncProgressObserver) (int, error) { result := s.syncAll.DoChan("all", func() (any, error) { - return s.syncAllAccounts(ctx) + return s.syncAllAccounts(ctx, observer) }) select { case <-ctx.Done(): @@ -412,14 +420,7 @@ func (s *Service) Sync(ctx context.Context) (int, error) { } } -// SyncAsync 异步触发全量模型同步,不阻塞调用方。用 context.Background 避免请求超时导致同步中断。 -func (s *Service) SyncAsync(_ context.Context) { - s.syncAll.DoChan("all", func() (any, error) { - return s.syncAllAccounts(context.Background()) - }) -} - -func (s *Service) syncAllAccounts(ctx context.Context) (int, error) { +func (s *Service) syncAllAccounts(ctx context.Context, observer SyncProgressObserver) (int, error) { if s.providers == nil { return 0, fmt.Errorf("Provider 注册表未初始化") } @@ -438,12 +439,20 @@ func (s *Service) syncAllAccounts(ctx context.Context) (int, error) { if len(credentials) == 0 { return 0, fmt.Errorf("没有可用于模型同步的账号") } - results, summary, runErr := batch.Map(ctx, credentials, batch.Options{Workers: s.bulkPool.Limit(), Pool: s.bulkPool}, func(workCtx context.Context, value account.Credential) ([]string, error) { + if observer != nil { + observer(0, len(credentials)) + } + var completed atomic.Int64 + results, summary, runErr := batch.MapObserved(ctx, credentials, batch.Options{Workers: s.bulkPool.Limit(), Pool: s.bulkPool}, func(workCtx context.Context, value account.Credential) ([]string, error) { adapter, ok := s.providers.Models(value.Provider) if !ok { return nil, fmt.Errorf("Provider %s 未注册模型同步能力", value.Provider) } return s.syncAccountCapabilities(workCtx, value, adapter) + }, func(_ int, _ batch.Result[[]string]) { + if observer != nil { + observer(int(completed.Add(1)), len(credentials)) + } }) pool := s.bulkPool.Snapshot() s.logger.Info("model_bulk_sync_completed", "total", summary.Total, "submitted", summary.Submitted, "succeeded", summary.Succeeded, "failed", summary.Failed, "panicked", summary.Panicked, "duration_ms", summary.Duration.Milliseconds(), "canceled", summary.Canceled, "pool_limit", pool.Limit, "pool_active", pool.Active, "pool_queued", pool.Queued, "pool_peak", pool.Peak, "error", runErr) diff --git a/backend/internal/transport/http/model/handler.go b/backend/internal/transport/http/model/handler.go index ab24a95c..9c955779 100644 --- a/backend/internal/transport/http/model/handler.go +++ b/backend/internal/transport/http/model/handler.go @@ -1,11 +1,14 @@ package model import ( + "context" + "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" + "sync/atomic" "time" modelapp "github.com/chenyme/grok2api/backend/internal/application/model" @@ -18,6 +21,11 @@ import ( type Handler struct{ service *modelapp.Service } +const ( + modelSyncHeartbeatInterval = 15 * time.Second + modelSyncWriteTimeout = 30 * time.Second +) + func NewHandler(service *modelapp.Service) *Handler { return &Handler{service: service} } func (h *Handler) Register(router *gin.RouterGroup) { @@ -234,10 +242,94 @@ func (h *Handler) batchDelete(c *gin.Context) { } func (h *Handler) sync(c *gin.Context) { - // 异步触发全量同步,不阻塞 HTTP 响应。 - // 同步需要 2min+,Cloudflare 免费版 100s 超时,直接同步会 524 → 浏览器 Failed to fetch。 - go h.service.SyncAsync(c.Request.Context()) - response.Success(c, http.StatusOK, gin.H{"synced": 0, "async": true}) + c.Header("Content-Type", "text/event-stream; charset=utf-8") + c.Header("Cache-Control", "no-cache, no-transform") + c.Header("X-Accel-Buffering", "no") + if err := writeModelSyncComment(c, "connected"); err != nil { + return + } + + type syncResult struct { + synced int + err error + } + result := make(chan syncResult, 1) + ctx, cancel := context.WithCancel(c.Request.Context()) + defer cancel() + var completed atomic.Int64 + var total atomic.Int64 + go func() { + synced, err := h.service.SyncObserved(ctx, func(current, maximum int) { + completed.Store(int64(current)) + total.Store(int64(maximum)) + }) + result <- syncResult{synced: synced, err: err} + }() + + heartbeat := time.NewTicker(modelSyncHeartbeatInterval) + defer heartbeat.Stop() + progressTicker := time.NewTicker(250 * time.Millisecond) + defer progressTicker.Stop() + lastCompleted, lastTotal := -1, -1 + for { + select { + case <-c.Request.Context().Done(): + return + case value := <-result: + if value.err != nil { + _ = writeModelSyncEvent(c, "error", gin.H{"code": "modelSyncFailed", "message": "同步模型能力失败"}) + return + } + _ = writeModelSyncEvent(c, "complete", gin.H{"synced": value.synced}) + return + case <-heartbeat.C: + if err := writeModelSyncComment(c, "heartbeat"); err != nil { + return + } + case <-progressTicker.C: + current, maximum := int(completed.Load()), int(total.Load()) + if maximum > 0 && (current != lastCompleted || maximum != lastTotal) { + if err := writeModelSyncEvent(c, "progress", gin.H{"completed": current, "total": maximum}); err != nil { + return + } + lastCompleted, lastTotal = current, maximum + } + } + } +} + +func writeModelSyncEvent(c *gin.Context, event string, value any) error { + payload, err := json.Marshal(value) + if err != nil { + return err + } + if err := setModelSyncWriteDeadline(c.Writer); err != nil { + return err + } + if _, err := fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event, payload); err != nil { + return err + } + c.Writer.Flush() + return c.Request.Context().Err() +} + +func writeModelSyncComment(c *gin.Context, comment string) error { + if err := setModelSyncWriteDeadline(c.Writer); err != nil { + return err + } + if _, err := fmt.Fprintf(c.Writer, ": %s\n\n", comment); err != nil { + return err + } + c.Writer.Flush() + return c.Request.Context().Err() +} + +func setModelSyncWriteDeadline(writer http.ResponseWriter) error { + err := http.NewResponseController(writer).SetWriteDeadline(time.Now().Add(modelSyncWriteTimeout)) + if errors.Is(err, http.ErrNotSupported) { + return nil + } + return err } func (h *Handler) update(c *gin.Context) { diff --git a/backend/internal/transport/http/model/handler_test.go b/backend/internal/transport/http/model/handler_test.go index 37a789c2..d6db6a19 100644 --- a/backend/internal/transport/http/model/handler_test.go +++ b/backend/internal/transport/http/model/handler_test.go @@ -1,13 +1,38 @@ package model import ( + "net/http" + "net/http/httptest" + "strings" "testing" modelapp "github.com/chenyme/grok2api/backend/internal/application/model" "github.com/chenyme/grok2api/backend/internal/domain/account" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/gin-gonic/gin" ) +func TestSyncStreamsTerminalFailureInsteadOfAcknowledgingSuccess(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + context.Request = httptest.NewRequest(http.MethodPost, "/api/admin/v1/models/sync", nil) + + handler := NewHandler(modelapp.NewService(nil, nil, nil, nil)) + handler.sync(context) + + if contentType := recorder.Header().Get("Content-Type"); !strings.HasPrefix(contentType, "text/event-stream") { + t.Fatalf("content type = %q", contentType) + } + body := recorder.Body.String() + if !strings.Contains(body, ": connected\n\n") || !strings.Contains(body, "event: error\ndata: {\"code\":\"modelSyncFailed\"") { + t.Fatalf("unexpected stream body: %q", body) + } + if strings.Contains(body, "event: complete") || strings.Contains(body, "\"synced\":0") { + t.Fatalf("failure was acknowledged as success: %q", body) + } +} + func TestNewModelResponseSeparatesPublicAndUpstreamNames(t *testing.T) { response := newModelResponse(modeldomain.Route{ ID: 1, PublicID: "Build/grok-4.5", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5", diff --git a/frontend/src/entities/model/model-api.ts b/frontend/src/entities/model/model-api.ts index 2303e683..89baf636 100644 --- a/frontend/src/entities/model/model-api.ts +++ b/frontend/src/entities/model/model-api.ts @@ -1,6 +1,7 @@ import type { ModelRouteDTO, ModelRouteGroupDTO } from "@/entities/model/types"; -import { apiRequest, type PaginatedDTO } from "@/shared/api/client"; +import { ApiError, apiEventStream, apiRequest, type PaginatedDTO } from "@/shared/api/client"; import { createObjectDecoder, createPaginatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder"; +import { i18n } from "@/shared/i18n"; import type { SortOrder } from "@/shared/lib/table-sort"; export type ListModelsInput = { @@ -76,8 +77,48 @@ export function listModelGroups(input: ListModelsInput): Promise { - return apiRequest("/api/admin/v1/models/sync", { method: "POST" }, decodeCountResult<{ synced: number }>("synced")); +type ModelSyncEventDTO = { + synced?: number; + completed?: number; + total?: number; + code?: string; + message?: string; +}; + +const decodeModelSyncEvent = createObjectDecoder("model sync event", { + synced: isOptional(isNumber), + completed: isOptional(isNumber), + total: isOptional(isNumber), + code: isOptional(isString), + message: isOptional(isString), +}); + +export type ModelSyncProgressDTO = { completed: number; total: number }; + +export async function syncModels(onProgress?: (progress: ModelSyncProgressDTO) => void): Promise<{ synced: number }> { + let result: { synced: number } | undefined; + await apiEventStream("/api/admin/v1/models/sync", { + method: "POST", + headers: { Accept: "text/event-stream" }, + }, decodeModelSyncEvent, ({ event, data }) => { + if (event === "progress" && typeof data.completed === "number" && typeof data.total === "number" && data.total > 0) { + onProgress?.({ completed: Math.min(Math.max(0, data.completed), data.total), total: data.total }); + return; + } + if (event === "complete" && typeof data.synced === "number") { + result = { synced: data.synced }; + return; + } + if (event === "error") { + const code = data.code ?? "modelSyncFailed"; + const message = i18n.exists(`apiErrors.${code}`) ? i18n.t(`apiErrors.${code}`) : (data.message ?? i18n.t("apiErrors.requestFailed")); + throw new ApiError(502, code, message); + } + }); + if (!result) { + throw new ApiError(502, "invalidResponse", i18n.t("apiErrors.invalidResponse")); + } + return result; } export type ModelAccountOptionDTO = { id: string; name: string }; diff --git a/frontend/src/features/models/models-page.tsx b/frontend/src/features/models/models-page.tsx index 8895513b..ec191b6e 100644 --- a/frontend/src/features/models/models-page.tsx +++ b/frontend/src/features/models/models-page.tsx @@ -34,6 +34,8 @@ import { cn } from "@/shared/lib/cn"; import { formatDateTime } from "@/shared/lib/format"; import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort"; +const modelSyncToastID = "model-sync-progress"; + export function ModelsPage() { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); @@ -135,14 +137,21 @@ export function ModelsPage() { }); const syncMutation = useMutation({ - mutationFn: syncModels, + mutationFn: () => syncModels((progress) => { + toast.loading(t("models.syncingProgress", progress), { id: modelSyncToastID }); + }), + onMutate: () => { + toast.loading(t("models.syncing"), { id: modelSyncToastID }); + }, onSuccess: (result) => { setSelected(new Set()); setPage(1); void queryClient.invalidateQueries({ queryKey: ["models"] }); - toast.success(t("models.synced", { count: result.synced })); + toast.success(t("models.synced", { count: result.synced }), { id: modelSyncToastID }); + }, + onError: (error) => { + toast.error(error instanceof Error ? error.message : t("errors.generic"), { id: modelSyncToastID }); }, - onError: showError, }); function showError(error: unknown): void { diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..b604036c 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -687,6 +687,8 @@ const resources = { deleteDescription: "将删除 {{name}} 及其密钥权限关联;如果上游账号仍支持该模型,后续同步会重新创建。", batchDeleteTitle: "删除所选 {{count}} 个模型路由?", batchDeleteDescription: "将同时删除所选路由及其密钥权限关联;上游账号仍支持的模型会在后续同步时重新创建。", + syncing: "正在准备同步账号模型能力", + syncingProgress: "正在同步账号模型能力 {{completed}} / {{total}}", synced: "已同步 {{count}} 个模型", created: "模型路由已创建", updated: "模型路由已更新", @@ -1341,7 +1343,7 @@ const resources = { accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" }, dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, - models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, + models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", syncing: "Preparing account capability sync", syncingProgress: "Syncing account capabilities {{completed}} / {{total}}", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, audits: { title: "Request audits", From d5da097512e0f50c0246bf5b2302fcc3be86d572 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:41:44 +0800 Subject: [PATCH 11/17] feat: support grok-4.6 xhigh and map max to xhigh --- .../internal/domain/model/reasoning_test.go | 8 +++ .../internal/infra/provider/cli/normalize.go | 11 ++-- .../infra/provider/cli/normalize_test.go | 54 ++++++++++++++++++- .../http/inference/model_list_test.go | 18 +++++++ frontend/src/shared/i18n/index.ts | 4 +- 5 files changed, 88 insertions(+), 7 deletions(-) diff --git a/backend/internal/domain/model/reasoning_test.go b/backend/internal/domain/model/reasoning_test.go index 0ed814d1..48e1f482 100644 --- a/backend/internal/domain/model/reasoning_test.go +++ b/backend/internal/domain/model/reasoning_test.go @@ -19,6 +19,7 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { {model: "grok-4.20-multi-agent-0309", want: []string{"low", "medium", "high", "xhigh"}}, {model: "grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, {model: "Build/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, + {model: "Console/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, {model: "grok-build-0.1", want: []string{"none"}}, {model: GrokComposer25Fast, want: []string{"none"}}, {model: "unknown-model", want: []string{"none"}}, @@ -43,6 +44,10 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { if !SupportsReasoningEffort("grok-4.6", "xhigh") || !SupportsReasoningEffort("Build/grok-4.6-xhigh", "xhigh") { t.Fatal("grok-4.6 must advertise xhigh") } + if !SupportsReasoningEffortForProvider(account.ProviderBuild, "grok-4.6", "xhigh") || + !SupportsReasoningEffortForProvider(account.ProviderConsole, "grok-4.6", "xhigh") { + t.Fatal("grok-4.6 xhigh must remain available through Build and Console") + } if SupportsReasoningEffort("grok-4.6", "none") || SupportsReasoningEffort("grok-4.6", "max") { t.Fatal("grok-4.6 must not advertise none/max") } @@ -119,4 +124,7 @@ func TestReasoningAliasPublicIDs(t *testing.T) { if got := ReasoningAliasPublicIDsForProvider(account.ProviderBuild, "grok-4.20-0309-reasoning"); len(got) != 3 { t.Fatalf("Console restriction leaked into Build aliases: %#v", got) } + if got := ReasoningAliasPublicIDsForProvider(account.ProviderConsole, "grok-4.6"); len(got) != 4 || got[3] != "grok-4.6-xhigh" { + t.Fatalf("Console grok-4.6 aliases = %#v", got) + } } diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index b1d6b15f..1a50f12b 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -118,8 +118,9 @@ func applyBuildResponseDefaults(payload map[string]json.RawMessage) (bool, error // normalizeBuildReasoningEffortPayload maps client aliases to levels accepted by // the selected Grok model. Grok 4.5 and unknown models retain the proven defensive -// xhigh/max -> high behavior; grok-4.6 and other explicitly supported xhigh models -// keep their value. Unverified max remains guarded. +// xhigh/max -> high behavior for models without an xhigh wire contract. Models +// that explicitly support xhigh keep xhigh and map the client-only max alias to +// that highest verified upstream level. func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, model string) bool { raw, exists := payload["reasoning"] if !exists || isEmptyJSON(raw) { @@ -157,7 +158,11 @@ func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, mo normalized = modeldomain.ReasoningEffortHigh } case "max": - normalized = modeldomain.ReasoningEffortHigh + if modeldomain.SupportsReasoningEffort(model, modeldomain.ReasoningEffortXHigh) { + normalized = modeldomain.ReasoningEffortXHigh + } else { + normalized = modeldomain.ReasoningEffortHigh + } default: return false } diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index 2b1331c6..ceb32a4e 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -52,11 +52,13 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { {name: "4.5 uppercase max", model: "grok-4.5", effort: "MAX", want: "high"}, {name: "multi-agent xhigh", model: "grok-4.20-multi-agent-0309", effort: "xhigh", want: "xhigh"}, {name: "multi-agent uppercase xhigh", model: "grok-4.20-multi-agent-0309", effort: "XHIGH", want: "xhigh"}, - {name: "multi-agent max remains guarded", model: "grok-4.20-multi-agent-0309", effort: "max", want: "high"}, + {name: "multi-agent max maps to highest supported effort", model: "grok-4.20-multi-agent-0309", effort: "max", want: "xhigh"}, {name: "4.6 xhigh", model: "grok-4.6", effort: "xhigh", want: "xhigh"}, {name: "4.6 uppercase xhigh", model: "grok-4.6", effort: "XHIGH", want: "xhigh"}, - {name: "4.6 max remains guarded", model: "grok-4.6", effort: "max", want: "high"}, + {name: "4.6 max maps to xhigh", model: "grok-4.6", effort: "max", want: "xhigh"}, + {name: "prefixed 4.6 uppercase max maps to xhigh", model: "Build/grok-4.6", effort: "MAX", want: "xhigh"}, {name: "unknown xhigh remains guarded", model: "future-model", effort: "xhigh", want: "high"}, + {name: "unknown max remains guarded", model: "future-model", effort: "max", want: "high"}, {name: "high", model: "grok-4.5", effort: "high", want: "high"}, {name: "medium", model: "grok-4.5", effort: "medium", want: "medium"}, } @@ -79,6 +81,54 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { } } +func TestNormalizeBuildMaxAcrossCompatibilityProtocols(t *testing.T) { + tests := []struct { + name string + body []byte + }{ + {name: "responses", body: []byte(`{"reasoning":{"effort":"max"},"input":"hello"}`)}, + {name: "chat completions", body: func() []byte { + converted, _, err := conversation.ConvertRequestWithOptions( + []byte(`{"model":"public","messages":[{"role":"user","content":"hello"}],"reasoning_effort":"max"}`), + "grok-4.6", + conversation.OperationChat, + ) + if err != nil { + t.Fatal(err) + } + return converted + }()}, + {name: "anthropic messages", body: func() []byte { + converted, _, err := conversation.ConvertRequestWithOptions( + []byte(`{"model":"public","max_tokens":64,"messages":[{"role":"user","content":"hello"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}}`), + "grok-4.6", + conversation.OperationMessages, + ) + if err != nil { + t.Fatal(err) + } + return converted + }()}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + normalized, err := normalizeBuildRequest(test.body, "grok-4.6") + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(normalized, &payload); err != nil { + t.Fatal(err) + } + reasoning, ok := payload["reasoning"].(map[string]any) + if !ok || reasoning["effort"] != "xhigh" { + t.Fatalf("reasoning = %#v, want max normalized to xhigh", payload["reasoning"]) + } + }) + } +} + func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index 9301d21b..ae18757d 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -69,6 +69,24 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) { } } +func TestAppendReasoningModelAliasesIncludesConsoleGrok46XHigh(t *testing.T) { + expanded := appendReasoningModelAliases([]modelListItem{{ + ID: "grok-4.6", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, + }}) + ids := make(map[string]bool, len(expanded)) + for _, item := range expanded { + ids[item.ID] = true + } + for _, want := range []string{"grok-4.6-low", "grok-4.6-medium", "grok-4.6-high", "grok-4.6-xhigh"} { + if !ids[want] { + t.Fatalf("missing Console alias %q in %#v", want, expanded) + } + } + if ids["grok-4.6-max"] { + t.Fatalf("client compatibility value max must not be advertised as a model alias: %#v", expanded) + } +} + func TestNewCodexModelCatalogIncludesRequiredProtocolFields(t *testing.T) { now := time.Unix(100, 0).UTC() items := newModelListItems([]modeldomain.Route{ diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 45e81c9c..b120075e 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -733,7 +733,7 @@ const resources = { modelAliases: "模型别名", modelAliasesDescription: "仅为当前可用且支持多个推理等级的模型生成后缀别名。", modelAliasesBuildSupport: "Grok Build:grok-4.6 支持 low / medium / high / xhigh;grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。", - modelAliasesConsoleSupport: "Grok Console:grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。", + modelAliasesConsoleSupport: "Grok Console:grok-4.6 支持 low / medium / high / xhigh;grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。", modelAliasesUnsupported: "Grok Web、图片模型和视频模型不生成推理等级后缀。", modelAliasesOn: "已开启:可发现并调用当前模型支持的推理等级别名。", modelAliasesOff: "已关闭:不生成动态推理别名;既有 Console 兼容别名不受影响。", @@ -1342,7 +1342,7 @@ const resources = { dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, - keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.6 supports low / medium / high / xhigh; grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, + keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.6 supports low / medium / high / xhigh; grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.6 supports low / medium / high / xhigh; grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, audits: { title: "Request audits", description: "Successful requests store metadata only. Failed requests retain a redacted and size-limited diagnostic snapshot.", From 6ed327b3d6d7e75dcc7fabac0b8097825a48fb24 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:50:19 +0800 Subject: [PATCH 12/17] feat: add grok-4.6 xhigh and Codex metadata --- .../transport/http/inference/codex_models.go | 1 + .../http/inference/model_list_test.go | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/backend/internal/transport/http/inference/codex_models.go b/backend/internal/transport/http/inference/codex_models.go index ee907cb9..da843eef 100644 --- a/backend/internal/transport/http/inference/codex_models.go +++ b/backend/internal/transport/http/inference/codex_models.go @@ -87,6 +87,7 @@ type grokModelCapability struct { // Codex catalogs never diverge from the levels each model actually supports. var grokCapabilities = map[string]grokModelCapability{ "grok-4.5": {500000, "xAI Grok 4.5 frontier model with reasoning and vision.", true}, + "grok-4.6": {500000, "xAI Grok 4.6 frontier model with reasoning and vision.", true}, "grok-4.3": {1000000, "xAI Grok 4.3 high-capacity reasoning model.", true}, "grok-build-0.1": {256000, "xAI Grok Build 0.1 coding model.", false}, "grok-4.20-0309-reasoning": {2000000, "xAI Grok 4.20 reasoning model.", true}, diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index ae18757d..49947352 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -128,6 +128,42 @@ func TestNewCodexModelCatalogIncludesRequiredProtocolFields(t *testing.T) { } } +func TestCodexCatalogUsesGrok46MetadataForBaseAndXHighAlias(t *testing.T) { + items := []modelListItem{ + {ID: "grok-4.6", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses}, + {ID: "grok-4.6-xhigh", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses}, + } + models := newCodexModelCatalog(items).Models + if len(models) != 2 { + t.Fatalf("model count = %d, want 2", len(models)) + } + + base := models[0] + if base.ContextWindow != 500000 || base.MaxContextWindow != 500000 { + t.Fatalf("grok-4.6 context window = %d/%d, want 500000/500000", base.ContextWindow, base.MaxContextWindow) + } + if base.Description != "xAI Grok 4.6 frontier model with reasoning and vision." { + t.Fatalf("grok-4.6 description = %q", base.Description) + } + if len(base.InputModalities) != 2 || base.InputModalities[0] != "text" || base.InputModalities[1] != "image" { + t.Fatalf("grok-4.6 input modalities = %#v, want text/image", base.InputModalities) + } + if base.DefaultReasoningLevel != "medium" || len(base.SupportedReasoningLevels) != 4 || base.SupportedReasoningLevels[3].Effort != "xhigh" { + t.Fatalf("grok-4.6 reasoning metadata = default %q, levels %#v", base.DefaultReasoningLevel, base.SupportedReasoningLevels) + } + if !base.SupportsReasoningSummaryParameter || !base.SupportsReasoningSummaries { + t.Fatalf("grok-4.6 reasoning support missing: %#v", base) + } + + alias := models[1] + if alias.ContextWindow != base.ContextWindow || alias.MaxContextWindow != base.MaxContextWindow || alias.Description != base.Description { + t.Fatalf("grok-4.6-xhigh did not inherit base metadata: %#v", alias) + } + if len(alias.InputModalities) != 2 || alias.DefaultReasoningLevel != "xhigh" || len(alias.SupportedReasoningLevels) != 1 || alias.SupportedReasoningLevels[0].Effort != "xhigh" { + t.Fatalf("grok-4.6-xhigh metadata = %#v", alias) + } +} + func TestCodexCatalogMarksConsoleGrok420AsFixedReasoning(t *testing.T) { entry := newCodexModelCatalog([]modelListItem{{ ID: "grok-4.20-0309-reasoning", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, From ed594187b0be3597ea715b0a369e519db98440e9 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:55:25 +0800 Subject: [PATCH 13/17] fix: recover Statsig meta from index 404 without weakening status validation --- .../internal/infra/provider/web/statsig.go | 84 ++++++----- .../infra/provider/web/statsig_test.go | 141 +++++++++++++++--- 2 files changed, 171 insertions(+), 54 deletions(-) diff --git a/backend/internal/infra/provider/web/statsig.go b/backend/internal/infra/provider/web/statsig.go index c313eff9..c7dfdae3 100644 --- a/backend/internal/infra/provider/web/statsig.go +++ b/backend/internal/infra/provider/web/statsig.go @@ -5,6 +5,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -29,6 +30,8 @@ const ( statsigResponseLimit = 4 << 10 ) +var errStatsigMetaMissing = errors.New("Grok index 缺少 grok-site-verification") + type statsigCacheEntry struct { value string expiresAt time.Time @@ -279,41 +282,47 @@ func fetchStatsigMetaContentWithDo(ctx context.Context, baseURL, token string, l if do == nil { return "", fmt.Errorf("Statsig 获取缺少出口租约") } - var indexErr error - for _, path := range []string{"/index", "/"} { - content, err := fetchStatsigMetaContentPath(ctx, baseURL, token, lease, path, do) - if err == nil { - return content, nil - } - if path == "/index" { - indexErr = err - if !shouldFallbackStatsigMeta(err) { - return "", err - } - continue - } + index, err := fetchStatsigMetaResponse(ctx, baseURL, token, lease, "/index", do) + if err != nil { return "", err } - if indexErr != nil { - return "", indexErr + if index.statusCode >= 200 && index.statusCode < 300 { + // A successful index response without the verification meta remains a hard + // protocol failure. Falling back here would hide a changed upstream page. + return extractStatsigMetaContent(index.body) } - return "", fmt.Errorf("Grok index 缺少 grok-site-verification") + if index.statusCode != http.StatusNotFound { + return "", statsigMetaStatusError("/index", index.statusCode) + } + if content, extractErr := extractStatsigMetaContent(index.body); extractErr == nil { + return content, nil + } else if !errors.Is(extractErr, errStatsigMetaMissing) { + return "", extractErr + } + + // /index currently returns a branded 404. Only that exact status with a + // missing meta is allowed to fall back to the canonical root page. + root, err := fetchStatsigMetaResponse(ctx, baseURL, token, lease, "/", do) + if err != nil { + return "", err + } + if root.statusCode < 200 || root.statusCode >= 300 { + return "", statsigMetaStatusError("/", root.statusCode) + } + return extractStatsigMetaContent(root.body) } -func shouldFallbackStatsigMeta(err error) bool { - if err == nil { - return false - } - message := err.Error() - return strings.Contains(message, "缺少 grok-site-verification") || strings.Contains(message, "Grok index 返回 ") +type statsigMetaResponse struct { + statusCode int + body []byte } -func fetchStatsigMetaContentPath(ctx context.Context, baseURL, token string, lease *infraegress.Lease, path string, do func(*http.Request) (*http.Response, error)) (string, error) { +func fetchStatsigMetaResponse(ctx context.Context, baseURL, token string, lease *infraegress.Lease, path string, do func(*http.Request) (*http.Response, error)) (statsigMetaResponse, error) { requestCtx, cancel := context.WithTimeout(infraegress.WithPhysicalCallStage(ctx, "statsig_meta"), 15*time.Second) defer cancel() request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+path, nil) if err != nil { - return "", err + return statsigMetaResponse{}, err } request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") request.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd") @@ -330,28 +339,31 @@ func fetchStatsigMetaContentPath(ctx context.Context, baseURL, token string, lea } response, err := do(request) if err != nil { - return "", err + return statsigMetaResponse{}, err } defer response.Body.Close() body, err := io.ReadAll(io.LimitReader(response.Body, statsigMetaBodyLimit+1)) if err != nil { - return "", err + return statsigMetaResponse{}, err } if len(body) > statsigMetaBodyLimit { - return "", fmt.Errorf("Grok index 超过安全上限") + return statsigMetaResponse{}, statsigMetaOversizeError(path) } - return statsigMetaFromHTTP(response.StatusCode, body) + return statsigMetaResponse{statusCode: response.StatusCode, body: body}, nil } -func statsigMetaFromHTTP(status int, body []byte) (string, error) { - content, err := extractStatsigMetaContent(body) - if err == nil { - return content, nil +func statsigMetaStatusError(path string, statusCode int) error { + if path == "/" { + return fmt.Errorf("Grok 首页返回 %d", statusCode) } - if status < 200 || status >= 300 { - return "", fmt.Errorf("Grok index 返回 %d", status) + return fmt.Errorf("Grok index 返回 %d", statusCode) +} + +func statsigMetaOversizeError(path string) error { + if path == "/" { + return fmt.Errorf("Grok 首页超过安全上限") } - return "", err + return fmt.Errorf("Grok index 超过安全上限") } func extractStatsigMetaContent(body []byte) (string, error) { @@ -360,7 +372,7 @@ func extractStatsigMetaContent(body []byte) (string, error) { switch tokenizer.Next() { case html.ErrorToken: if tokenizer.Err() == io.EOF { - return "", fmt.Errorf("Grok index 缺少 grok-site-verification") + return "", errStatsigMetaMissing } return "", tokenizer.Err() case html.StartTagToken, html.SelfClosingTagToken: diff --git a/backend/internal/infra/provider/web/statsig_test.go b/backend/internal/infra/provider/web/statsig_test.go index 0ac543d3..d7953366 100644 --- a/backend/internal/infra/provider/web/statsig_test.go +++ b/backend/internal/infra/provider/web/statsig_test.go @@ -19,25 +19,10 @@ type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) } -func TestStatsigMetaFromHTTPAcceptsIndexNotFoundWithVerification(t *testing.T) { - body := []byte(``) - value, err := statsigMetaFromHTTP(http.StatusNotFound, body) - if err != nil || value != "meta-value" { - t.Fatalf("value=%q err=%v", value, err) - } -} +type failingStatsigBody struct{} -func TestStatsigMetaFromHTTPKeepsMissingVerificationErrorOnSuccessStatus(t *testing.T) { - if _, err := statsigMetaFromHTTP(http.StatusOK, []byte(``)); err == nil || !strings.Contains(err.Error(), "缺少 grok-site-verification") { - t.Fatalf("err=%v", err) - } -} - -func TestStatsigMetaFromHTTPPreservesStatusWhenVerificationMissing(t *testing.T) { - if _, err := statsigMetaFromHTTP(http.StatusNotFound, []byte(``)); err == nil || !strings.Contains(err.Error(), "Grok index 返回 404") { - t.Fatalf("err=%v", err) - } -} +func (failingStatsigBody) Read([]byte) (int, error) { return 0, errors.New("read failed") } +func (failingStatsigBody) Close() error { return nil } func TestFetchStatsigMetaContentFallsBackToRootWhenIndexHasNoVerification(t *testing.T) { var paths []string @@ -80,6 +65,126 @@ func TestFetchStatsigMetaContentDoesNotFallbackWhenIndex404HasVerification(t *te } } +func TestFetchStatsigMetaContentDoesNotFallbackWhenSuccessfulIndexHasNoVerification(t *testing.T) { + var paths []string + do := func(request *http.Request) (*http.Response, error) { + paths = append(paths, request.URL.Path) + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if !errors.Is(err, errStatsigMetaMissing) { + t.Fatalf("err=%v", err) + } + if len(paths) != 1 || paths[0] != "/index" { + t.Fatalf("successful index without verification must not fall back: paths=%v", paths) + } +} + +func TestFetchStatsigMetaContentRejectsNon404IndexStatuses(t *testing.T) { + for _, status := range []int{http.StatusMovedPermanently, http.StatusForbidden, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusServiceUnavailable} { + for _, withMeta := range []bool{false, true} { + t.Run(fmt.Sprintf("status_%d_meta_%t", status, withMeta), func(t *testing.T) { + body := `` + if withMeta { + body = `` + } + var calls int + do := func(request *http.Request) (*http.Response, error) { + calls++ + if request.URL.Path != "/index" { + t.Fatalf("unexpected fallback to %q", request.URL.Path) + } + return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("Grok index 返回 %d", status)) { + t.Fatalf("err=%v", err) + } + if calls != 1 { + t.Fatalf("calls=%d", calls) + } + }) + } + } +} + +func TestFetchStatsigMetaContentRequiresSuccessfulRoot(t *testing.T) { + for _, withMeta := range []bool{false, true} { + t.Run(fmt.Sprintf("meta_%t", withMeta), func(t *testing.T) { + body := `` + if withMeta { + body = `` + } + do := func(request *http.Request) (*http.Response, error) { + if request.URL.Path == "/index" { + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + } + return &http.Response{StatusCode: http.StatusServiceUnavailable, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || !strings.Contains(err.Error(), "Grok 首页返回 503") { + t.Fatalf("err=%v", err) + } + }) + } +} + +func TestFetchStatsigMetaContentRequiresVerificationOnSuccessfulRoot(t *testing.T) { + do := func(request *http.Request) (*http.Response, error) { + status := http.StatusOK + if request.URL.Path == "/index" { + status = http.StatusNotFound + } + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(strings.NewReader(``)), + Header: http.Header{}, + }, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if !errors.Is(err, errStatsigMetaMissing) { + t.Fatalf("err=%v", err) + } +} + +func TestFetchStatsigMetaContentDoesNotFallbackOnTransportReadOrOversizeFailure(t *testing.T) { + t.Run("transport", func(t *testing.T) { + var calls int + do := func(*http.Request) (*http.Response, error) { + calls++ + return nil, errors.New("dial failed") + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || err.Error() != "dial failed" || calls != 1 { + t.Fatalf("err=%v calls=%d", err, calls) + } + }) + + t.Run("read", func(t *testing.T) { + var calls int + do := func(*http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusNotFound, Body: failingStatsigBody{}, Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || err.Error() != "read failed" || calls != 1 { + t.Fatalf("err=%v calls=%d", err, calls) + } + }) + + t.Run("oversize", func(t *testing.T) { + var calls int + do := func(*http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(strings.Repeat("x", statsigMetaBodyLimit+1))), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || !strings.Contains(err.Error(), "超过安全上限") || calls != 1 { + t.Fatalf("err=%v calls=%d", err, calls) + } + }) +} + func TestExtractStatsigMetaContentAcceptsCurrentMetaName(t *testing.T) { for _, name := range []string{"grok-site―verification", "grok-site-verification"} { body := []byte(``) From 49daa16cf76bc7348533a79890cde383f98ac707 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 23:00:26 +0800 Subject: [PATCH 14/17] fix: make serialized Build detect observers panic-safe --- .../application/account/build_detect_test.go | 110 +++++++++++++----- .../internal/application/account/service.go | 14 ++- 2 files changed, 86 insertions(+), 38 deletions(-) diff --git a/backend/internal/application/account/build_detect_test.go b/backend/internal/application/account/build_detect_test.go index 9fec90f7..9d0ab222 100644 --- a/backend/internal/application/account/build_detect_test.go +++ b/backend/internal/application/account/build_detect_test.go @@ -9,6 +9,7 @@ import ( "net/http" "path/filepath" "strconv" + "sync/atomic" "testing" "time" @@ -294,45 +295,15 @@ func TestDetectBuildAccountsStreamsInvalidOnlyForAll(t *testing.T) { } func TestDetectBuildAccountsSerializesItemObserver(t *testing.T) { - ctx := context.Background() - database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "detect-observer.db")) - if err != nil { - t.Fatal(err) - } - defer database.Close() - if err := database.InitializeSchema(ctx); err != nil { - t.Fatal(err) - } - cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) - if err != nil { - t.Fatal(err) - } - accessToken, err := cipher.Encrypt("access-token") - if err != nil { - t.Fatal(err) - } - repo := relational.NewAccountRepository(database) const accountCount = 8 - for index := range accountCount { - if _, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ - Provider: accountdomain.ProviderBuild, Name: "invalid-" + strconv.Itoa(index), UserID: "user-invalid-" + strconv.Itoa(index), - SourceKey: "detect-invalid-" + strconv.Itoa(index), EncryptedAccessToken: accessToken, - Enabled: true, AuthStatus: accountdomain.AuthStatusActive, RefreshPermanent: true, Priority: 1, MaxConcurrent: 1, - }); err != nil { - t.Fatal(err) - } - } - service := NewService(repo, nil, nil, nil, provider.NewRegistry(detectResponsesAdapter{ - status: http.StatusUnauthorized, - }), cipher, nil) - service.SetDetectPool(batch.NewPool(accountCount)) + service := newConcurrentInvalidBuildDetectService(t, accountCount) started := make(chan struct{}, accountCount) release := make(chan struct{}) var items []BuildDetectItemResult errCh := make(chan error, 1) go func() { - _, _, detectErr := service.DetectBuildAccountsWithProgress(ctx, nil, true, nil, func(item BuildDetectItemResult) error { + _, _, detectErr := service.DetectBuildAccountsWithProgress(context.Background(), nil, true, nil, func(item BuildDetectItemResult) error { started <- struct{}{} <-release items = append(items, item) @@ -355,3 +326,78 @@ func TestDetectBuildAccountsSerializesItemObserver(t *testing.T) { t.Fatalf("serialized items = %d, want %d", len(items), accountCount) } } + +func TestDetectBuildAccountsObserverPanicDoesNotDeadlock(t *testing.T) { + const accountCount = 8 + service := newConcurrentInvalidBuildDetectService(t, accountCount) + + type detectResult struct { + succeeded int + failed int + err error + } + var calls atomic.Int64 + resultCh := make(chan detectResult, 1) + go func() { + succeeded, failed, err := service.DetectBuildAccountsWithProgress(context.Background(), nil, true, nil, func(BuildDetectItemResult) error { + if calls.Add(1) == 1 { + panic("item observer panic") + } + return nil + }) + resultCh <- detectResult{succeeded: succeeded, failed: failed, err: err} + }() + + timer := time.NewTimer(2 * time.Second) + defer timer.Stop() + select { + case result := <-resultCh: + if result.err != nil { + t.Fatal(result.err) + } + if result.succeeded != 0 || result.failed != accountCount { + t.Fatalf("summary succeeded=%d failed=%d, want 0/%d", result.succeeded, result.failed, accountCount) + } + if got := calls.Load(); got != accountCount { + t.Fatalf("observer calls = %d, want %d", got, accountCount) + } + case <-timer.C: + t.Fatal("itemObserver panic deadlocked Build account detection") + } +} + +func newConcurrentInvalidBuildDetectService(t *testing.T, accountCount int) *Service { + t.Helper() + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "detect-observer.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + accessToken, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + repo := relational.NewAccountRepository(database) + for index := range accountCount { + if _, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "invalid-" + strconv.Itoa(index), UserID: "user-invalid-" + strconv.Itoa(index), + SourceKey: "detect-invalid-" + strconv.Itoa(index), EncryptedAccessToken: accessToken, + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, RefreshPermanent: true, Priority: 1, MaxConcurrent: 1, + }); err != nil { + t.Fatal(err) + } + } + service := NewService(repo, nil, nil, nil, provider.NewRegistry(detectResponsesAdapter{ + status: http.StatusUnauthorized, + }), cipher, nil) + service.SetDetectPool(batch.NewPool(accountCount)) + return service +} diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 4261c6c7..5d45a0f7 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -3717,7 +3717,7 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin return 0, 0, err } } - var progressMu sync.Mutex + var observerMu sync.Mutex var progressErr error completed := 0 runCtx, cancel := context.WithCancel(ctx) @@ -3725,9 +3725,11 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin summary, err := batch.ForEachObserved(runCtx, ids, batch.Options{Workers: pool.Limit(), Pool: pool}, func(workCtx context.Context, id uint64) (BuildDetectItemResult, error) { item := s.detectBuildAccount(workCtx, id) if itemObserver != nil && (selectedMode || item.Outcome == BuildDetectOutcomeInvalid) { - progressMu.Lock() - notifyErr := itemObserver(item) - progressMu.Unlock() + notifyErr := func() error { + observerMu.Lock() + defer observerMu.Unlock() + return itemObserver(item) + }() if notifyErr != nil { return item, notifyErr } @@ -3744,8 +3746,8 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin if errors.As(result.Err, &panicErr) { s.logger.Error("account_bulk_task_panicked", "operation", "build_detect", "account_id", ids[index], "error", panicErr, "stack", string(panicErr.Stack)) } - progressMu.Lock() - defer progressMu.Unlock() + observerMu.Lock() + defer observerMu.Unlock() completed++ if progress != nil { if notifyErr := progress(completed, len(ids)); notifyErr != nil && progressErr == nil { From 902c0d872783415aa46b31592eb82bf5a239fc9d Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 08:43:19 +0800 Subject: [PATCH 15/17] feat: add scalable degraded-account monitoring --- backend/internal/application/audit/degrade.go | 330 ++++++++--------- .../application/audit/degrade_test.go | 158 +++++++- backend/internal/domain/audit/degrade.go | 10 +- backend/internal/domain/audit/degrade_test.go | 6 +- .../relational/audit_repository.go | 338 +++++++++++++++--- .../relational/audit_repository_test.go | 11 + .../infra/persistence/relational/schema.go | 1 + backend/internal/repository/audit.go | 96 ++++- .../internal/transport/http/audit/handler.go | 86 +++-- .../transport/http/audit/handler_test.go | 6 +- .../internal/transport/http/egress/handler.go | 3 + .../transport/http/egress/handler_test.go | 4 +- .../quality-guard/degrade-accounts-panel.tsx | 169 +++++---- .../quality-guard/quality-guard-api.ts | 34 +- .../quality-guard/quality-guard-page.tsx | 7 +- frontend/src/shared/components/pagination.tsx | 10 +- frontend/src/shared/i18n/index.ts | 16 +- 17 files changed, 887 insertions(+), 398 deletions(-) diff --git a/backend/internal/application/audit/degrade.go b/backend/internal/application/audit/degrade.go index 96758715..06880b28 100644 --- a/backend/internal/application/audit/degrade.go +++ b/backend/internal/application/audit/degrade.go @@ -3,7 +3,7 @@ package audit import ( "context" "math" - "sort" + "strings" "time" auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" @@ -11,19 +11,31 @@ import ( ) const ( - degradeWindow1h = "1h" - degradeWindow6h = "6h" - degradeWindow24h = "24h" - degradeWindow7d = "7d" - degradeEventLimit = 20_000 - degradeRecentEventCap = 80 + degradeWindow1h = "1h" + degradeWindow6h = "6h" + degradeWindow24h = "24h" + degradeWindow7d = "7d" + degradeRecentEventCap = 80 + degradeDefaultPage = 1 + degradeDefaultPageSize = 50 + degradeMaxPageSize = 100 ) type DegradeThresholds struct { - SoftTPS float64 - HardTPS float64 - MinGenMS int64 - MinOut int64 + SoftTPS float64 + HardTPS float64 + MinGenMS int64 + MinOut int64 + FailClosed bool +} + +type DegradeAccountFilter struct { + Search string + Status string + Class string + MinHits int + Page int + PageSize int } type DegradeSummary struct { @@ -34,30 +46,39 @@ type DegradeSummary struct { Series []DegradeBucket Nodes []DegradeNode Accounts []DegradeAccount + AccountPage DegradeAccountPage Events []DegradeEventView } type DegradeTotals struct { - Hits int - Accounts int - StillEnabled int - Disabled int - Hard int - Soft int - Burst int + Hits int64 + Accounts int64 + StillEnabled int64 + Disabled int64 + Deleted int64 + Hard int64 + Soft int64 + Burst int64 MaxTPS float64 } +type DegradeAccountPage struct { + Page int + PageSize int + Total int64 + HasMore bool +} + type DegradeBucket struct { Label string `json:"label"` - Count int `json:"count"` - Severe int `json:"severe"` + Count int64 `json:"count"` + Severe int64 `json:"severe"` } type DegradeNode struct { Name string `json:"name"` - Hits int `json:"hits"` - Accounts int `json:"accounts"` + Hits int64 `json:"hits"` + Accounts int64 `json:"accounts"` MaxTPS float64 `json:"maxTPS"` } @@ -65,14 +86,14 @@ type DegradeAccount struct { ID uint64 Name string Email string - Hits int + Hits int64 MaxTPS float64 - Classes map[string]int + Classes map[string]int64 Nodes []string Last time.Time Enabled bool - BFS int Found bool + BFS int } type DegradeEventView struct { @@ -88,19 +109,34 @@ type DegradeEventView struct { Model string } -func (s *Service) DegradeSummary(ctx context.Context, window string, thresholds DegradeThresholds) (DegradeSummary, error) { +type degradeBucketSpec struct { + Range repository.DegradeBucketRange + Label string +} + +func (s *Service) DegradeSummary(ctx context.Context, window string, thresholds DegradeThresholds, filter DegradeAccountFilter) (DegradeSummary, error) { window, start, end, err := resolveDegradeWindow(window, s.now().UTC()) if err != nil { return DegradeSummary{}, err } thresholds = normalizeDegradeThresholds(thresholds) - events, err := s.audits.ListDegradeEvents(ctx, repository.DegradeEventQuery{ - Start: start, End: end, MinOutputTokens: thresholds.MinOut, Limit: degradeEventLimit, + filter = normalizeDegradeAccountFilter(filter) + bucketSpecs := degradeBucketSpecs(window, start, end) + bucketRanges := make([]repository.DegradeBucketRange, 0, len(bucketSpecs)) + for _, spec := range bucketSpecs { + bucketRanges = append(bucketRanges, spec.Range) + } + data, err := s.audits.SummarizeDegrade(ctx, repository.DegradeSummaryQuery{ + Start: start, End: end, SoftTPS: thresholds.SoftTPS, HardTPS: thresholds.HardTPS, + MinGenerationMS: thresholds.MinGenMS, MinOutputTokens: thresholds.MinOut, FailClosed: thresholds.FailClosed, + AccountSearch: filter.Search, AccountStatus: filter.Status, AccountClass: filter.Class, MinHits: filter.MinHits, + AccountOffset: (filter.Page - 1) * filter.PageSize, AccountLimit: filter.PageSize, + Buckets: bucketRanges, RecentLimit: degradeRecentEventCap, }) if err != nil { return DegradeSummary{}, err } - return buildDegradeSummary(window, end, thresholds, events), nil + return buildDegradeSummary(window, end, thresholds, filter, bucketSpecs, data), nil } func resolveDegradeWindow(value string, now time.Time) (string, time.Time, time.Time, error) { @@ -143,189 +179,109 @@ func normalizeDegradeThresholds(value DegradeThresholds) DegradeThresholds { return value } -func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresholds, events []repository.DegradeEvent) DegradeSummary { - type accAgg struct { - hits int - maxTPS float64 - classes map[string]int - nodes map[string]struct{} - last time.Time - name string - email string - enabled bool - found bool - bfs int +func normalizeDegradeAccountFilter(value DegradeAccountFilter) DegradeAccountFilter { + value.Search = strings.TrimSpace(value.Search) + if value.Status != "enabled" && value.Status != "disabled" && value.Status != "deleted" { + value.Status = "" } - type nodeAgg struct { - hits int - accounts map[uint64]struct{} - maxTPS float64 + if value.Class != auditdomain.DegradeClassBurst && value.Class != auditdomain.DegradeClassSoft && value.Class != auditdomain.DegradeClassHard { + value.Class = "" } - accounts := map[uint64]*accAgg{} - nodes := map[string]*nodeAgg{} - classCounts := map[string]int{} - var classified []DegradeEventView - var maxTPS float64 + if value.MinHits < 1 { + value.MinHits = 1 + } + if value.Page < 1 { + value.Page = degradeDefaultPage + } + if value.PageSize < 1 || value.PageSize > degradeMaxPageSize { + value.PageSize = degradeDefaultPageSize + } + return value +} - for _, event := range events { - class, tps, _ := auditdomain.ClassifyOutputSpeed(event.OutputTokens, event.FirstTokenMS, event.DurationMS, thresholds.SoftTPS, thresholds.HardTPS, thresholds.MinGenMS) - if class == "" { - continue - } - classCounts[class]++ - if tps > maxTPS { - maxTPS = tps - } - nodeName := event.EgressNodeName +func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresholds, filter DegradeAccountFilter, bucketSpecs []degradeBucketSpec, data repository.DegradeSummaryResult) DegradeSummary { + accounts := make([]DegradeAccount, 0, len(data.Accounts)) + for _, value := range data.Accounts { + accounts = append(accounts, DegradeAccount{ + ID: value.ID, Name: value.Name, Email: value.Email, Hits: value.Hits, MaxTPS: round(value.MaxTPS, 1), + Classes: map[string]int64{ + auditdomain.DegradeClassBurst: value.Burst, + auditdomain.DegradeClassSoft: value.Soft, + auditdomain.DegradeClassHard: value.Hard, + }, + Nodes: value.Nodes, Last: value.Last, Enabled: value.Enabled, Found: value.Found, BFS: value.BuildBotFlagSource, + }) + } + nodes := make([]DegradeNode, 0, len(data.Nodes)) + for _, value := range data.Nodes { + nodes = append(nodes, DegradeNode{Name: value.Name, Hits: value.Hits, Accounts: value.Accounts, MaxTPS: round(value.MaxTPS, 1)}) + } + events := make([]DegradeEventView, 0, len(data.Events)) + for _, value := range data.Events { + nodeName := value.EgressNodeName if nodeName == "" { nodeName = "?" } - classified = append(classified, DegradeEventView{ - ID: event.ID, RequestID: event.RequestID, AccountID: event.AccountID, AccountName: event.AccountName, - NodeName: nodeName, OutputTokens: event.OutputTokens, TPS: math.Round(tps*100) / 100, Class: class, - CreatedAt: event.CreatedAt, Model: event.Model, - }) - if event.AccountID == nil || *event.AccountID == 0 { - continue - } - id := *event.AccountID - rec := accounts[id] - if rec == nil { - rec = &accAgg{classes: map[string]int{}, nodes: map[string]struct{}{}} - accounts[id] = rec - } - rec.hits++ - if tps > rec.maxTPS { - rec.maxTPS = tps - } - rec.classes[class]++ - rec.nodes[nodeName] = struct{}{} - if event.CreatedAt.After(rec.last) { - rec.last = event.CreatedAt - rec.name = event.AccountName - } - if rec.name == "" { - rec.name = event.AccountName - } - if event.Email != "" { - rec.email = event.Email - } - if event.Enabled != nil { - rec.enabled = *event.Enabled - rec.found = true - } - if event.BuildBotFlagSource > rec.bfs { - rec.bfs = event.BuildBotFlagSource - } - nd := nodes[nodeName] - if nd == nil { - nd = &nodeAgg{accounts: map[uint64]struct{}{}} - nodes[nodeName] = nd - } - nd.hits++ - nd.accounts[id] = struct{}{} - if tps > nd.maxTPS { - nd.maxTPS = tps - } - } - - accountViews := make([]DegradeAccount, 0, len(accounts)) - enabled, disabled := 0, 0 - for id, rec := range accounts { - if rec.found && rec.enabled { - enabled++ - } else { - disabled++ - } - nodeNames := make([]string, 0, len(rec.nodes)) - for name := range rec.nodes { - nodeNames = append(nodeNames, name) - } - sort.Strings(nodeNames) - email := rec.email - if email == "" { - email = rec.name - } - accountViews = append(accountViews, DegradeAccount{ - ID: id, Name: rec.name, Email: email, Hits: rec.hits, MaxTPS: math.Round(rec.maxTPS*10) / 10, - Classes: rec.classes, Nodes: nodeNames, Last: rec.last, Enabled: rec.found && rec.enabled, BFS: rec.bfs, Found: rec.found, + events = append(events, DegradeEventView{ + ID: value.ID, RequestID: value.RequestID, AccountID: value.AccountID, AccountName: value.AccountName, + NodeName: nodeName, OutputTokens: value.OutputTokens, TPS: round(value.TPS, 2), Class: value.Class, + CreatedAt: value.CreatedAt, Model: value.Model, }) } - sort.Slice(accountViews, func(i, j int) bool { - if accountViews[i].Hits != accountViews[j].Hits { - return accountViews[i].Hits > accountViews[j].Hits + series := make([]DegradeBucket, len(bucketSpecs)) + for index, spec := range bucketSpecs { + series[index].Label = spec.Label + } + for _, value := range data.Buckets { + if value.Index >= 0 && value.Index < len(series) { + series[value.Index].Count = value.Count + series[value.Index].Severe = value.Severe } - return accountViews[i].MaxTPS > accountViews[j].MaxTPS - }) - - nodeViews := make([]DegradeNode, 0, len(nodes)) - for name, rec := range nodes { - nodeViews = append(nodeViews, DegradeNode{Name: name, Hits: rec.hits, Accounts: len(rec.accounts), MaxTPS: math.Round(rec.maxTPS*10) / 10}) } - sort.Slice(nodeViews, func(i, j int) bool { return nodeViews[i].Hits > nodeViews[j].Hits }) - - recent := classified - if len(recent) > degradeRecentEventCap { - recent = recent[:degradeRecentEventCap] - } - return DegradeSummary{ Window: window, GeneratedAt: now, Thresholds: thresholds, Totals: DegradeTotals{ - Hits: len(classified), Accounts: len(accounts), StillEnabled: enabled, Disabled: disabled, - Hard: classCounts[auditdomain.DegradeClassHard], Soft: classCounts[auditdomain.DegradeClassSoft], - Burst: classCounts[auditdomain.DegradeClassBurst], MaxTPS: maxTPS, + Hits: data.Totals.Hits, Accounts: data.Totals.Accounts, StillEnabled: data.Totals.StillEnabled, + Disabled: data.Totals.Disabled, Deleted: data.Totals.Deleted, Hard: data.Totals.Hard, + Soft: data.Totals.Soft, Burst: data.Totals.Burst, MaxTPS: round(data.Totals.MaxTPS, 2), }, - Series: bucketDegradeSeries(classified, window, now), - Nodes: nodeViews, Accounts: accountViews, Events: recent, + Series: series, Nodes: nodes, Accounts: accounts, + AccountPage: DegradeAccountPage{ + Page: data.AccountOffset/filter.PageSize + 1, PageSize: filter.PageSize, Total: data.AccountTotal, + HasMore: int64(data.AccountOffset+filter.PageSize) < data.AccountTotal, + }, + Events: events, } } -func bucketDegradeSeries(events []DegradeEventView, window string, now time.Time) []DegradeBucket { - var step time.Duration - var start time.Time - var label func(time.Time) string +func degradeBucketSpecs(window string, start, end time.Time) []degradeBucketSpec { + step := 5 * time.Minute + label := func(value time.Time) string { return value.Format("15:04") } switch window { case degradeWindow7d: step = 2 * time.Hour - start = now.Add(-7 * 24 * time.Hour) - label = func(t time.Time) string { return t.Format("01-02 15:00") } + label = func(value time.Time) string { return value.Format("01-02 15:00") } case degradeWindow24h: step = time.Hour - start = now.Add(-24 * time.Hour) - label = func(t time.Time) string { return t.Format("15:00") } + label = func(value time.Time) string { return value.Format("15:00") } case degradeWindow6h: step = 20 * time.Minute - start = now.Add(-6 * time.Hour) - label = func(t time.Time) string { return t.Format("15:04") } - default: - step = 5 * time.Minute - start = now.Add(-time.Hour) - label = func(t time.Time) string { return t.Format("15:04") } } - var buckets []time.Time - for cursor := start; cursor.Before(now); cursor = cursor.Add(step) { - buckets = append(buckets, cursor) - } - if len(buckets) == 0 { - return nil - } - counts := make([]int, len(buckets)) - severe := make([]int, len(buckets)) - stepSeconds := step.Seconds() - for _, event := range events { - idx := int(event.CreatedAt.Sub(start).Seconds() / stepSeconds) - if idx < 0 || idx >= len(counts) { - continue - } - counts[idx]++ - if event.Class == auditdomain.DegradeClassHard || event.Class == auditdomain.DegradeClassBurst { - severe[idx]++ + var result []degradeBucketSpec + for cursor := start; cursor.Before(end); cursor = cursor.Add(step) { + bucketEnd := cursor.Add(step) + if bucketEnd.After(end) { + bucketEnd = end } + result = append(result, degradeBucketSpec{ + Range: repository.DegradeBucketRange{Start: cursor, End: bucketEnd}, + Label: label(cursor), + }) } - out := make([]DegradeBucket, len(buckets)) - for i, bucket := range buckets { - out[i] = DegradeBucket{Label: label(bucket), Count: counts[i], Severe: severe[i]} - } - return out + return result +} + +func round(value float64, places int) float64 { + factor := math.Pow10(places) + return math.Round(value*factor) / factor } diff --git a/backend/internal/application/audit/degrade_test.go b/backend/internal/application/audit/degrade_test.go index 24d40fe7..4705aa37 100644 --- a/backend/internal/application/audit/degrade_test.go +++ b/backend/internal/application/audit/degrade_test.go @@ -2,11 +2,13 @@ package audit import ( "context" + "fmt" "log/slog" "path/filepath" "testing" "time" + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" ) @@ -35,7 +37,7 @@ func TestDegradeSummaryClassifiesStreamingAnomalies(t *testing.T) { } service := NewService(repo, slog.Default(), 8, 4, time.Second) service.now = func() time.Time { return now } - summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}) + summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{}) if err != nil { t.Fatal(err) } @@ -45,6 +47,158 @@ func TestDegradeSummaryClassifiesStreamingAnomalies(t *testing.T) { if len(summary.Accounts) != 1 || summary.Accounts[0].ID != 7 || summary.Accounts[0].Hits != 1 { t.Fatalf("accounts = %#v", summary.Accounts) } + if summary.Totals.Deleted != 1 || summary.Totals.Disabled != 0 || summary.Accounts[0].Found { + t.Fatalf("deleted account state = totals %#v, account %#v", summary.Totals, summary.Accounts[0]) + } +} + +func TestDegradeSummaryDoesNotDropOlderAnomalyAfterTwentyThousandNewerRows(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-large.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + accountID := uint64(7) + records := make([]auditdomain.Record, 0, 20_001) + records = append(records, auditdomain.Record{ + RequestID: "older-real-anomaly", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2_000, + FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-2 * time.Hour), + }) + for index := 0; index < 20_000; index++ { + records = append(records, auditdomain.Record{ + RequestID: fmt.Sprintf("newer-healthy-%05d", index), ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 100, + FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Minute - time.Duration(index)*time.Millisecond), + }) + } + if err := repo.CreateBatch(ctx, records); err != nil { + t.Fatal(err) + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + if summary.Totals.Hits != 1 || summary.Totals.Hard != 1 || len(summary.Events) != 1 || summary.Events[0].RequestID != "older-real-anomaly" { + t.Fatalf("summary silently dropped older anomaly: totals=%#v events=%#v", summary.Totals, summary.Events) + } +} + +func TestDegradeSummaryMatchesFailClosedShortWindowPolicy(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-policy.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(50) + accountID := uint64(9) + if err := repo.Create(ctx, auditdomain.Record{ + RequestID: "short-window", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 200, + FirstTokenMS: &first, DurationMS: 250, CreatedAt: now.Add(-time.Minute), + }); err != nil { + t.Fatal(err) + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + open, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000, FailClosed: false}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + closed, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000, FailClosed: true}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + if open.Totals.Hard != 1 || open.Totals.Burst != 0 || closed.Totals.Hard != 0 || closed.Totals.Burst != 1 { + t.Fatalf("open=%#v closed=%#v", open.Totals, closed.Totals) + } +} + +func TestDegradeSummaryPaginatesAccountsInRepository(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-page.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + for id := uint64(1); id <= 3; id++ { + accountID := id + if err := repo.Create(ctx, auditdomain.Record{ + RequestID: fmt.Sprintf("page-account-%d", id), ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2_000, + FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Duration(id) * time.Minute), + }); err != nil { + t.Fatal(err) + } + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{}, DegradeAccountFilter{Page: 2, PageSize: 2}) + if err != nil { + t.Fatal(err) + } + if summary.AccountPage.Total != 3 || summary.AccountPage.HasMore || len(summary.Accounts) != 1 { + t.Fatalf("page=%#v accounts=%#v", summary.AccountPage, summary.Accounts) + } +} + +func TestDegradeSummarySearchesEveryAccountIdentityField(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-search.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountValue, _, err := relational.NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, AuthType: accountdomain.AuthTypeOAuth, + Name: "Searchable Build Account", SourceKey: "searchable-build", + EncryptedAccessToken: "encrypted-token", AuthStatus: accountdomain.AuthStatusActive, Enabled: true, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + first := int64(100) + if err := relational.NewAuditRepository(database).Create(ctx, auditdomain.Record{ + RequestID: "search-by-name", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountValue.ID, AccountName: "stale audit name", StatusCode: 200, Streaming: true, + OutputTokens: 2_000, FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Minute), + }); err != nil { + t.Fatal(err) + } + service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{}, DegradeAccountFilter{Search: "searchable build"}) + if err != nil { + t.Fatal(err) + } + if summary.AccountPage.Total != 1 || len(summary.Accounts) != 1 || summary.Accounts[0].ID != accountValue.ID { + t.Fatalf("account search result = %#v", summary) + } } func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) { @@ -58,7 +212,7 @@ func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) { t.Fatal(err) } service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second) - if _, err := service.DegradeSummary(ctx, "3h", DegradeThresholds{}); err != ErrInvalidPeriod { + if _, err := service.DegradeSummary(ctx, "3h", DegradeThresholds{}, DegradeAccountFilter{}); err != ErrInvalidPeriod { t.Fatalf("error = %v", err) } } diff --git a/backend/internal/domain/audit/degrade.go b/backend/internal/domain/audit/degrade.go index f1b57113..66af0667 100644 --- a/backend/internal/domain/audit/degrade.go +++ b/backend/internal/domain/audit/degrade.go @@ -14,16 +14,16 @@ const ( ) // ClassifyOutputSpeed matches the quality-guard panel formula: -// output tokens / (durationMs - firstTokenMs). Short generation windows with -// a soft-or-higher rate are buffered_burst; otherwise the hard and soft -// thresholds apply in that order. -func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64) (class string, tps float64, genMS int64) { +// output tokens / (durationMs - firstTokenMs). In fail-closed mode, short +// generation windows with a soft-or-higher rate are buffered_burst; otherwise +// the hard and soft thresholds apply in that order. +func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64, failClosed bool) (class string, tps float64, genMS int64) { genMS = durationMS - firstTokenMS if genMS <= 0 || outputTokens <= 0 { return "", 0, genMS } tps = float64(outputTokens) * 1000 / float64(genMS) - if minGenMS > 0 && genMS < minGenMS && tps >= softTPS { + if failClosed && minGenMS > 0 && genMS < minGenMS && tps >= softTPS { return DegradeClassBurst, tps, genMS } if tps >= hardTPS { diff --git a/backend/internal/domain/audit/degrade_test.go b/backend/internal/domain/audit/degrade_test.go index 24ac8c81..476ce742 100644 --- a/backend/internal/domain/audit/degrade_test.go +++ b/backend/internal/domain/audit/degrade_test.go @@ -8,17 +8,19 @@ func TestClassifyOutputSpeed(t *testing.T) { output, first, duration int64 soft, hard float64 minGen int64 + failClosed bool wantClass string }{ {name: "hard", output: 2000, first: 200, duration: 1200, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard}, {name: "soft", output: 600, first: 200, duration: 1400, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassSoft}, - {name: "burst short window", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassBurst}, + {name: "short window follows hard threshold by default", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard}, + {name: "burst short window when fail closed", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, failClosed: true, wantClass: DegradeClassBurst}, {name: "healthy", output: 100, first: 200, duration: 2200, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, {name: "zero generation", output: 100, first: 500, duration: 500, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen) + class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen, test.failClosed) if class != test.wantClass { t.Fatalf("class = %q, want %q", class, test.wantClass) } diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 6b2e8cde..d0e0d314 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -8,6 +8,7 @@ import ( "fmt" "math" "sort" + "strconv" "strings" "time" "unicode/utf8" @@ -683,66 +684,307 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS return result, nil } -const degradeEventScanLimit = 20_000 - -type degradeEventRow struct { - ID uint64 `gorm:"column:id"` - RequestID string `gorm:"column:request_id"` - AccountID *uint64 `gorm:"column:account_id"` - AccountName string `gorm:"column:account_name"` - Email string `gorm:"column:email"` - Enabled *bool `gorm:"column:enabled"` - BuildBotFlagSource int `gorm:"column:build_bot_flag_source"` - EgressNodeID *uint64 `gorm:"column:egress_node_id"` - EgressNodeName string `gorm:"column:egress_node_name"` - OutputTokens int64 `gorm:"column:output_tokens"` - FirstTokenMS int64 `gorm:"column:first_token_ms"` - DurationMS int64 `gorm:"column:duration_ms"` - CreatedAt time.Time `gorm:"column:created_at"` - Model string `gorm:"column:model_upstream_model"` +type degradeTotalsRow struct { + Hits int64 `gorm:"column:hits"` + Accounts int64 `gorm:"column:accounts"` + StillEnabled int64 `gorm:"column:still_enabled"` + Disabled int64 `gorm:"column:disabled"` + Deleted int64 `gorm:"column:deleted"` + Hard int64 `gorm:"column:hard"` + Soft int64 `gorm:"column:soft"` + Burst int64 `gorm:"column:burst"` + MaxTPS float64 `gorm:"column:max_tps"` } -func (r *AuditRepository) ListDegradeEvents(ctx context.Context, input repository.DegradeEventQuery) ([]repository.DegradeEvent, error) { - limit := input.Limit - if limit <= 0 || limit > degradeEventScanLimit { - limit = degradeEventScanLimit +type degradeAccountRow struct { + ID uint64 `gorm:"column:id"` + Name string `gorm:"column:name"` + Email string `gorm:"column:email"` + Hits int64 `gorm:"column:hits"` + MaxTPS float64 `gorm:"column:max_tps"` + Burst int64 `gorm:"column:burst"` + Soft int64 `gorm:"column:soft"` + Hard int64 `gorm:"column:hard"` + Last degradeTimestamp `gorm:"column:last_seen"` + Enabled bool `gorm:"column:enabled"` + Found bool `gorm:"column:found"` + BuildBotFlagSource int `gorm:"column:build_bot_flag_source"` +} + +type degradeTimestamp time.Time + +func (value *degradeTimestamp) Scan(input any) error { + parsed, err := parseDegradeTimestamp(input) + if err != nil { + return err } - minOut := input.MinOutputTokens - if minOut <= 0 { - minOut = audit.DefaultDegradeMinOutput + *value = degradeTimestamp(parsed) + return nil +} + +func parseDegradeTimestamp(input any) (time.Time, error) { + if parsed, ok := input.(time.Time); ok { + return parsed, nil } - var rows []degradeEventRow - query := r.db.db.WithContext(ctx).Table("request_audits AS a"). - Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.first_token_ms, a.duration_ms, a.created_at, a.model_upstream_model, p.email, p.enabled, COALESCE(c.build_bot_flag_source, 0) AS build_bot_flag_source"). - Joins("LEFT JOIN provider_accounts p ON p.id = a.account_id"). - Joins("LEFT JOIN account_credentials c ON c.account_id = a.account_id"). - Where("a.provider = ?", "grok_build"). - Where("a.streaming = ?", true). - Where(auditSuccessPredicate). - Where("a.output_tokens >= ?", minOut). - Where("a.first_token_ms IS NOT NULL"). - Where("a.duration_ms > a.first_token_ms"). - Where("a.request_id NOT LIKE ?", "quality_%") + var raw string + switch value := input.(type) { + case string: + raw = value + case []byte: + raw = string(value) + case nil: + return time.Time{}, nil + default: + return time.Time{}, fmt.Errorf("unsupported degrade timestamp type %T", input) + } + for _, layout := range []string{ + time.RFC3339Nano, + "2006-01-02 15:04:05.999999999-07:00", + "2006-01-02 15:04:05.999999999Z07:00", + "2006-01-02 15:04:05.999999999", + "2006-01-02 15:04:05-07:00", + "2006-01-02 15:04:05", + } { + parsed, err := time.Parse(layout, raw) + if err == nil { + return parsed, nil + } + } + return time.Time{}, fmt.Errorf("invalid degrade timestamp") +} + +type degradeNodeRow struct { + Name string `gorm:"column:name"` + Hits int64 `gorm:"column:hits"` + Accounts int64 `gorm:"column:accounts"` + MaxTPS float64 `gorm:"column:max_tps"` +} + +type degradeBucketRow struct { + Index int `gorm:"column:bucket_index"` + Count int64 `gorm:"column:count"` + Severe int64 `gorm:"column:severe"` +} + +type degradeAccountNodeRow struct { + AccountID uint64 `gorm:"column:account_id"` + Name string `gorm:"column:name"` +} + +type degradeEventRow struct { + ID uint64 `gorm:"column:id"` + RequestID string `gorm:"column:request_id"` + AccountID *uint64 `gorm:"column:account_id"` + AccountName string `gorm:"column:account_name"` + EgressNodeID *uint64 `gorm:"column:egress_node_id"` + EgressNodeName string `gorm:"column:egress_node_name"` + OutputTokens int64 `gorm:"column:output_tokens"` + TPS float64 `gorm:"column:tps"` + Class string `gorm:"column:degrade_class"` + CreatedAt time.Time `gorm:"column:created_at"` + Model string `gorm:"column:model_upstream_model"` +} + +func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository.DegradeSummaryQuery) (repository.DegradeSummaryResult, error) { + if input.AccountLimit <= 0 || input.AccountLimit > 100 { + input.AccountLimit = 50 + } + if input.AccountOffset < 0 { + input.AccountOffset = 0 + } + if input.RecentLimit <= 0 || input.RecentLimit > 200 { + input.RecentLimit = 80 + } + var result repository.DegradeSummaryResult + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + classified := r.degradeClassifiedQuery(tx, input) + var totals degradeTotalsRow + if err := tx.Table("(?) AS d", classified). + Select(`COUNT(*) AS hits, + COUNT(DISTINCT d.account_id) AS accounts, + COUNT(DISTINCT CASE WHEN p.id IS NOT NULL AND p.enabled = TRUE THEN d.account_id END) AS still_enabled, + COUNT(DISTINCT CASE WHEN p.id IS NOT NULL AND p.enabled = FALSE THEN d.account_id END) AS disabled, + COUNT(DISTINCT CASE WHEN p.id IS NULL THEN d.account_id END) AS deleted, + COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard, + COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft, + COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst, + COALESCE(MAX(d.tps), 0) AS max_tps`). + Joins("LEFT JOIN provider_accounts p ON p.id = d.account_id"). + Scan(&totals).Error; err != nil { + return err + } + result.Totals = repository.DegradeTotals{ + Hits: totals.Hits, Accounts: totals.Accounts, StillEnabled: totals.StillEnabled, + Disabled: totals.Disabled, Deleted: totals.Deleted, Hard: totals.Hard, Soft: totals.Soft, + Burst: totals.Burst, MaxTPS: totals.MaxTPS, + } + + accountQuery := r.degradeAccountAggregate(tx, classified, input) + if err := tx.Table("(?) AS filtered_accounts", accountQuery).Count(&result.AccountTotal).Error; err != nil { + return err + } + accountOffset := input.AccountOffset + if result.AccountTotal > 0 && int64(accountOffset) >= result.AccountTotal { + accountOffset = int((result.AccountTotal-1)/int64(input.AccountLimit)) * input.AccountLimit + } + result.AccountOffset = accountOffset + var accountRows []degradeAccountRow + if err := accountQuery.Order("hits DESC, max_tps DESC, id ASC"). + Offset(accountOffset).Limit(input.AccountLimit).Scan(&accountRows).Error; err != nil { + return err + } + accountIDs := make([]uint64, 0, len(accountRows)) + accountsByID := make(map[uint64]*repository.DegradeAccount, len(accountRows)) + result.Accounts = make([]repository.DegradeAccount, 0, len(accountRows)) + for _, row := range accountRows { + result.Accounts = append(result.Accounts, repository.DegradeAccount{ + ID: row.ID, Name: row.Name, Email: row.Email, Hits: row.Hits, MaxTPS: row.MaxTPS, + Burst: row.Burst, Soft: row.Soft, Hard: row.Hard, Last: time.Time(row.Last), Enabled: row.Enabled, + Found: row.Found, BuildBotFlagSource: row.BuildBotFlagSource, + }) + accountIDs = append(accountIDs, row.ID) + accountsByID[row.ID] = &result.Accounts[len(result.Accounts)-1] + } + if len(accountIDs) > 0 { + var nodeRows []degradeAccountNodeRow + if err := tx.Table("(?) AS d", classified). + Select("d.account_id, COALESCE(NULLIF(d.egress_node_name, ''), '?') AS name"). + Where("d.account_id IN ?", accountIDs). + Group("d.account_id, COALESCE(NULLIF(d.egress_node_name, ''), '?')"). + Order("d.account_id ASC, name ASC").Scan(&nodeRows).Error; err != nil { + return err + } + for _, row := range nodeRows { + if account := accountsByID[row.AccountID]; account != nil { + account.Nodes = append(account.Nodes, row.Name) + } + } + } + + var nodeRows []degradeNodeRow + if err := tx.Table("(?) AS d", classified). + Select("COALESCE(NULLIF(d.egress_node_name, ''), '?') AS name, COUNT(*) AS hits, COUNT(DISTINCT d.account_id) AS accounts, COALESCE(MAX(d.tps), 0) AS max_tps"). + Group("COALESCE(NULLIF(d.egress_node_name, ''), '?')").Order("hits DESC, name ASC").Scan(&nodeRows).Error; err != nil { + return err + } + result.Nodes = make([]repository.DegradeNode, 0, len(nodeRows)) + for _, row := range nodeRows { + result.Nodes = append(result.Nodes, repository.DegradeNode{Name: row.Name, Hits: row.Hits, Accounts: row.Accounts, MaxTPS: row.MaxTPS}) + } + + if len(input.Buckets) > 0 { + caseSQL, caseArgs := degradeBucketCase(input.Buckets) + bucketed := tx.Table("(?) AS d", classified).Select(caseSQL+" AS bucket_index, d.degrade_class", caseArgs...) + var bucketRows []degradeBucketRow + if err := tx.Table("(?) AS b", bucketed). + Select("b.bucket_index, COUNT(*) AS count, COALESCE(SUM(CASE WHEN b.degrade_class IN ('hard_tps', 'buffered_burst') THEN 1 ELSE 0 END), 0) AS severe"). + Where("b.bucket_index >= 0").Group("b.bucket_index").Order("b.bucket_index ASC").Scan(&bucketRows).Error; err != nil { + return err + } + result.Buckets = make([]repository.DegradeBucket, 0, len(bucketRows)) + for _, row := range bucketRows { + result.Buckets = append(result.Buckets, repository.DegradeBucket{Index: row.Index, Count: row.Count, Severe: row.Severe}) + } + } + + var eventRows []degradeEventRow + if err := tx.Table("(?) AS d", classified). + Select("d.id, d.request_id, d.account_id, d.account_name, d.egress_node_id, d.egress_node_name, d.output_tokens, d.tps, d.degrade_class, d.created_at, d.model_upstream_model"). + Order("d.created_at DESC, d.id DESC").Limit(input.RecentLimit).Scan(&eventRows).Error; err != nil { + return err + } + result.Events = make([]repository.DegradeEvent, 0, len(eventRows)) + for _, row := range eventRows { + result.Events = append(result.Events, repository.DegradeEvent{ + ID: row.ID, RequestID: row.RequestID, AccountID: row.AccountID, AccountName: row.AccountName, + EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, OutputTokens: row.OutputTokens, + TPS: row.TPS, Class: row.Class, CreatedAt: row.CreatedAt, Model: row.Model, + }) + } + return nil + }) + return result, err +} + +func (r *AuditRepository) degradeClassifiedQuery(tx *gorm.DB, input repository.DegradeSummaryQuery) *gorm.DB { + castType := "REAL" + if r.db.dialect == "postgres" { + castType = "DOUBLE PRECISION" + } + generationExpression := "(a.duration_ms - a.first_token_ms)" + // NULLIF keeps PostgreSQL safe even if its planner evaluates the throughput + // expression before the duration guard in the WHERE clause. + tpsExpression := fmt.Sprintf("(CAST(a.output_tokens AS %s) * 1000.0 / NULLIF(%s, 0))", castType, generationExpression) + classExpression := fmt.Sprintf("CASE WHEN ? AND %s < ? THEN ? WHEN %s >= ? THEN ? ELSE ? END", generationExpression, tpsExpression) + query := tx.Table("request_audits AS a"). + Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.created_at, a.model_upstream_model, "+tpsExpression+" AS tps, "+classExpression+" AS degrade_class", + input.FailClosed, input.MinGenerationMS, audit.DegradeClassBurst, input.HardTPS, audit.DegradeClassHard, audit.DegradeClassSoft). + Where("a.provider = ?", "grok_build").Where("a.streaming = ?", true). + Where(auditSuccessPredicate).Where("a.output_tokens >= ?", input.MinOutputTokens). + Where("a.first_token_ms IS NOT NULL").Where("a.duration_ms > a.first_token_ms"). + Where("a.request_id NOT LIKE ?", "quality_%").Where(tpsExpression+" >= ?", input.SoftTPS) if !input.Start.IsZero() { query = query.Where("a.created_at >= ?", input.Start) } if !input.End.IsZero() { query = query.Where("a.created_at < ?", input.End) } - if err := query.Order("a.created_at DESC").Limit(limit).Scan(&rows).Error; err != nil { - return nil, err + return query +} + +func (r *AuditRepository) degradeAccountAggregate(tx *gorm.DB, classified *gorm.DB, input repository.DegradeSummaryQuery) *gorm.DB { + query := tx.Table("(?) AS d", classified). + Select(`d.account_id AS id, + COALESCE(NULLIF(p.name, ''), MAX(d.account_name), '') AS name, + COALESCE(p.email, '') AS email, + COUNT(*) AS hits, + COALESCE(MAX(d.tps), 0) AS max_tps, + COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst, + COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft, + COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard, + MAX(d.created_at) AS last_seen, + COALESCE(p.enabled, FALSE) AS enabled, + CASE WHEN p.id IS NULL THEN FALSE ELSE TRUE END AS found, + COALESCE(c.build_bot_flag_source, 0) AS build_bot_flag_source`). + Joins("LEFT JOIN provider_accounts p ON p.id = d.account_id"). + Joins("LEFT JOIN account_credentials c ON c.account_id = d.account_id"). + Where("d.account_id IS NOT NULL"). + Group("d.account_id, p.id, p.name, p.email, p.enabled, c.build_bot_flag_source") + if search := strings.TrimSpace(input.AccountSearch); search != "" { + pattern := "%" + strings.ToLower(search) + "%" + query = query.Where( + "LOWER(COALESCE(p.email, '')) LIKE ? OR LOWER(COALESCE(p.name, '')) LIKE ? OR LOWER(COALESCE(d.account_name, '')) LIKE ? OR CAST(d.account_id AS TEXT) LIKE ?", + pattern, pattern, pattern, pattern, + ) } - out := make([]repository.DegradeEvent, 0, len(rows)) - for _, row := range rows { - out = append(out, repository.DegradeEvent{ - ID: row.ID, RequestID: row.RequestID, AccountID: row.AccountID, AccountName: row.AccountName, - Email: row.Email, Enabled: row.Enabled, BuildBotFlagSource: row.BuildBotFlagSource, - EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, - OutputTokens: row.OutputTokens, FirstTokenMS: row.FirstTokenMS, DurationMS: row.DurationMS, - CreatedAt: row.CreatedAt, Model: row.Model, - }) + switch input.AccountStatus { + case "enabled": + query = query.Where("p.id IS NOT NULL AND p.enabled = TRUE") + case "disabled": + query = query.Where("p.id IS NOT NULL AND p.enabled = FALSE") + case "deleted": + query = query.Where("p.id IS NULL") } - return out, nil + if input.MinHits > 1 { + query = query.Having("COUNT(*) >= ?", input.MinHits) + } + if input.AccountClass != "" { + query = query.Having("SUM(CASE WHEN d.degrade_class = ? THEN 1 ELSE 0 END) > 0", input.AccountClass) + } + return query +} + +func degradeBucketCase(buckets []repository.DegradeBucketRange) (string, []any) { + var builder strings.Builder + args := make([]any, 0, len(buckets)*2) + builder.WriteString("CASE") + for index, bucket := range buckets { + builder.WriteString(" WHEN d.created_at >= ? AND d.created_at < ? THEN ") + builder.WriteString(strconv.Itoa(index)) + args = append(args, bucket.Start, bucket.End) + } + builder.WriteString(" ELSE -1 END") + return builder.String(), args } func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter repository.AuditListFilter) *gorm.DB { diff --git a/backend/internal/infra/persistence/relational/audit_repository_test.go b/backend/internal/infra/persistence/relational/audit_repository_test.go index b53c0f1a..5525b12b 100644 --- a/backend/internal/infra/persistence/relational/audit_repository_test.go +++ b/backend/internal/infra/persistence/relational/audit_repository_test.go @@ -538,4 +538,15 @@ func TestAuditRepositoryStreamFailureKeepsHTTPStatusAndFiltersAsOther(t *testing } } +func TestDegradeTimestampScansPostgresTimeValue(t *testing.T) { + expected := time.Date(2026, time.August, 14, 8, 30, 0, 123, time.UTC) + var value degradeTimestamp + if err := value.Scan(expected); err != nil { + t.Fatal(err) + } + if actual := time.Time(value); !actual.Equal(expected) { + t.Fatalf("scanned timestamp = %s, want %s", actual, expected) + } +} + func uint64Pointer(value uint64) *uint64 { return &value } diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index dab56f5a..c9d79249 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -89,6 +89,7 @@ var schemaIndexes = []string{ "CREATE INDEX IF NOT EXISTS idx_audits_account_created_id ON request_audits(account_id, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audits_status_created_id ON request_audits(status_code, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audits_streaming_created_id ON request_audits(streaming, created_at DESC, id DESC)", + "CREATE INDEX IF NOT EXISTS idx_audits_provider_streaming_created_id ON request_audits(provider, streaming, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audit_attempts_audit_number ON request_audit_attempts(audit_id, number)", "CREATE INDEX IF NOT EXISTS idx_response_ownership_expires_id ON response_ownership(expires_at, response_id)", "CREATE INDEX IF NOT EXISTS idx_response_ownership_account ON response_ownership(account_id)", diff --git a/backend/internal/repository/audit.go b/backend/internal/repository/audit.go index 4be019aa..d421a5d0 100644 --- a/backend/internal/repository/audit.go +++ b/backend/internal/repository/audit.go @@ -16,30 +16,94 @@ type AuditRepository interface { ListCursor(ctx context.Context, query AuditCursorQuery) ([]audit.Record, bool, error) Summarize(ctx context.Context, query AuditSummaryQuery) (audit.Summary, error) SumTokensByAccountsSince(ctx context.Context, accountIDs []uint64, since time.Time) (map[uint64]int64, error) - ListDegradeEvents(ctx context.Context, query DegradeEventQuery) ([]DegradeEvent, error) + SummarizeDegrade(ctx context.Context, query DegradeSummaryQuery) (DegradeSummaryResult, error) } -type DegradeEventQuery struct { +type DegradeSummaryQuery struct { Start time.Time End time.Time + SoftTPS float64 + HardTPS float64 + MinGenerationMS int64 MinOutputTokens int64 - Limit int + FailClosed bool + AccountSearch string + AccountStatus string + AccountClass string + MinHits int + AccountOffset int + AccountLimit int + Buckets []DegradeBucketRange + RecentLimit int } -// DegradeEvent is a slim streaming-success audit plus optional account flags. -type DegradeEvent struct { +type DegradeBucketRange struct { + Start time.Time + End time.Time +} + +type DegradeSummaryResult struct { + Totals DegradeTotals + Accounts []DegradeAccount + AccountTotal int64 + AccountOffset int + Nodes []DegradeNode + Buckets []DegradeBucket + Events []DegradeEvent +} + +type DegradeTotals struct { + Hits int64 + Accounts int64 + StillEnabled int64 + Disabled int64 + Deleted int64 + Hard int64 + Soft int64 + Burst int64 + MaxTPS float64 +} + +type DegradeAccount struct { ID uint64 - RequestID string - AccountID *uint64 - AccountName string + Name string Email string - Enabled *bool + Hits int64 + MaxTPS float64 + Burst int64 + Soft int64 + Hard int64 + Last time.Time + Enabled bool + Found bool BuildBotFlagSource int - EgressNodeID *uint64 - EgressNodeName string - OutputTokens int64 - FirstTokenMS int64 - DurationMS int64 - CreatedAt time.Time - Model string + Nodes []string +} + +type DegradeNode struct { + Name string + Hits int64 + Accounts int64 + MaxTPS float64 +} + +type DegradeBucket struct { + Index int + Count int64 + Severe int64 +} + +// DegradeEvent is a classified streaming-success audit. +type DegradeEvent struct { + ID uint64 + RequestID string + AccountID *uint64 + AccountName string + EgressNodeID *uint64 + EgressNodeName string + OutputTokens int64 + TPS float64 + Class string + CreatedAt time.Time + Model string } diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index ccdb4500..bc3dbf6b 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -337,7 +337,19 @@ func (h *Handler) summary(c *gin.Context) { func (h *Handler) degradeAccounts(c *gin.Context) { softTPS, _ := strconv.ParseFloat(c.Query("softTPS"), 64) hardTPS, _ := strconv.ParseFloat(c.Query("hardTPS"), 64) - result, err := h.service.DegradeSummary(c.Request.Context(), c.DefaultQuery("window", "24h"), auditapp.DegradeThresholds{SoftTPS: softTPS, HardTPS: hardTPS}) + minGenMS, _ := strconv.ParseInt(c.Query("minGenMs"), 10, 64) + failClosed, _ := strconv.ParseBool(c.Query("failClosed")) + minHits, _ := strconv.Atoi(c.Query("minHits")) + page, _ := strconv.Atoi(c.Query("page")) + pageSize, _ := strconv.Atoi(c.Query("pageSize")) + result, err := h.service.DegradeSummary( + c.Request.Context(), c.DefaultQuery("window", "24h"), + auditapp.DegradeThresholds{SoftTPS: softTPS, HardTPS: hardTPS, MinGenMS: minGenMS, FailClosed: failClosed}, + auditapp.DegradeAccountFilter{ + Search: c.Query("search"), Status: c.Query("status"), Class: c.Query("class"), MinHits: minHits, + Page: page, PageSize: pageSize, + }, + ) if errors.Is(err, auditapp.ErrInvalidPeriod) { response.Error(c, http.StatusBadRequest, "invalidAuditPeriod", "window 仅支持 1h、6h、24h、7d") return @@ -351,7 +363,7 @@ func (h *Handler) degradeAccounts(c *gin.Context) { accounts = append(accounts, degradeAccountResponse{ ID: strconv.FormatUint(account.ID, 10), Name: account.Name, Email: account.Email, Hits: account.Hits, MaxTPS: account.MaxTPS, Classes: account.Classes, Nodes: account.Nodes, Last: account.Last, - Enabled: account.Enabled, BFS: account.BFS, + Enabled: account.Enabled, Found: account.Found, BFS: account.BFS, }) } events := make([]degradeEventResponse, 0, len(result.Events)) @@ -372,21 +384,35 @@ func (h *Handler) degradeAccounts(c *gin.Context) { Thresholds: degradeThresholdsResponse{SoftTPS: result.Thresholds.SoftTPS, HardTPS: result.Thresholds.HardTPS, MinGenMS: result.Thresholds.MinGenMS, MinOut: result.Thresholds.MinOut}, Totals: degradeTotalsResponse{ Hits: result.Totals.Hits, Accounts: result.Totals.Accounts, StillEnabled: result.Totals.StillEnabled, - Disabled: result.Totals.Disabled, Hard: result.Totals.Hard, Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS, + Disabled: result.Totals.Disabled, Deleted: result.Totals.Deleted, Hard: result.Totals.Hard, + Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS, }, - Series: result.Series, Nodes: result.Nodes, Accounts: accounts, Events: events, + Series: result.Series, Nodes: result.Nodes, Accounts: accounts, + AccountPage: degradeAccountPageResponse{ + Page: result.AccountPage.Page, PageSize: result.AccountPage.PageSize, + Total: result.AccountPage.Total, HasMore: result.AccountPage.HasMore, + }, + Events: events, }) } type degradeSummaryResponse struct { - Window string `json:"window"` - GeneratedAt time.Time `json:"generatedAt"` - Thresholds degradeThresholdsResponse `json:"thresholds"` - Totals degradeTotalsResponse `json:"totals"` - Series []auditapp.DegradeBucket `json:"series"` - Nodes []auditapp.DegradeNode `json:"nodes"` - Accounts []degradeAccountResponse `json:"accounts"` - Events []degradeEventResponse `json:"events"` + Window string `json:"window"` + GeneratedAt time.Time `json:"generatedAt"` + Thresholds degradeThresholdsResponse `json:"thresholds"` + Totals degradeTotalsResponse `json:"totals"` + Series []auditapp.DegradeBucket `json:"series"` + Nodes []auditapp.DegradeNode `json:"nodes"` + Accounts []degradeAccountResponse `json:"accounts"` + AccountPage degradeAccountPageResponse `json:"accountPage"` + Events []degradeEventResponse `json:"events"` +} + +type degradeAccountPageResponse struct { + Page int `json:"page"` + PageSize int `json:"pageSize"` + Total int64 `json:"total"` + HasMore bool `json:"hasMore"` } type degradeThresholdsResponse struct { @@ -397,27 +423,29 @@ type degradeThresholdsResponse struct { } type degradeTotalsResponse struct { - Hits int `json:"hits"` - Accounts int `json:"accounts"` - StillEnabled int `json:"stillEnabled"` - Disabled int `json:"disabled"` - Hard int `json:"hard"` - Soft int `json:"soft"` - Burst int `json:"burst"` + Hits int64 `json:"hits"` + Accounts int64 `json:"accounts"` + StillEnabled int64 `json:"stillEnabled"` + Disabled int64 `json:"disabled"` + Deleted int64 `json:"deleted"` + Hard int64 `json:"hard"` + Soft int64 `json:"soft"` + Burst int64 `json:"burst"` MaxTPS float64 `json:"maxTPS"` } type degradeAccountResponse struct { - ID string `json:"id"` - Name string `json:"name"` - Email string `json:"email"` - Hits int `json:"hits"` - MaxTPS float64 `json:"maxTPS"` - Classes map[string]int `json:"classes"` - Nodes []string `json:"nodes"` - Last time.Time `json:"last"` - Enabled bool `json:"enabled"` - BFS int `json:"bfs"` + ID string `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + Hits int64 `json:"hits"` + MaxTPS float64 `json:"maxTPS"` + Classes map[string]int64 `json:"classes"` + Nodes []string `json:"nodes"` + Last time.Time `json:"last"` + Enabled bool `json:"enabled"` + Found bool `json:"found"` + BFS int `json:"bfs"` } type degradeEventResponse struct { diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go index 7e139f09..857b8af7 100644 --- a/backend/internal/transport/http/audit/handler_test.go +++ b/backend/internal/transport/http/audit/handler_test.go @@ -189,8 +189,10 @@ func TestDegradeAccountsListsHardHitsAndRejectsUnknownWindow(t *testing.T) { NewHandler(auditapp.NewService(repo, slog.Default(), 8, 4, time.Second)).Register(router.Group("/api/admin/v1")) ok := httptest.NewRecorder() - router.ServeHTTP(ok, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=24h&softTPS=500&hardTPS=1000", nil)) - if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"id":"11"`) || !strings.Contains(ok.Body.String(), `"hard":1`) { + router.ServeHTTP(ok, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=24h&softTPS=500&hardTPS=1000&failClosed=false&page=1&pageSize=20", nil)) + if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"id":"11"`) || !strings.Contains(ok.Body.String(), `"hard":1`) || + !strings.Contains(ok.Body.String(), `"found":false`) || !strings.Contains(ok.Body.String(), `"deleted":1`) || + !strings.Contains(ok.Body.String(), `"accountPage":{"page":1,"pageSize":20,"total":1,"hasMore":false}`) { t.Fatalf("status=%d body=%s", ok.Code, ok.Body.String()) } diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index c5d792eb..9846265c 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -139,6 +139,8 @@ type qualityGuardConfig struct { QuarantineSeconds int `json:"quarantine_seconds"` MinHealthyNodes int `json:"min_healthy_nodes"` MaxOutputTokens int `json:"max_output_tokens"` + FailClosed bool `json:"fail_closed"` + MinGenerationMS int `json:"min_generation_ms"` Prompt string `json:"prompt"` Expected string `json:"expected"` } @@ -194,6 +196,7 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) { "hard_tps": state.Guard.HardTPS, "consecutive_soft": state.Guard.ConsecutiveSoft, "consecutive_errors": state.Guard.ConsecutiveErrors, "quarantine_seconds": state.Guard.QuarantineSeconds, "min_healthy_nodes": state.Guard.MinHealthyNodes, "max_output_tokens": state.Guard.MaxOutputTokens, + "fail_closed": state.Guard.FailClosed, "min_generation_ms": state.Guard.MinGenerationMS, }, "nodes": state.Nodes, "protectedNodeIds": state.ProtectedNodeIDs, "recentEvents": state.RecentEvents, } diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index 5e53991e..36c0b390 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -17,7 +17,7 @@ import ( func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) { path := t.TempDir() + "/state.json" - state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}` + state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"fail_closed":true,"min_generation_ms":1234,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}` if err := os.WriteFile(path, []byte(state), 0o600); err != nil { t.Fatal(err) } @@ -25,7 +25,7 @@ func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) { context, _ := gin.CreateTestContext(recorder) context.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil) NewHandler(nil, path).qualityGuardStatus(context) - if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) { + if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) || !strings.Contains(recorder.Body.String(), `"fail_closed":true`) || !strings.Contains(recorder.Body.String(), `"min_generation_ms":1234`) { t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) } if strings.Contains(recorder.Body.String(), "must-not-leak") || strings.Contains(recorder.Body.String(), "private-probe-prompt") || strings.Contains(recorder.Body.String(), "private-marker") || strings.Contains(recorder.Body.String(), "client_key_id") || !strings.Contains(recorder.Body.String(), `"recentEvents":[]`) { diff --git a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx index 66dd821c..8d269ff8 100644 --- a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx +++ b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { AlertTriangle, Gauge, Power, PowerOff, RefreshCw, Search, Users } from "lucide-react"; +import { AlertTriangle, Gauge, PowerOff, RefreshCw, Search, Users } from "lucide-react"; import { useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; @@ -13,33 +13,40 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@ import { updateAccountsEnabled } from "@/features/accounts/accounts-api"; import { getDegradeAccounts, type DegradeAccountDTO, type DegradeClass, type DegradeSummaryDTO, type DegradeWindow } from "@/features/quality-guard/quality-guard-api"; import { EmptyState, ErrorState } from "@/shared/components/data-state"; +import { Pagination } from "@/shared/components/pagination"; +import { useDebouncedValue } from "@/shared/hooks/use-debounced-value"; import { cn } from "@/shared/lib/cn"; import { formatCompactDateTime } from "@/shared/lib/format"; const MUTE_TOAST_ID = "quality-guard-degrade-mute"; -export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; hardTPS?: number }) { +export function DegradeAccountsPanel({ softTPS, hardTPS, failClosed, minGenMs }: { softTPS?: number; hardTPS?: number; failClosed?: boolean; minGenMs?: number }) { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); const [period, setPeriod] = useState("24h"); const [search, setSearch] = useState(""); - const [status, setStatus] = useState<"all" | "on" | "off">("all"); + const debouncedSearch = useDebouncedValue(search); + const [status, setStatus] = useState<"all" | "enabled" | "disabled" | "deleted">("all"); const [cls, setCls] = useState<"all" | DegradeClass>("all"); const [hitsMin, setHitsMin] = useState(1); + const [page, setPage] = useState(1); + const [pageSize, setPageSize] = useState(50); const [selected, setSelected] = useState>(() => new Set()); const query = useQuery({ - queryKey: ["quality-guard-degrade-accounts", period, softTPS, hardTPS], - queryFn: () => getDegradeAccounts({ window: period, softTPS, hardTPS }), + queryKey: ["quality-guard-degrade-accounts", period, softTPS, hardTPS, failClosed, minGenMs, debouncedSearch, status, cls, hitsMin, page, pageSize], + queryFn: () => getDegradeAccounts({ + window: period, softTPS, hardTPS, failClosed, minGenMs, search: debouncedSearch || undefined, + status: status === "all" ? undefined : status, class: cls === "all" ? undefined : cls, + minHits: hitsMin, page, pageSize, + }), refetchInterval: 15_000, }); const data = query.data; - const rows = useMemo(() => filterAccounts(data, { search, status, cls, hitsMin }), [data, search, status, cls, hitsMin]); - const selectable = rows; + const rows = useMemo(() => data?.accounts ?? [], [data?.accounts]); + const selectable = useMemo(() => rows.filter((account) => account.found && account.enabled), [rows]); const selectedRows = selectable.filter((account) => selected.has(account.id)); - const selectedEnabled = selectedRows.filter((account) => account.enabled); - const selectedMuted = selectedRows.filter((account) => !account.enabled); const allSelected = selectable.length > 0 && selectedRows.length === selectable.length; const muteMutation = useMutation({ @@ -53,18 +60,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h }, onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.muteFailed"), { id: MUTE_TOAST_ID }), }); - const unmuteMutation = useMutation({ - mutationFn: (ids: string[]) => updateAccountsEnabled(ids, true, "grok_build"), - onMutate: () => toast.loading(t("qualityGuard.degrade.unmuting"), { id: MUTE_TOAST_ID }), - onSuccess: (_, ids) => { - setSelected(new Set()); - void queryClient.invalidateQueries({ queryKey: ["quality-guard-degrade-accounts"] }); - void queryClient.invalidateQueries({ queryKey: ["accounts"] }); - toast.success(t("qualityGuard.degrade.unmuted", { count: ids.length }), { id: MUTE_TOAST_ID }); - }, - onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.unmuteFailed"), { id: MUTE_TOAST_ID }), - }); - const busy = muteMutation.isPending || unmuteMutation.isPending; + const busy = muteMutation.isPending; const toggleAll = (checked: boolean) => { setSelected((current) => { @@ -84,7 +80,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h
- + = data.thresholds.hardTPS ? "bad" : undefined} />
@@ -100,30 +96,24 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h

{t("qualityGuard.degrade.accountsTitle")}

{hitsMin > 1 - ? t("qualityGuard.degrade.accountsHintFiltered", { shown: rows.length, total: data.accounts.length, min: hitsMin }) - : t("qualityGuard.degrade.accountsHint", { shown: rows.length, total: data.accounts.length })} + ? t("qualityGuard.degrade.accountsHintFiltered", { shown: rows.length, total: data.accountPage.total, min: hitsMin }) + : t("qualityGuard.degrade.accountsHint", { shown: rows.length, total: data.accountPage.total })}

- setSearch(event.target.value)} placeholder={t("qualityGuard.degrade.search")} /> + { setSearch(event.target.value); setPage(1); setSelected(new Set()); }} placeholder={t("qualityGuard.degrade.search")} />
- { setSelected(new Set()); setPeriod(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> - setStatus(value as "all" | "on" | "off")} items={[["all", t("qualityGuard.degrade.statusAll")], ["on", t("qualityGuard.degrade.statusOn")], ["off", t("qualityGuard.degrade.statusOff")]]} /> - setCls(value as "all" | DegradeClass)} items={[["all", t("qualityGuard.degrade.classAll")], ["buffered_burst", "burst"], ["soft_tps", "soft"], ["hard_tps", "hard"]]} /> - setHitsMin(Number(value))} items={[["1", t("qualityGuard.degrade.hitsAll")], ["2", t("qualityGuard.degrade.hitsMin", { count: 2 })], ["3", t("qualityGuard.degrade.hitsMin", { count: 3 })], ["5", t("qualityGuard.degrade.hitsMin", { count: 5 })], ["10", t("qualityGuard.degrade.hitsMin", { count: 10 })]]} /> - -
+ {data.accountPage.total > 0 ? ( +
+ { setPage(value); setSelected(new Set()); }} + onPageSizeChange={(value) => { setPageSize(value); setPage(1); setSelected(new Set()); }} + /> +
+ ) : null}
@@ -205,19 +215,6 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h ); } -function filterAccounts(data: DegradeSummaryDTO | undefined, filters: { search: string; status: "all" | "on" | "off"; cls: "all" | DegradeClass; hitsMin: number }) { - if (!data) return []; - const search = filters.search.trim().toLowerCase(); - return data.accounts.filter((account) => { - if (account.hits < filters.hitsMin) return false; - if (filters.status === "on" && !account.enabled) return false; - if (filters.status === "off" && account.enabled) return false; - if (filters.cls !== "all" && (account.classes[filters.cls] ?? 0) <= 0) return false; - if (search && !`${account.id} ${account.email} ${account.name}`.toLowerCase().includes(search)) return false; - return true; - }); -} - function classSummary(classes: DegradeAccountDTO["classes"]) { return [ classes.buffered_burst ? `burst ${classes.buffered_burst}` : "", diff --git a/frontend/src/features/quality-guard/quality-guard-api.ts b/frontend/src/features/quality-guard/quality-guard-api.ts index 0ddffa14..f47d5149 100644 --- a/frontend/src/features/quality-guard/quality-guard-api.ts +++ b/frontend/src/features/quality-guard/quality-guard-api.ts @@ -76,6 +76,8 @@ export type QualityGuardStatus = { quarantine_seconds: number; min_healthy_nodes: number; max_output_tokens: number; + fail_closed: boolean; + min_generation_ms: number; }; nodes?: Record; protectedNodeIds?: string[]; @@ -110,6 +112,7 @@ const configValidator = hasShape({ node_ids: isArrayOf(isString), active_interval_seconds: isNumber, passive_poll_seconds: isNumber, soft_tps: isNumber, hard_tps: isNumber, consecutive_soft: isNumber, consecutive_errors: isNumber, quarantine_seconds: isNumber, min_healthy_nodes: isNumber, max_output_tokens: isNumber, + fail_closed: isBoolean, min_generation_ms: isNumber, }); const detectionStatsValidator = hasShape({ total: isNumber, healthy: isNumber, soft: isNumber, hard: isNumber, @@ -165,6 +168,7 @@ export type DegradeAccountDTO = { nodes: string[]; last: string; enabled: boolean; + found: boolean; bfs: number; }; @@ -185,10 +189,11 @@ export type DegradeSummaryDTO = { window: DegradeWindow; generatedAt: string; thresholds: { softTPS: number; hardTPS: number; minGenMs: number; minOutputTokens: number }; - totals: { hits: number; accounts: number; stillEnabled: number; disabled: number; hard: number; soft: number; burst: number; maxTPS: number }; + totals: { hits: number; accounts: number; stillEnabled: number; disabled: number; deleted: number; hard: number; soft: number; burst: number; maxTPS: number }; series: { label: string; count: number; severe: number }[]; nodes: { name: string; hits: number; accounts: number; maxTPS: number }[]; accounts: DegradeAccountDTO[]; + accountPage: { page: number; pageSize: number; total: number; hasMore: boolean }; events: DegradeEventDTO[]; }; @@ -198,13 +203,14 @@ const decodeDegradeSummary = createObjectDecoder("degrade acc window: isOneOf("1h", "6h", "24h", "7d"), generatedAt: isString, thresholds: hasShape({ softTPS: isNumber, hardTPS: isNumber, minGenMs: isNumber, minOutputTokens: isNumber }), - totals: hasShape({ hits: isNumber, accounts: isNumber, stillEnabled: isNumber, disabled: isNumber, hard: isNumber, soft: isNumber, burst: isNumber, maxTPS: isNumber }), + totals: hasShape({ hits: isNumber, accounts: isNumber, stillEnabled: isNumber, disabled: isNumber, deleted: isNumber, hard: isNumber, soft: isNumber, burst: isNumber, maxTPS: isNumber }), series: isArrayOf(hasShape({ label: isString, count: isNumber, severe: isNumber })), nodes: isArrayOf(hasShape({ name: isString, hits: isNumber, accounts: isNumber, maxTPS: isNumber })), accounts: isArrayOf(hasShape({ id: isString, name: isString, email: isString, hits: isNumber, maxTPS: isNumber, - classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, bfs: isNumber, + classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, found: isBoolean, bfs: isNumber, })), + accountPage: hasShape({ page: isNumber, pageSize: isNumber, total: isNumber, hasMore: isBoolean }), events: isArrayOf(hasShape({ id: isString, requestId: isString, accountId: isOptional(isString), accountName: isString, nodeName: isString, outputTokens: isNumber, tps: isNumber, class: degradeClassValidator, @@ -212,9 +218,27 @@ const decodeDegradeSummary = createObjectDecoder("degrade acc })), }); -export function getDegradeAccounts(input: { window: DegradeWindow; softTPS?: number; hardTPS?: number }): Promise { - const query = new URLSearchParams({ window: input.window }); +export function getDegradeAccounts(input: { + window: DegradeWindow; + softTPS?: number; + hardTPS?: number; + failClosed?: boolean; + minGenMs?: number; + search?: string; + status?: "enabled" | "disabled" | "deleted"; + class?: DegradeClass; + minHits?: number; + page: number; + pageSize: number; +}): Promise { + const query = new URLSearchParams({ window: input.window, page: String(input.page), pageSize: String(input.pageSize) }); if (input.softTPS) query.set("softTPS", String(input.softTPS)); if (input.hardTPS) query.set("hardTPS", String(input.hardTPS)); + if (input.failClosed !== undefined) query.set("failClosed", String(input.failClosed)); + if (input.minGenMs) query.set("minGenMs", String(input.minGenMs)); + if (input.search) query.set("search", input.search); + if (input.status) query.set("status", input.status); + if (input.class) query.set("class", input.class); + if (input.minHits && input.minHits > 1) query.set("minHits", String(input.minHits)); return apiRequest(`/api/admin/v1/request-audits/degrade-accounts?${query}`, {}, decodeDegradeSummary); } diff --git a/frontend/src/features/quality-guard/quality-guard-page.tsx b/frontend/src/features/quality-guard/quality-guard-page.tsx index ce682c16..34c4d1ba 100644 --- a/frontend/src/features/quality-guard/quality-guard-page.tsx +++ b/frontend/src/features/quality-guard/quality-guard-page.tsx @@ -167,7 +167,12 @@ export function QualityGuardPage() { {t("qualityGuard.degrade.tab")} - + {!status?.available ? : ( diff --git a/frontend/src/shared/components/pagination.tsx b/frontend/src/shared/components/pagination.tsx index 63c08bb9..de4c24d8 100644 --- a/frontend/src/shared/components/pagination.tsx +++ b/frontend/src/shared/components/pagination.tsx @@ -7,7 +7,7 @@ import { cn } from "@/shared/lib/cn"; const PAGE_SIZE_OPTIONS = [20, 100, 500, 1000, 2000] as const; -export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChange, className }: { page: number; pageSize: number; total: number; onPageChange: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; className?: string }) { +export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChange, pageSizeOptions = PAGE_SIZE_OPTIONS, className }: { page: number; pageSize: number; total: number; onPageChange: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; pageSizeOptions?: readonly number[]; className?: string }) { const { t } = useTranslation(); const pages = Math.max(1, Math.ceil(total / pageSize)); @@ -20,7 +20,7 @@ export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChan - {onPageSizeChange ? : } + {onPageSizeChange ? : } ); } @@ -36,12 +36,12 @@ export function CursorPagination({ page, pageSize, hasMore, disabled = false, on {t("audits.cursorPage", { page })} - + ); } -function PageSizeSelector({ pageSize, disabled = false, onChange }: { pageSize: number; disabled?: boolean; onChange: (pageSize: number) => void }) { +function PageSizeSelector({ pageSize, disabled = false, options, onChange }: { pageSize: number; disabled?: boolean; options: readonly number[]; onChange: (pageSize: number) => void }) { const { t } = useTranslation(); return (
@@ -49,7 +49,7 @@ function PageSizeSelector({ pageSize, disabled = false, onChange }: { pageSize: {t("common.rows")} diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 169df231..e3693e69 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -447,15 +447,15 @@ const resources = { degrade: { tab: "降智账号", overview: "降智账号概览", series: "降智时序", nodes: "按出口节点", hits: "降智次数", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", - accounts: "涉及账号", accountsHelp: "窗口内去重", stillEnabled: "仍在调度", stillEnabledHelp: "漏网,可批量禁", + accounts: "涉及账号", accountsHelp: "窗口内去重 · 已删除 {{deleted}}", stillEnabled: "仍在调度", stillEnabledHelp: "漏网,可批量禁", maxTPS: "峰值 TPS", maxTPSHelp: "单次请求最高", accountsTitle: "降智账号", accountsHint: "显示 {{shown}} / {{total}}", accountsHintFiltered: "显示 {{shown}} / {{total}} · 命中≥{{min}}", - search: "搜邮箱 / ID", statusAll: "全部状态", statusOn: "仍在调度", statusOff: "已禁言", + search: "搜名称 / 邮箱 / ID", statusAll: "全部状态", statusOn: "仍在调度", statusOff: "已禁用", statusDeleted: "账号已删除", classAll: "全部类型", class: "类型", account: "账号", status: "状态", hitCount: "命中", hitsAll: "全部次数", hitsMin: "命中 ≥ {{count}}", windows: { "1h": "近 1 小时", "6h": "近 6 小时", "24h": "近 24 小时", "7d": "近 7 天" }, - muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", unmuteSelected: "解除禁用", unmuteSelectedCount: "解除禁用 ({{count}})", unmuteConfirm: "确认恢复 {{count}} 个已禁账号到调度?", unmuting: "正在恢复账号", unmuted: "已恢复 {{count}} 个账号", unmuteFailed: "恢复失败", - scheduling: "调度", mutedStatus: "已禁", + muteSelected: "禁用所选", muteSelectedCount: "禁用所选 ({{count}})", muteConfirm: "确认禁用 {{count}} 个仍在调度的降智账号?", muting: "正在禁用账号", muted: "已禁用 {{count}} 个账号", muteFailed: "禁用失败", + scheduling: "调度中", disabledStatus: "已禁用", deletedStatus: "已删除", events: "最近事件", eventsHelp: "用户请求,不含 quality-test 探针", noHits: "这个窗口没有降智请求", noNodes: "无节点数据", noAccounts: "没有匹配账号", noEvents: "无事件", }, @@ -1356,15 +1356,15 @@ const resources = { degrade: { tab: "Degraded accounts", overview: "Degraded account overview", series: "Degrade timeline", nodes: "By egress node", hits: "Degrade hits", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", - accounts: "Accounts", accountsHelp: "Unique in this window", stillEnabled: "Still scheduled", stillEnabledHelp: "Still enabled; can be muted in bulk", + accounts: "Accounts", accountsHelp: "Unique in this window · {{deleted}} deleted", stillEnabled: "Still scheduled", stillEnabledHelp: "Still enabled; can be disabled in bulk", maxTPS: "Peak TPS", maxTPSHelp: "Highest single request", accountsTitle: "Degraded accounts", accountsHint: "Showing {{shown}} / {{total}}", accountsHintFiltered: "Showing {{shown}} / {{total}} · hits ≥ {{min}}", - search: "Search email / ID", statusAll: "All statuses", statusOn: "Still scheduled", statusOff: "Muted", + search: "Search name / email / ID", statusAll: "All statuses", statusOn: "Still scheduled", statusOff: "Disabled", statusDeleted: "Deleted accounts", classAll: "All classes", class: "Class", account: "Account", status: "Status", hitCount: "Hits", hitsAll: "Any hit count", hitsMin: "Hits ≥ {{count}}", windows: { "1h": "Last 1 hour", "6h": "Last 6 hours", "24h": "Last 24 hours", "7d": "Last 7 days" }, - muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", unmuteSelected: "Unmute selected", unmuteSelectedCount: "Unmute selected ({{count}})", unmuteConfirm: "Restore {{count}} muted accounts to scheduling?", unmuting: "Restoring accounts", unmuted: "Restored {{count}} accounts", unmuteFailed: "Failed to restore accounts", - scheduling: "Scheduled", mutedStatus: "Muted", + muteSelected: "Disable selected", muteSelectedCount: "Disable selected ({{count}})", muteConfirm: "Disable {{count}} still-scheduled degraded accounts?", muting: "Disabling accounts", muted: "Disabled {{count}} accounts", muteFailed: "Failed to disable accounts", + scheduling: "Scheduled", disabledStatus: "Disabled", deletedStatus: "Deleted", events: "Recent events", eventsHelp: "User requests; quality-test probes are excluded", noHits: "No degrade requests in this window", noNodes: "No node data", noAccounts: "No matching accounts", noEvents: "No events", }, From 16e12bdc283a493a8eddce1271b1ede9a2ad1d58 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:06:03 +0800 Subject: [PATCH 16/17] fix: use Responses stream state machine for image compatibility --- backend/internal/infra/provider/web/image.go | 40 ++++++++++++----- .../infra/provider/web/protocol_test.go | 44 +++++++++++++++++++ 2 files changed, 72 insertions(+), 12 deletions(-) diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index fb759985..cb2b1438 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -24,6 +24,7 @@ import ( mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) const ( @@ -513,16 +514,14 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid } parsed.appendText(liteImageMarkdown(item)) } - payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) if input.Stream || request.Streaming { - var stream bytes.Buffer - writeStreamStart(&stream, request.Operation, responseID, input.Model, parsed.InputTokens) - if err := writeStreamDelta(&stream, request.Operation, responseID, input.Model, "text", parsed.Text.String()); err != nil { + stream, err := buildImageCompatibilityStream(request.Operation, responseID, input.Model, &parsed) + if err != nil { return nil, err } - writeStreamDone(&stream, request.Operation, responseID, input.Model, parsed, payload) - return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: count}, nil + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream)), QuotaUnits: count}, nil } + payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) data, err := json.Marshal(payload) if err != nil { return nil, err @@ -568,16 +567,14 @@ func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request if parsed.Text.Len() == 0 { return nil, fmt.Errorf("图片生成兼容响应中没有图片") } - result := buildOpenAIResult(request.Operation, parsed.ResponseID, input.Model, parsed, false) if input.Stream || request.Streaming { - var stream bytes.Buffer - writeStreamStart(&stream, request.Operation, parsed.ResponseID, input.Model, parsed.InputTokens) - if err := writeStreamDelta(&stream, request.Operation, parsed.ResponseID, input.Model, "text", parsed.Text.String()); err != nil { + stream, err := buildImageCompatibilityStream(request.Operation, parsed.ResponseID, input.Model, &parsed) + if err != nil { return nil, err } - writeStreamDone(&stream, request.Operation, parsed.ResponseID, input.Model, parsed, result) - return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: generated.QuotaUnits}, nil + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream)), QuotaUnits: generated.QuotaUnits}, nil } + result := buildOpenAIResult(request.Operation, parsed.ResponseID, input.Model, parsed, false) data, err := json.Marshal(result) if err != nil { return nil, err @@ -585,6 +582,25 @@ func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: generated.QuotaUnits}, nil } +func buildImageCompatibilityStream(operation, responseID, model string, parsed *parsedChat) ([]byte, error) { + var stream bytes.Buffer + writeStreamStart(&stream, operation, responseID, model, parsed.InputTokens) + if operation == conversation.OperationResponses { + responsesStream := newWebResponsesStream(&stream, responseID) + if err := responsesStream.Delta("text", parsed.Text.String()); err != nil { + return nil, err + } + if err := responsesStream.Finish(parsed); err != nil { + return nil, err + } + } else if err := writeStreamDelta(&stream, operation, responseID, model, "text", parsed.Text.String()); err != nil { + return nil, err + } + payload := buildOpenAIResult(operation, responseID, model, *parsed, false) + writeStreamDone(&stream, operation, responseID, model, *parsed, payload) + return stream.Bytes(), nil +} + func liteImageMarkdown(item map[string]any) string { if value, _ := item["url"].(string); value != "" { return "![image](" + value + ")" diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 3c848f22..ef00e67f 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -215,6 +215,50 @@ func TestQualityImageResponsesUsesImageCompatibilityValidation(t *testing.T) { } } +func TestImageCompatibilityResponsesStreamUsesOutputStateMachine(t *testing.T) { + parsed := parsedChat{ResponseID: "resp_image", InputTokens: 3} + parsed.appendText("![image](https://example.com/generated.png)") + body, err := buildImageCompatibilityStream( + conversation.OperationResponses, + parsed.ResponseID, + "grok-imagine-image-lite", + &parsed, + ) + if err != nil { + t.Fatal(err) + } + stream := string(body) + for _, event := range []string{ + "response.created", + "response.output_item.added", + "response.content_part.added", + "response.output_text.delta", + "response.output_text.done", + "response.content_part.done", + "response.output_item.done", + "response.completed", + } { + if !strings.Contains(stream, "event: "+event+"\n") { + t.Fatalf("stream missing %s: %s", event, stream) + } + } + if strings.Contains(stream, "chat.completion.chunk") || strings.Contains(stream, "data: [DONE]") { + t.Fatalf("Responses stream contains Chat Completions envelope: %s", stream) + } + if len(parsed.ResponseOutput) != 1 { + t.Fatalf("response output = %#v", parsed.ResponseOutput) + } + item := parsed.ResponseOutput[0].(map[string]any) + if item["type"] != "message" || item["status"] != "completed" { + t.Fatalf("response output item = %#v", item) + } + itemID, _ := item["id"].(string) + completedAt := strings.Index(stream, "event: response.completed\n") + if itemID == "" || completedAt < 0 || !strings.Contains(stream[completedAt:], `"id":"`+itemID+`"`) { + t.Fatalf("completed response does not reuse output item %q: %s", itemID, stream) + } +} + func TestNormalizeResponsesInputImage(t *testing.T) { dataURI := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" input, _ := json.Marshal([]any{map[string]any{ From 852e44443e85b9331e1de59ba10e2c20bd3913f0 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:15:35 +0800 Subject: [PATCH 17/17] fix: update resolution field descriptions for images and videos --- frontend/src/features/docs/api-docs-page.tsx | 4 ++-- frontend/src/shared/i18n/index.ts | 22 +++++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/frontend/src/features/docs/api-docs-page.tsx b/frontend/src/features/docs/api-docs-page.tsx index c3677ca6..49caa853 100644 --- a/frontend/src/features/docs/api-docs-page.tsx +++ b/frontend/src/features/docs/api-docs-page.tsx @@ -96,7 +96,7 @@ const endpoints: Record = { { name: "prompt", required: true, descriptionKey: "docs.reference.fieldPrompt" }, { name: "n", descriptionKey: "docs.reference.fieldImageCount" }, { name: "aspect_ratio", descriptionKey: "docs.reference.fieldAspectRatio" }, - { name: "resolution", descriptionKey: "docs.reference.fieldResolution" }, + { name: "resolution", descriptionKey: "docs.reference.fieldImageResolution" }, { name: "quality", descriptionKey: "docs.reference.fieldQuality" }, { name: "response_format", descriptionKey: "docs.reference.fieldResponseFormat" }, { name: "stream", descriptionKey: "docs.reference.fieldImageStream" }, @@ -128,7 +128,7 @@ const endpoints: Record = { { name: "prompt", descriptionKey: "docs.reference.fieldVideoPrompt" }, { name: "duration", descriptionKey: "docs.reference.fieldDuration" }, { name: "aspect_ratio", descriptionKey: "docs.reference.fieldAspectRatio" }, - { name: "resolution", descriptionKey: "docs.reference.fieldResolution" }, + { name: "resolution", descriptionKey: "docs.reference.fieldVideoResolution" }, { name: "image", descriptionKey: "docs.reference.fieldVideoImage" }, { name: "reference_images", descriptionKey: "docs.reference.fieldReferenceImages" }, { name: "reference_audios", descriptionKey: "docs.reference.fieldReferenceAudios" }, diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 08ae7f32..965fb1dc 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1100,20 +1100,21 @@ const resources = { fieldPrompt: "用于生成或编辑图片的自然语言描述。", fieldImageCount: "需要返回的图片数量;网关会选择可满足数量的最小上游批次。", fieldAspectRatio: "输出媒体的宽高比,例如 1:1、2:3 或 16:9。", - fieldResolution: "输出分辨率;图片支持 1k/2k。视频 grok-imagine-video 支持 480p/720p,grok-imagine-video-1.5 额外支持 1080p,但 1080p 不能用于参考图生视频。", + fieldImageResolution: "图片输出分辨率,支持 1k/2k。", + fieldVideoResolution: "视频输出分辨率,支持 480p/720p;仅上游模型 grok-imagine-video-1.5 在非参考图模式下支持 1080p。", fieldQuality: "Image 2.0 的生成质量,可选 low 或 medium;默认 medium。", fieldResponseFormat: "图片返回格式,支持 url 或 b64_json。", fieldImageStream: "是否使用图片生成扩展 SSE 流;默认 false。", fieldEditImages: "待编辑图片,使用 image 或 images 传入 URL、Data URL 或已支持的图片引用。", fieldVideoPrompt: "视频描述;使用图片输入时可作为运动或镜头指令。", - fieldDuration: "视频时长(秒)。文生视频与首帧图生视频最长 15 秒;参考图生视频 grok-imagine-video 最长 10 秒、grok-imagine-video-1.5 最长 15 秒。", + fieldDuration: "视频时长(秒),范围 1–15。Console 路由中,grok-imagine-video 的参考图模式最长 10 秒;grok-imagine-video-1.5 最长 15 秒。", fieldVideoImage: "可选首帧图片引用,用于图生视频;最多 1 张,不可与 reference_images 同时使用。", fieldVideoEditPrompt: "描述希望如何修改原视频。", fieldVideoExtendPrompt: "描述视频接下来应发生的内容。", fieldVideoInput: "输入视频,支持 url 或本地上传后的 file_id。", fieldVideoExtendDuration: "延长片段时长,单位秒,范围 2 到 10,默认 6。", - fieldReferenceImages: "可选参考图片数组,用于参考图视频;最多 7 张,每项提供 url 或 file_id,不可与 image 同时使用。", - fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。需上游团队开启该能力,未开启时上游返回 403。", + fieldReferenceImages: "可选参考图片数组,用于参考图视频;网关最多接收 8 张,Console 路由最多 7 张。每项提供 url 或 file_id,不可与 image 同时使用。", + fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。该能力可能受上游团队权限控制;Console 未开通时上游返回 403。", fieldRequestId: "创建视频任务时返回的 request_id。", noteChatProviders: "Build、Web 与 Console 使用独立账号池和上游协议,但向客户端返回统一的 Chat Completions 结构。", noteChatImages: "对话图片会先完成校验与上传,再绑定到本次选择的账号;不会在流开始后切换账号。", @@ -1131,7 +1132,7 @@ const resources = { noteEditSources: "远程图片会经过 SSRF、防体积超限和内容类型校验后再上传到上游。", noteVideoAsync: "创建接口只返回 request_id;生成过程异步执行并持久化任务状态。", noteVideoDuration: "时长、比例、分辨率和图片输入按当前视频模型能力校验。", - noteVideoReference: "参考图视频走 /videos/generations + reference_images,最多 7 张;只传 1 张也保持参考图语义,不会被当成首帧。不可与 image 同用。参考图模式 resolution 最高 720p,grok-imagine-video-1.5 也不例外。reference_audios 使用内置 voice_id,需团队开启该能力。", + noteVideoReference: "参考图视频走 /videos/generations + reference_images;只传 1 张也保持参考图语义,不会被当成首帧。网关最多接收 8 张,Console 路由最多 7 张;不可与 image 同用。参考图模式最高 720p。Console 的 grok-imagine-video 参考图模式最长 10 秒,reference_audios 还需相应团队权限。", noteVideoStrict: "视频接口严格使用当前官方字段,不保留旧项目的兼容别名。", noteVideoEditModel: "视频编辑与延长的实际路由必须指向 Console/grok-imagine-video;对外模型名可以自定义。", noteVideoBilling: "视频编辑与延长暂未返回可可靠结算的输入视频时长,因此保持可调用,并在请求审计中标记为未计费;不会消耗 API Key 的金额额度。", @@ -1730,20 +1731,21 @@ const resources = { fieldPrompt: "Natural-language instructions for image generation or editing.", fieldImageCount: "Number of images to return. The gateway selects the smallest upstream batch that can satisfy it.", fieldAspectRatio: "Output aspect ratio such as 1:1, 2:3, or 16:9.", - fieldResolution: "Output resolution. Images support 1k/2k. For video, grok-imagine-video supports 480p/720p and grok-imagine-video-1.5 also supports 1080p, but 1080p cannot be used for reference-to-video.", + fieldImageResolution: "Image output resolution. Supported values are 1k and 2k.", + fieldVideoResolution: "Video output resolution. Supported values are 480p and 720p; only the upstream grok-imagine-video-1.5 model supports 1080p, and only without reference images.", fieldQuality: "Generation quality for Image 2.0: low or medium. Defaults to medium.", fieldResponseFormat: "Image response format: url or b64_json.", fieldImageStream: "Enable the image-generation SSE extension. Defaults to false.", fieldEditImages: "Source image or images supplied as URLs, data URLs, or another supported image reference.", fieldVideoPrompt: "Video description, or motion and camera instructions when an image is supplied.", - fieldDuration: "Video duration in seconds. Text-to-video and first-frame image-to-video allow up to 15s. For reference-to-video, grok-imagine-video allows up to 10s and grok-imagine-video-1.5 up to 15s.", + fieldDuration: "Video duration in seconds, from 1 to 15. On Console routes, reference-to-video is limited to 10s with grok-imagine-video and 15s with grok-imagine-video-1.5.", fieldVideoImage: "Optional first-frame image reference for image-to-video generation. At most one image, and it cannot be combined with reference_images.", fieldVideoEditPrompt: "Describe how the source video should change.", fieldVideoExtendPrompt: "Describe what should happen next in the video.", fieldVideoInput: "Source video input. Provide either url or an uploaded file_id.", fieldVideoExtendDuration: "Extension length in seconds. Allowed range is 2 to 10; defaults to 6.", - fieldReferenceImages: "Optional reference image array for reference-to-video, up to 7 items. Each item uses url or file_id and cannot be combined with image.", - fieldReferenceAudios: "Optional reference audio array of up to 3 built-in voice_id values. Can be used alone or with reference_images. The upstream team must have the capability enabled; otherwise upstream returns 403.", + fieldReferenceImages: "Optional reference image array for reference-to-video. The gateway accepts up to 8 items, while Console routes accept up to 7. Each item uses url or file_id and cannot be combined with image.", + fieldReferenceAudios: "Optional reference audio array of up to 3 built-in voice_id values. It can be used alone or with reference_images and may require upstream team entitlement; Console returns an upstream 403 when the capability is not enabled.", fieldRequestId: "The request_id returned when the video job is created.", noteChatProviders: "Build, Web, and Console use separate account pools and upstream protocols while returning the same Chat Completions shape.", noteChatImages: "Conversation images are validated and uploaded before being bound to the selected account. Accounts never switch after streaming begins.", @@ -1761,7 +1763,7 @@ const resources = { noteEditSources: "Remote images pass SSRF, size, and content-type checks before upload to the upstream service.", noteVideoAsync: "Creation returns only request_id. Generation runs asynchronously with persistent job state.", noteVideoDuration: "Duration, aspect ratio, resolution, and image inputs are validated against the selected video model.", - noteVideoReference: "Reference-to-video uses /videos/generations with reference_images, up to 7 items. A single item still keeps reference semantics and is not promoted to a first frame. Do not combine with image. Resolution tops out at 720p in reference mode, including grok-imagine-video-1.5. reference_audios accepts built-in voice_id values and requires team entitlement.", + noteVideoReference: "Reference-to-video uses /videos/generations with reference_images. A single item keeps reference semantics and is not promoted to a first frame. The gateway accepts up to 8 items and Console routes up to 7; do not combine them with image. Reference mode tops out at 720p. On Console, grok-imagine-video reference mode is limited to 10s and reference_audios also requires the corresponding team entitlement.", noteVideoStrict: "Video endpoints use the current official fields without non-standard aliases.", noteVideoEditModel: "The resolved route for video edits and extensions must target Console/grok-imagine-video; the public model name may be customized.", noteVideoBilling: "Video edits and extensions do not yet expose a reliably billable input-video duration. They remain callable, are audited as unpriced, and do not consume the API key spend limit.",