diff --git a/backend/internal/application/audit/service.go b/backend/internal/application/audit/service.go index 4dc557d8..fb1b3d26 100644 --- a/backend/internal/application/audit/service.go +++ b/backend/internal/application/audit/service.go @@ -431,7 +431,7 @@ func (s *Service) ListCursor(ctx context.Context, rawCursor string, pageSize int if filter.Sort.Field == "" && filter.Sort.Direction == "" { filter.Sort = repository.SortQuery{Field: "createdAt", Direction: repository.SortDescending} } - if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") || !repository.IsValidSort(filter.Sort, "request", "model", "billing", "tokens", "status", "mode", "duration", "createdAt") { + if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx", "other") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") || !repository.IsValidSort(filter.Sort, "request", "model", "billing", "tokens", "status", "mode", "duration", "createdAt") { return CursorResult{}, ErrInvalidFilter } cursor, err := decodeAuditCursor(rawCursor, filter.Sort) @@ -563,7 +563,7 @@ func (s *Service) SummaryFresh(ctx context.Context, search, rawPeriod string, fi } func (s *Service) summary(ctx context.Context, search, rawPeriod string, filter ListFilter, useCache bool) (SummaryResult, error) { - if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") { + if !validAuditFilter(filter.Status, "", "success", "clientError", "serverError", "2xx", "4xx", "5xx", "other") || !validAuditFilter(filter.Mode, "", "stream", "nonStream") { return SummaryResult{}, ErrInvalidFilter } period, start, end, err := s.resolvePeriod(rawPeriod) diff --git a/backend/internal/application/gateway/image.go b/backend/internal/application/gateway/image.go index 1fe2b92b..9da4fad3 100644 --- a/backend/internal/application/gateway/image.go +++ b/backend/internal/application/gateway/image.go @@ -269,7 +269,7 @@ func (s *Service) executeImage( var once sync.Once finalize := func(_ Usage, _ string, errorCode string) { once.Do(func() { - successful := response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" + successful := auditRequestSucceeded(response.StatusCode, errorCode) lease.completeSelectorObservation(successful) lease.Release() budget := newFinalizationBudget(string(operation), string(route.Provider)) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 3cb79f31..617f614f 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -1252,7 +1252,9 @@ attemptLoop: var once sync.Once finalize := func(usage Usage, responseID, errorCode string) { once.Do(func() { - successful := response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" + // HTTP 状态码保留线上真实值;流在 2xx 响应头之后失败时由 errorCode + // 决定最终结果,避免把协议状态与业务结果混为一谈。 + successful := auditRequestSucceeded(response.StatusCode, errorCode) lease.completeSelectorObservation(successful) budget := newFinalizationBudget(string(operation), string(route.Provider)) if isUpstreamStreamFailure(errorCode) { @@ -1279,7 +1281,7 @@ attemptLoop: record.MediaOutputImages = int64(max(0, response.QuotaUnits)) } tokenPricing, tokenPriced := audit.EstimateOfficialCost(pricingModel, usage.InputTokens, usage.CachedInputTokens, usage.OutputTokens, usage.ContextInputTokens) - if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" && imagePriced { + if successful && imagePriced { record.EstimatedCostInUSDTicks = imagePricing.CostInUSDTicks record.PricingModel = imagePricing.Model record.PricingVersion = audit.OfficialPricingAsOf @@ -1298,7 +1300,7 @@ attemptLoop: record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = errorCode attempts := failureAttempts.snapshot() - if response.StatusCode < 200 || response.StatusCode >= 300 || errorCode != "" || len(attempts) > 0 { + if !successful || len(attempts) > 0 { record.Attempts = attempts } record.CreatedAt = now @@ -1412,6 +1414,13 @@ func isUpstreamStreamFailure(errorCode string) bool { } } +// auditRequestSucceeded keeps transport truth (the HTTP status) separate from +// the terminal request outcome. A stream that fails after 2xx headers is not a +// successful request even though its HTTP status remains 2xx. +func auditRequestSucceeded(statusCode int, errorCode string) bool { + return statusCode >= 200 && statusCode < 300 && errorCode == "" +} + func isRetryableTransportFailure(providerValue accountdomain.Provider, err error) bool { return providerValue != accountdomain.ProviderBuild || !neterrorpkg.IsResponseHeaderTimeout(err) } diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 5262a77a..e1b29c9d 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -3897,3 +3897,26 @@ func testCipher(t *testing.T) *security.Cipher { } return cipher } + +func TestAuditRequestSucceeded(t *testing.T) { + cases := []struct { + name string + statusCode int + errorCode string + want bool + }{ + {name: "2xx without error succeeds", statusCode: 200, errorCode: "", want: true}, + {name: "2xx stream interruption fails", statusCode: 200, errorCode: "upstream_stream_interrupted", want: false}, + {name: "2xx stream incomplete fails", statusCode: 200, errorCode: "upstream_stream_incomplete", want: false}, + {name: "any 2xx error fails", statusCode: 201, errorCode: "stream_interrupted", want: false}, + {name: "4xx fails", statusCode: 404, errorCode: "upstream_error", want: false}, + {name: "5xx fails", statusCode: 502, errorCode: "upstream_server_error", want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := auditRequestSucceeded(tc.statusCode, tc.errorCode); got != tc.want { + t.Fatalf("auditRequestSucceeded(%d, %q) = %t, want %t", tc.statusCode, tc.errorCode, got, tc.want) + } + }) + } +} diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index e5332131..5226fbb1 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "strconv" "strings" "time" @@ -63,8 +64,14 @@ func (r *AccountRepository) List(ctx context.Context, input repository.AccountLi query = query.Where("provider = ?", input.Filter.Provider) } if search := strings.TrimSpace(input.Page.Search); search != "" { - pattern := "%" + strings.ToLower(search) + "%" - query = query.Where("LOWER(name) LIKE ? OR LOWER(email) LIKE ? OR LOWER(user_id) LIKE ? OR LOWER(team_id) LIKE ?", pattern, pattern, pattern, pattern) + if id, err := strconv.ParseUint(strings.TrimPrefix(search, "#"), 10, 64); strings.HasPrefix(search, "#") && err == nil && id > 0 { + // #ID 是管理端名单使用的内部精确查询形式,走主键索引且不改变 + // 原有纯数字名称的模糊搜索语义。 + query = query.Where("provider_accounts.id = ?", id) + } else { + pattern := "%" + strings.ToLower(search) + "%" + query = query.Where("LOWER(name) LIKE ? OR LOWER(email) LIKE ? OR LOWER(user_id) LIKE ? OR LOWER(team_id) LIKE ?", pattern, pattern, pattern, pattern) + } } switch input.Filter.QuotaType { case "free": diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 9bd9ed9e..820824e3 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -26,6 +26,8 @@ const ( auditInsertBatchSize = 20 auditLookupBatchSize = 500 attemptInsertBatchSize = 40 + auditSuccessPredicate = "status_code >= 200 AND status_code < 300 AND (error_code IS NULL OR error_code = '')" + auditSuccessAggregate = "COALESCE(SUM(CASE WHEN " + auditSuccessPredicate + " THEN 1 ELSE 0 END), 0)" ) var errAuditBatchRequiresFallback = errors.New("audit batch requires idempotent fallback") @@ -642,7 +644,6 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS var aggregate struct { Requests int64 SuccessfulRequests int64 - FailedRequests int64 InputTokens int64 CachedInputTokens int64 OutputTokens int64 @@ -658,8 +659,7 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS query := applyAuditQuery(r.db.db.WithContext(ctx).Model(&requestAuditModel{}), input.Search, input.Start, input.End, input.Filter) if err := query.Select(` COUNT(*) AS requests, - COALESCE(SUM(CASE WHEN status_code >= 200 AND status_code < 300 THEN 1 ELSE 0 END), 0) AS successful_requests, - COALESCE(SUM(CASE WHEN status_code < 200 OR status_code >= 300 THEN 1 ELSE 0 END), 0) AS failed_requests, + ` + auditSuccessAggregate + ` AS successful_requests, COALESCE(SUM(input_tokens), 0) AS input_tokens, COALESCE(SUM(cached_input_tokens), 0) AS cached_input_tokens, COALESCE(SUM(output_tokens), 0) AS output_tokens, @@ -674,7 +674,7 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS return audit.Summary{}, err } result := audit.Summary{ - Requests: aggregate.Requests, SuccessfulRequests: aggregate.SuccessfulRequests, FailedRequests: aggregate.FailedRequests, + Requests: aggregate.Requests, SuccessfulRequests: aggregate.SuccessfulRequests, FailedRequests: aggregate.Requests - aggregate.SuccessfulRequests, InputTokens: aggregate.InputTokens, CachedInputTokens: aggregate.CachedInputTokens, OutputTokens: aggregate.OutputTokens, ReasoningTokens: aggregate.ReasoningTokens, TotalTokens: aggregate.TotalTokens, DurationMS: aggregate.DurationMS, EstimatedCostInUSDTicks: aggregate.EstimatedCostInUSDTicks, PricedRequests: aggregate.PricedRequests, @@ -707,11 +707,16 @@ func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter } switch filter.Status { case "success", "2xx": - query = query.Where("status_code >= 200 AND status_code < 300") + query = query.Where(auditSuccessPredicate) case "clientError", "4xx": query = query.Where("status_code >= 400 AND status_code < 500") case "serverError", "5xx": query = query.Where("status_code >= 500 AND status_code < 600") + case "other": + // 保留真实 HTTP 状态:2xx 响应头之后的流失败通过 error_code 识别; + // 同时覆盖不属于 2xx/4xx/5xx 的状态段。status_code < 100 兼容 + // 曾运行过早期实现并写入 0 的开发数据库,但新记录仍只允许 100..599。 + query = query.Where("(status_code >= 200 AND status_code < 300 AND error_code IS NOT NULL AND error_code <> '') OR status_code < 200 OR (status_code >= 300 AND status_code < 400) OR status_code >= 600") } switch filter.Mode { case "stream": diff --git a/backend/internal/infra/persistence/relational/audit_repository_test.go b/backend/internal/infra/persistence/relational/audit_repository_test.go index 67c29cbf..b53c0f1a 100644 --- a/backend/internal/infra/persistence/relational/audit_repository_test.go +++ b/backend/internal/infra/persistence/relational/audit_repository_test.go @@ -489,4 +489,53 @@ func TestAuditRepositorySummaryAppliesRangeAndGroupsPricingTier(t *testing.T) { } } +func TestAuditRepositoryStreamFailureKeepsHTTPStatusAndFiltersAsOther(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "audit-stream-failure.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repository := NewAuditRepository(database) + now := time.Now().UTC() + values := []audit.Record{ + {RequestID: "stream-interrupted", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "public", StatusCode: 200, Streaming: true, ErrorCode: "upstream_stream_interrupted", DurationMS: 616_731, CreatedAt: now.Add(-time.Hour)}, + {RequestID: "healthy", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "public", StatusCode: 200, Streaming: true, InputTokens: 100, OutputTokens: 50, TotalTokens: 150, DurationMS: 100, CreatedAt: now.Add(-2 * time.Hour)}, + {RequestID: "server-error", ClientKeyID: 1, ModelRouteID: 1, ModelPublicID: "public", StatusCode: 500, ErrorCode: "upstream_server_error", DurationMS: 50, CreatedAt: now.Add(-3 * time.Hour)}, + } + if err := repository.CreateBatch(ctx, values); err != nil { + t.Fatal(err) + } + // 真实 HTTP 200 被保留,但带 error_code 的流式记录计入失败。 + summary, err := repository.Summarize(ctx, repositorypkg.AuditSummaryQuery{Start: now.Add(-24 * time.Hour), End: now}) + if err != nil { + t.Fatal(err) + } + if summary.Requests != 3 || summary.SuccessfulRequests != 1 || summary.FailedRequests != 2 { + t.Fatalf("summary = %#v", summary) + } + // "其它错误"筛选通过 error_code 命中 2xx 响应头之后的流失败。 + items, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 50, Filter: repositorypkg.AuditListFilter{Status: "other"}}) + if err != nil { + t.Fatal(err) + } + if len(items) != 1 || items[0].RequestID != "stream-interrupted" { + t.Fatalf("other filter items = %#v", items) + } + if items[0].StatusCode != 200 { + t.Fatalf("stream failure status = %d, want original HTTP 200", items[0].StatusCode) + } + // "成功"筛选排除带错误码的记录。 + items, _, err = repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 50, Filter: repositorypkg.AuditListFilter{Status: "success"}}) + if err != nil { + t.Fatal(err) + } + if len(items) != 1 || items[0].RequestID != "healthy" { + t.Fatalf("success filter items = %#v", items) + } +} + func uint64Pointer(value uint64) *uint64 { return &value } diff --git a/backend/internal/infra/persistence/relational/client_key_repository.go b/backend/internal/infra/persistence/relational/client_key_repository.go index baaa786d..1588c576 100644 --- a/backend/internal/infra/persistence/relational/client_key_repository.go +++ b/backend/internal/infra/persistence/relational/client_key_repository.go @@ -4,6 +4,7 @@ import ( "context" "errors" "sort" + "strconv" "strings" "time" @@ -34,8 +35,13 @@ func (r *ClientKeyRepository) List(ctx context.Context, input repository.ClientK var total int64 query := r.db.db.WithContext(ctx).Model(&clientKeyModel{}).Where("internal_kind IS NULL") if search := strings.TrimSpace(input.Page.Search); search != "" { - pattern := "%" + strings.ToLower(search) + "%" - query = query.Where("LOWER(name) LIKE ? OR LOWER(prefix) LIKE ?", pattern, pattern) + if id, err := strconv.ParseUint(strings.TrimPrefix(search, "#"), 10, 64); strings.HasPrefix(search, "#") && err == nil && id > 0 { + // #ID 走主键索引;普通数字仍按名称/前缀搜索,保持现有 API 兼容。 + query = query.Where("client_keys.id = ?", id) + } else { + pattern := "%" + strings.ToLower(search) + "%" + query = query.Where("LOWER(name) LIKE ? OR LOWER(prefix) LIKE ?", pattern, pattern) + } } switch input.Filter.Status { case "active": diff --git a/backend/internal/infra/persistence/relational/dashboard_repository.go b/backend/internal/infra/persistence/relational/dashboard_repository.go index 0a097818..673b047e 100644 --- a/backend/internal/infra/persistence/relational/dashboard_repository.go +++ b/backend/internal/infra/persistence/relational/dashboard_repository.go @@ -19,8 +19,7 @@ func NewDashboardRepository(db *Database) *DashboardRepository { return &Dashboa const dashboardUsageAggregateSelect = ` COUNT(*) AS requests, - COALESCE(SUM(CASE WHEN status_code >= 200 AND status_code < 300 THEN 1 ELSE 0 END), 0) AS successful_requests, - COALESCE(SUM(CASE WHEN status_code < 200 OR status_code >= 300 THEN 1 ELSE 0 END), 0) AS failed_requests, + ` + auditSuccessAggregate + ` AS successful_requests, COALESCE(SUM(input_tokens), 0) AS input_tokens, COALESCE(SUM(cached_input_tokens), 0) AS cached_input_tokens, COALESCE(SUM(output_tokens), 0) AS output_tokens, @@ -99,6 +98,7 @@ func (r *DashboardRepository) Snapshot(ctx context.Context, window repository.Da Scan(&result.Usage).Error; err != nil { return err } + result.Usage.FailedRequests = result.Usage.Requests - result.Usage.SuccessfulRequests var buckets []struct { BucketIndex int `gorm:"column:bucket_index"` Requests int64 @@ -146,7 +146,7 @@ func (r *DashboardRepository) Snapshot(ctx context.Context, window repository.Da Tokens int64 } if err := tx.Model(&requestAuditModel{}). - Select("provider, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN status_code >= 200 AND status_code < 300 THEN 1 ELSE 0 END), 0) AS successful_requests, COALESCE(SUM(total_tokens), 0) AS tokens"). + Select("provider, COUNT(*) AS requests, "+auditSuccessAggregate+" AS successful_requests, COALESCE(SUM(total_tokens), 0) AS tokens"). Where("created_at >= ? AND created_at < ?", start, end). Group("provider"). Order("requests DESC, provider ASC"). diff --git a/backend/internal/infra/persistence/relational/dashboard_repository_test.go b/backend/internal/infra/persistence/relational/dashboard_repository_test.go index ba1742b4..a3a64bb5 100644 --- a/backend/internal/infra/persistence/relational/dashboard_repository_test.go +++ b/backend/internal/infra/persistence/relational/dashboard_repository_test.go @@ -112,6 +112,34 @@ func TestDashboardRepositorySnapshot(t *testing.T) { } } +func TestDashboardRepositoryCounts2xxWithErrorAsFailure(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "dashboard-stream-failure.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.UTC) + audits := []requestAuditModel{ + {RequestID: "healthy", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", Operation: "responses", UsageSource: "upstream", StatusCode: 200, CreatedAt: now.Add(-2 * time.Minute)}, + {RequestID: "stream-interrupted", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", Operation: "responses", UsageSource: "upstream", StatusCode: 200, Streaming: true, ErrorCode: "upstream_stream_interrupted", CreatedAt: now.Add(-time.Minute)}, + } + if err := database.db.WithContext(ctx).Create(&audits).Error; err != nil { + t.Fatal(err) + } + boundaries := testDashboardBoundaries(now.Add(-time.Hour), time.Hour, 2) + snapshot, err := NewDashboardRepository(database).Snapshot(ctx, testDashboardWindow(boundaries), now) + if err != nil { + t.Fatal(err) + } + if snapshot.Usage.Requests != 2 || snapshot.Usage.SuccessfulRequests != 1 || snapshot.Usage.FailedRequests != 1 { + t.Fatalf("usage = %#v", snapshot.Usage) + } +} + func BenchmarkDashboardUsageAggregate(b *testing.B) { ctx := context.Background() database, err := OpenSQLite(ctx, filepath.Join(b.TempDir(), "dashboard-benchmark.db")) diff --git a/backend/internal/infra/persistence/relational/list_filter_repository_test.go b/backend/internal/infra/persistence/relational/list_filter_repository_test.go index d355bb6e..96299aaa 100644 --- a/backend/internal/infra/persistence/relational/list_filter_repository_test.go +++ b/backend/internal/infra/persistence/relational/list_filter_repository_test.go @@ -3,6 +3,7 @@ package relational import ( "context" "path/filepath" + "strconv" "testing" "time" @@ -49,6 +50,7 @@ func TestListFilters(t *testing.T) { } accounts := NewAccountRepository(database) + assertAccountSearchResult(t, ctx, accounts, "#"+strconv.FormatUint(free.ID, 10), free.ID) assertAccountFilterCount(t, ctx, accounts, repository.AccountListFilter{QuotaType: "free", Now: now}, 1) assertAccountFilterCount(t, ctx, accounts, repository.AccountListFilter{QuotaType: "paid", Now: now}, 1) assertAccountFilterCount(t, ctx, accounts, repository.AccountListFilter{QuotaType: "unknown", Now: now}, 1) @@ -246,6 +248,7 @@ func TestListFilters(t *testing.T) { } assertClientKeySearchCount(t, ctx, keys, "production", 1) assertClientKeySearchCount(t, ctx, keys, "abc123", 1) + assertClientKeySearchResult(t, ctx, keys, "#"+strconv.FormatUint(activeKey.ID, 10), activeKey.ID) keyValues, _, err := keys.List(ctx, repository.ClientKeyListQuery{Page: repository.PageQuery{Limit: 20, Sort: repository.SortQuery{Field: "name", Direction: repository.SortDescending}}, Filter: repository.ClientKeyListFilter{Now: now}}) if err != nil || len(keyValues) != 3 || keyValues[0].Name != "production" || keyValues[2].Name != "disabled" { t.Fatalf("client key name sort = %#v, err = %v", keyValues, err) @@ -320,6 +323,14 @@ func assertAccountFilterCount(t *testing.T, ctx context.Context, accounts *Accou } } +func assertAccountSearchResult(t *testing.T, ctx context.Context, accounts *AccountRepository, search string, expectedID uint64) { + t.Helper() + values, total, err := accounts.List(ctx, repository.AccountListQuery{Page: repository.PageQuery{Limit: 20, Search: search}}) + if err != nil || total != 1 || len(values) != 1 || values[0].ID != expectedID { + t.Fatalf("account search %q values = %#v, total = %d, err = %v", search, values, total, err) + } +} + func assertModelSearchCount(t *testing.T, ctx context.Context, models *ModelRepository, search string, expected int64) { t.Helper() _, total, err := models.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 20, Search: search}}) @@ -336,6 +347,14 @@ func assertClientKeySearchCount(t *testing.T, ctx context.Context, keys *ClientK } } +func assertClientKeySearchResult(t *testing.T, ctx context.Context, keys *ClientKeyRepository, search string, expectedID uint64) { + t.Helper() + values, total, err := keys.List(ctx, repository.ClientKeyListQuery{Page: repository.PageQuery{Limit: 20, Search: search}, Filter: repository.ClientKeyListFilter{Now: time.Now().UTC()}}) + if err != nil || total != 1 || len(values) != 1 || values[0].ID != expectedID { + t.Fatalf("client key search %q values = %#v, total = %d, err = %v", search, values, total, err) + } +} + func assertAuditSearchResult(t *testing.T, ctx context.Context, audits *AuditRepository, search, expectedRequestID string) { t.Helper() values, _, err := audits.ListCursor(ctx, repository.AuditCursorQuery{Limit: 20, Search: search}) diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts index bef4c9b8..880d3443 100644 --- a/frontend/src/features/accounts/accounts-api.ts +++ b/frontend/src/features/accounts/accounts-api.ts @@ -222,7 +222,8 @@ type ListAccountsInput = { risk?: string; agreement?: string; association?: string; - provider: AccountProvider; + // 为空时返回全部 provider 的账号,用于跨 provider 的通用名单(如请求审计筛选)。 + provider?: AccountProvider; sortBy?: string; sortOrder?: SortOrder; }; @@ -241,7 +242,7 @@ export function listAccounts(input: ListAccountsInput): Promise listModels({ page: 1, pageSize: 100 }), staleTime: 60_000, }); + // 密钥/账号筛选名单只在对应三级菜单展开时懒加载,输入后重新按匹配查询。 + const [keyFilterOptionsOpen, setKeyFilterOptionsOpen] = useState(false); + const [accountFilterOptionsOpen, setAccountFilterOptionsOpen] = useState(false); + const [keyFilterOptionsSearch, setKeyFilterOptionsSearch] = useState(""); + const [accountFilterOptionsSearch, setAccountFilterOptionsSearch] = useState(""); + const debouncedKeyFilterOptionsSearch = useDebouncedValue(keyFilterOptionsSearch); + const debouncedAccountFilterOptionsSearch = useDebouncedValue(accountFilterOptionsSearch); + const keyFilterOptionsQuery = useQuery({ + queryKey: ["client-keys", "audit-filter", debouncedKeyFilterOptionsSearch], + queryFn: () => listClientKeys({ page: 1, pageSize: AUDIT_FILTER_PAGE_SIZE, search: auditFilterOptionSearch(debouncedKeyFilterOptionsSearch) }), + enabled: keyFilterOptionsOpen, + staleTime: 60_000, + }); + const accountFilterOptionsQuery = useQuery({ + queryKey: ["accounts", "audit-filter", debouncedAccountFilterOptionsSearch], + queryFn: () => listAccounts({ page: 1, pageSize: AUDIT_FILTER_PAGE_SIZE, search: auditFilterOptionSearch(debouncedAccountFilterOptionsSearch) }), + enabled: accountFilterOptionsOpen, + staleTime: 60_000, + }); + const keyFilterOptionsFailed = keyFilterOptionsQuery.isError; + const keyFilterOptionsFetching = keyFilterOptionsQuery.isFetching; + const accountFilterOptionsFailed = accountFilterOptionsQuery.isError; + const accountFilterOptionsFetching = accountFilterOptionsQuery.isFetching; + // 账号范围覆盖三种 provider,审计记录可能来自任一 provider 的账号。 + const keyFilterOptions = keyFilterOptionsQuery.data?.items ?? []; + const accountFilterOptions = accountFilterOptionsQuery.data?.items ?? []; + const keyFilterGroups = [ + { + id: "keys", label: t("audits.key"), + emptyLabel: keyFilterOptionsFailed ? t("audits.filterOptionsLoadFailed") : keyFilterOptionsFetching ? t("common.loading") : t("audits.filterOptionsEmpty"), + options: keyFilterOptions.map((key) => ({ + value: String(key.id), + label: key.name || key.prefix, + description: `#${key.id} · ${key.prefix}`, + })), + loading: keyFilterOptionsFetching, hasMore: keyFilterOptionsFailed, + actionLabel: t("common.retry"), onAction: () => { void keyFilterOptionsQuery.refetch(); }, + noteLabel: !keyFilterOptionsFailed && (keyFilterOptionsQuery.data?.total ?? 0) > keyFilterOptions.length ? t("audits.filterOptionsTruncated") : undefined, + hideLabel: true, + maxHeightClassName: AUDIT_FILTER_MAX_HEIGHT, + }, + ]; + const accountFilterGroups = [ + { + id: "accounts", label: t("audits.account"), + emptyLabel: accountFilterOptionsFailed ? t("audits.filterOptionsLoadFailed") : accountFilterOptionsFetching ? t("common.loading") : t("audits.filterOptionsEmpty"), + options: accountFilterOptions.map((account) => ({ + value: String(account.id), + label: account.name || account.email || `#${account.id}`, + description: `#${account.id}`, + badge: providerShortLabel(account.provider), + })), + loading: accountFilterOptionsFetching, hasMore: accountFilterOptionsFailed, + actionLabel: t("common.retry"), onAction: () => { void accountFilterOptionsQuery.refetch(); }, + noteLabel: !accountFilterOptionsFailed && (accountFilterOptionsQuery.data?.total ?? 0) > accountFilterOptions.length ? t("audits.filterOptionsTruncated") : undefined, + hideLabel: true, + maxHeightClassName: AUDIT_FILTER_MAX_HEIGHT, + }, + ]; const result = auditsQuery.data; const nextCursor = result?.nextCursor ?? ""; const summary = summaryQuery.data; @@ -162,13 +227,36 @@ export function RequestAuditsPage() { { value: "2xx", label: `2xx · ${t("audits.statusSuccess")}` }, { value: "4xx", label: `4xx · ${t("audits.statusClientError")}` }, { value: "5xx", label: `5xx · ${t("audits.statusServerError")}` }, + { value: "other", label: t("audits.statusOtherError") }, ] }, { id: "mode", label: t("audits.mode"), value: modeFilter, onChange: setModeFilter, options: [ { value: "stream", label: t("audits.stream") }, { value: "nonStream", label: t("audits.nonStream") }, ] }, - { id: "key", type: "text", label: t("audits.key"), value: keyFilter, placeholder: t("audits.keyFilterPlaceholder"), onChange: setKeyFilter }, - { id: "account", type: "text", label: t("audits.account"), value: accountFilter, placeholder: t("audits.accountFilterPlaceholder"), onChange: setAccountFilter }, + { + id: "key", label: t("audits.key"), value: keyFilter, + onChange: setKeyFilter, options: [ + { + value: "any", label: t("audits.key"), groups: keyFilterGroups, + onGroupsOpenChange: setKeyFilterOptionsOpen, + groupSearch: { value: keyFilterOptionsSearch, placeholder: t("audits.keyFilterPlaceholder"), onChange: (value) => { + setKeyFilterOptionsSearch(value); + } }, + }, + ], + }, + { + id: "account", label: t("audits.account"), value: accountFilter, + onChange: setAccountFilter, options: [ + { + value: "any", label: t("audits.account"), groups: accountFilterGroups, + onGroupsOpenChange: setAccountFilterOptionsOpen, + groupSearch: { value: accountFilterOptionsSearch, placeholder: t("audits.accountFilterPlaceholder"), onChange: (value) => { + setAccountFilterOptionsSearch(value); + } }, + }, + ], + }, ]} /> @@ -553,9 +641,20 @@ function StatusCode({ statusCode, hasError = false }: { statusCode: number; hasE function AuditStatus({ audit, onOpen }: { audit: AuditDTO; onOpen: () => void }) { const { t } = useTranslation(); const mode = audit.operation === "compaction" ? t("audits.operations.compaction") : audit.streaming ? t("audits.stream") : t("audits.nonStream"); + const hasError = Boolean(audit.errorCode); + // 保留真实 HTTP 状态,同时明确标识 2xx 响应头之后发生的流式失败。 + // statusCode 0 仅兼容曾运行过早期实现的开发数据库。 + const showErrorLabel = hasError && (audit.statusCode === 0 || (audit.statusCode >= 200 && audit.statusCode < 300)); const content = ( <> - + {showErrorLabel ? ( + + + {audit.statusCode > 0 ? `${audit.statusCode} · ` : ""}{t("audits.errorLabel")} + + ) : ( + + )} {mode} ); @@ -591,6 +690,22 @@ function providerLabel(provider: AuditDTO["provider"]): string { } } +function providerShortLabel(provider: AuditDTO["provider"]): string { + switch (provider) { + case "grok_build": + return "Build"; + case "grok_web": + return "Web"; + case "grok_console": + return "Console"; + } +} + +function auditFilterOptionSearch(value: string): string { + const trimmed = value.trim(); + return /^\d+$/.test(trimmed) ? `#${trimmed}` : trimmed; +} + function formatUSDCost(ticks: number, fractionDigits: number): string { return `$${(ticks / 10_000_000_000).toFixed(fractionDigits)}`; } diff --git a/frontend/src/shared/components/data-table-filters.tsx b/frontend/src/shared/components/data-table-filters.tsx index 42b7d6c9..d1f0b4b9 100644 --- a/frontend/src/shared/components/data-table-filters.tsx +++ b/frontend/src/shared/components/data-table-filters.tsx @@ -1,4 +1,4 @@ -import { Check, ListFilter, X } from "lucide-react"; +import { Check, ListFilter, Search, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { Button } from "@/components/ui/button"; @@ -10,12 +10,16 @@ import { Input } from "@/components/ui/input"; type DataTableFilterOptionGroup = { id: string; label: string; - options: Array<{ value: string; label: string }>; + options: Array<{ value: string; label: string; description?: string; badge?: string }>; emptyLabel?: string; loading?: boolean; hasMore?: boolean; actionLabel?: string; onAction?: () => void; + noteLabel?: string; + hideLabel?: boolean; + // 名单内容超出该高度时内部滚动(例如 max-h-40 = 5 行),避免菜单被拉得很长。 + maxHeightClassName?: string; }; type DataTableFilterOption = { @@ -123,27 +127,50 @@ export function DataTableFilters({ filters }: { filters: DataTableFilter[] }) { {narrowedLabel ? {narrowedLabel} : null} {option.value === filter.value ? : null} - + {option.groupSearch ? ( -
event.stopPropagation()}> - option.groupSearch?.onChange(event.target.value)} - /> +
event.stopPropagation()}> +
+ + option.groupSearch?.onChange(event.target.value)} + /> +
) : null} - {t("common.all")} + {t("common.all")} {option.groups.map((group) => (
- {group.label} - {group.options.length === 0 - ? {group.emptyLabel ?? t("common.noData")} - : group.options.map((entry) => {entry.label})} + {!group.hideLabel ? {group.label} : null} +
+ {group.options.length === 0 + ? {group.emptyLabel ?? t("common.noData")} + : group.options.map((entry) => ( + + {entry.description || entry.badge ? ( + + {entry.label} + + {entry.description ? {entry.description} : null} + {entry.description && entry.badge ? : null} + {entry.badge ? {entry.badge} : null} + + + ) : entry.label} + + ))} +
+ {group.noteLabel ?
{group.noteLabel}
: null} {group.hasMore && group.onAction ? (