diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index f9a8904e6c..3d37b26956 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -147,12 +147,13 @@ type WindowStats struct { // UsageProgress 使用量进度 type UsageProgress struct { - Utilization float64 `json:"utilization"` // 使用率百分比 (0-100+,100表示100%) - ResetsAt *time.Time `json:"resets_at"` // 重置时间 - RemainingSeconds int `json:"remaining_seconds"` // 距重置剩余秒数 - WindowStats *WindowStats `json:"window_stats,omitempty"` // 窗口期统计(从窗口开始到当前的使用量) - UsedRequests int64 `json:"used_requests,omitempty"` - LimitRequests int64 `json:"limit_requests,omitempty"` + Utilization float64 `json:"utilization"` // 使用率百分比 (0-100+,100表示100%) + UtilizationUnknown bool `json:"utilization_unknown,omitempty"` // 仅有本地统计,上游使用率未知 + ResetsAt *time.Time `json:"resets_at"` // 重置时间 + RemainingSeconds int `json:"remaining_seconds"` // 距重置剩余秒数 + WindowStats *WindowStats `json:"window_stats,omitempty"` // 窗口期统计(从窗口开始到当前的使用量) + UsedRequests int64 `json:"used_requests,omitempty"` + LimitRequests int64 `json:"limit_requests,omitempty"` } // AntigravityQuotaGroup is a group of Antigravity models that share their quota windows. @@ -752,7 +753,7 @@ func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, accountID func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Account, force bool) (*UsageInfo, error) { now := time.Now() - usage := &UsageInfo{UpdatedAt: &now} + usage := &UsageInfo{Source: "passive"} if account == nil { return usage, nil @@ -769,10 +770,11 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou if account.IsShadow() { updates = buildCodexSparkWindowExtraUpdates(quotaUsage, now) } - if len(updates) > 0 { + if hasOpenAIQuotaObservation(updates) { mergeAccountExtra(account, updates) s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates) applyExtraToUsage(usage, account.Extra, now) + usage.Source = "active" } } } @@ -783,28 +785,30 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou // Extra keys and immediately reflected in the returned UsageInfo. if s.openAIQuotaService != nil { if quotaUsage, err := s.openAIQuotaService.QueryUsage(WithScopedAdminAccountOperation(ctx, "accounts.usage.read"), account.ID); err == nil { - if updates := buildCodexSparkWindowExtraUpdates(quotaUsage, now); len(updates) > 0 { + if updates := buildCodexSparkWindowExtraUpdates(quotaUsage, now); hasOpenAIQuotaObservation(updates) { mergeAccountExtra(account, updates) s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates) if account.ParentAccountID != nil && adminaccess.RestrictedFromContext(ctx) == nil { notifyOpenAIAutoReset(*account.ParentAccountID) } - if usage.UpdatedAt == nil { - usage.UpdatedAt = &now - } applyExtraToUsage(usage, account.Extra, now) + usage.Source = "active" } } } } else { - if updates, err := s.probeOpenAICodexSnapshot(ctx, account); err == nil && len(updates) > 0 { + if updates, err := s.probeOpenAICodexSnapshot(ctx, account); err == nil && hasOpenAIQuotaObservation(updates) { mergeAccountExtra(account, updates) - if usage.UpdatedAt == nil { - usage.UpdatedAt = &now - } applyExtraToUsage(usage, account.Extra, now) + usage.Source = "active" } } + if usage.Source != "active" { + // Keep the last observation available, but never turn a failed probe + // (or a response without quota data) into a fresh successful read. + usage.ErrorCode = "quota_refresh_failed" + usage.Error = "Unable to refresh OpenAI quota; displayed values may be from an earlier observation" + } } if s.usageLogRepo == nil { @@ -813,14 +817,14 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou if stats, err := s.usageLogRepo.GetAccountWindowStats(ctx, account.ID, codexWindowStatsStart(usage.FiveHour, 5*time.Hour, now)); err == nil { if usage.FiveHour == nil { - usage.FiveHour = &UsageProgress{Utilization: 0} + usage.FiveHour = &UsageProgress{UtilizationUnknown: true} } usage.FiveHour.WindowStats = windowStatsFromAccountStats(stats) } if stats, err := s.usageLogRepo.GetAccountWindowStats(ctx, account.ID, codexWindowStatsStart(usage.SevenDay, 7*24*time.Hour, now)); err == nil { if usage.SevenDay == nil { - usage.SevenDay = &UsageProgress{Utilization: 0} + usage.SevenDay = &UsageProgress{UtilizationUnknown: true} } usage.SevenDay.WindowStats = windowStatsFromAccountStats(stats) } @@ -963,7 +967,7 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco if err != nil { return nil, err } - if len(updates) > 0 { + if hasOpenAIQuotaObservation(updates) { s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates) return updates, nil } @@ -1026,6 +1030,14 @@ func applyExtraToUsage(usage *UsageInfo, extra map[string]any, now time.Time) { if usage == nil { return } + // updated_at is the upstream observation time, not the time the UI read + // this cache. Legacy snapshots without a timestamp have unknown freshness. + usage.UpdatedAt = nil + if raw, ok := extra["codex_usage_updated_at"]; ok { + if observedAt, err := parseTime(fmt.Sprint(raw)); err == nil && !observedAt.IsZero() { + usage.UpdatedAt = &observedAt + } + } if progress := buildCodexUsageProgressFromExtra(extra, "5h", now); progress != nil { usage.FiveHour = progress } @@ -1034,6 +1046,12 @@ func applyExtraToUsage(usage *UsageInfo, extra map[string]any, now time.Time) { } } +func hasOpenAIQuotaObservation(updates map[string]any) bool { + _, has5h := updates["codex_5h_used_percent"] + _, has7d := updates["codex_7d_used_percent"] + return has5h || has7d +} + func (s *AccountUsageService) getGeminiUsage(ctx context.Context, account *Account) (*UsageInfo, error) { now := time.Now() usage := &UsageInfo{ diff --git a/backend/internal/service/account_usage_service_spark_shadow_test.go b/backend/internal/service/account_usage_service_spark_shadow_test.go index 442ac6b4b0..0d4af0bf37 100644 --- a/backend/internal/service/account_usage_service_spark_shadow_test.go +++ b/backend/internal/service/account_usage_service_spark_shadow_test.go @@ -148,4 +148,69 @@ func TestGetOpenAIUsage_SparkShadow_WritesExtraAndReturnsNonEmptyWindows(t *test "returned UsageInfo.FiveHour must be non-nil (rebuild from merged Extra must happen)") require.NotNil(t, usage.SevenDay, "returned UsageInfo.SevenDay must be non-nil (rebuild from merged Extra must happen)") + require.Equal(t, "active", usage.Source) + require.Empty(t, usage.Error) + require.NotNil(t, usage.UpdatedAt) + observedAt, err := time.Parse(time.RFC3339, shadow.Extra["codex_usage_updated_at"].(string)) + require.NoError(t, err) + require.True(t, usage.UpdatedAt.Equal(observedAt)) +} + +func TestGetOpenAIUsage_SparkShadow_FailedOrEmptyQueryDoesNotRefreshSnapshot(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + status int + body string + }{ + {"expired token", http.StatusUnauthorized, `{"error":{"code":"token_expired"}}`}, + {"empty quota", http.StatusOK, `{}`}, + {"empty windows", http.StatusOK, `{"additional_rate_limits":[{"metered_feature":"codex_bengalfox","rate_limit":{}}]}`}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + observedAt := time.Now().Add(-24 * time.Hour).UTC().Truncate(time.Second) + parentID := int64(100) + parent := &Account{ID: parentID, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive} + shadow := &Account{ + ID: 200, ParentAccountID: &parentID, + Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, + QuotaDimension: QuotaDimensionSpark, + Extra: map[string]any{ + "codex_7d_used_percent": 100.0, + "codex_usage_updated_at": observedAt.Format(time.RFC3339), + }, + } + repo := &sparkShadowUsageTestRepo{ + accounts: map[int64]*Account{100: parent, 200: shadow}, + updateExtraCh: make(chan map[string]any, 1), + } + tokens := &stubQuotaTokenCache{tokens: map[string]string{OpenAITokenCacheKey(parent): "fake-access-token"}} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + })) + defer srv.Close() + svc := &AccountUsageService{ + accountRepo: repo, + openAIQuotaService: NewOpenAIQuotaService(repo, nil, NewOpenAITokenProvider(repo, tokens, nil), newQuotaRedirectingFactory(srv), nil), + } + usage, err := svc.getOpenAIUsage(context.Background(), shadow, true) + require.NoError(t, err) + require.Equal(t, "quota_refresh_failed", usage.ErrorCode) + require.NotEmpty(t, usage.Error) + require.Equal(t, "passive", usage.Source) + require.NotNil(t, usage.UpdatedAt) + require.True(t, usage.UpdatedAt.Equal(observedAt)) + require.NotNil(t, usage.SevenDay) + require.Equal(t, 100.0, usage.SevenDay.Utilization) + require.Equal(t, observedAt.Format(time.RFC3339), shadow.Extra["codex_usage_updated_at"]) + select { + case <-repo.updateExtraCh: + t.Fatal("failed or empty queries must not persist a fresh snapshot") + case <-time.After(100 * time.Millisecond): + } + }) + } } diff --git a/backend/internal/service/account_usage_service_test.go b/backend/internal/service/account_usage_service_test.go index ca153a3c42..7fded934d6 100644 --- a/backend/internal/service/account_usage_service_test.go +++ b/backend/internal/service/account_usage_service_test.go @@ -206,6 +206,96 @@ func TestAccountUsageService_GetOpenAIUsage_DoesNotPromoteCodexExtraToRateLimit( } } +func TestAccountUsageService_GetOpenAIUsage_PreservesSnapshotObservationTime(t *testing.T) { + t.Parallel() + observedAt := time.Now().Add(-48 * time.Hour).UTC().Truncate(time.Second) + for _, stamp := range []string{observedAt.Format(time.RFC3339), "", "invalid"} { + t.Run(stamp, func(t *testing.T) { + account := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Extra: map[string]any{ + "codex_5h_used_percent": 10.0, + "codex_7d_used_percent": 100.0, + "codex_usage_updated_at": stamp, + }, + } + usage, err := (&AccountUsageService{}).getOpenAIUsage(context.Background(), account, false) + if err != nil { + t.Fatal(err) + } + if stamp == observedAt.Format(time.RFC3339) { + if usage.UpdatedAt == nil || !usage.UpdatedAt.Equal(observedAt) { + t.Fatalf("cached snapshot must keep its observation time %v, got %v", observedAt, usage.UpdatedAt) + } + } else if usage.UpdatedAt != nil { + t.Fatalf("unknown observation time must not become the request time: %v", usage.UpdatedAt) + } + if usage.Source != "passive" || usage.Error != "" { + t.Fatalf("snapshot read should be passive, not a failed refresh: %#v", usage) + } + }) + } +} + +func TestAccountUsageService_GetOpenAIUsage_RefreshFailureKeepsCachedDataAndReportsError(t *testing.T) { + t.Parallel() + observedAt := time.Now().Add(-24 * time.Hour).UTC().Truncate(time.Second) + for _, shadow := range []bool{false, true} { + account := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Extra: map[string]any{ + "codex_7d_used_percent": 100.0, + "codex_usage_updated_at": observedAt.Format(time.RFC3339), + }, + } + if shadow { + parentID := int64(10) + account.ParentAccountID = &parentID + account.QuotaDimension = QuotaDimensionSpark + } + // Ordinary accounts have no token; shadow accounts have no quota service. + // Neither case may turn a failed query into a fresh, successful snapshot. + usage, err := (&AccountUsageService{}).getOpenAIUsage(context.Background(), account, true) + if err != nil { + t.Fatal(err) + } + if usage.ErrorCode != "quota_refresh_failed" || usage.Error == "" { + t.Fatalf("refresh failure was hidden (shadow=%v): %#v", shadow, usage) + } + if usage.SevenDay == nil || usage.SevenDay.Utilization != 100 { + t.Fatalf("last known quota should remain available: %#v", usage.SevenDay) + } + if usage.UpdatedAt == nil || !usage.UpdatedAt.Equal(observedAt) || usage.Source != "passive" { + t.Fatalf("failed refresh must not advance snapshot freshness: %#v", usage) + } + if account.RateLimitResetAt != nil || account.Extra["codex_usage_updated_at"] != observedAt.Format(time.RFC3339) { + t.Fatal("failed refresh must not mutate the snapshot or scheduler state") + } + } +} + +func TestAccountUsageService_GetOpenAIUsage_RefreshFailureWithoutSnapshot(t *testing.T) { + t.Parallel() + svc := &AccountUsageService{usageLogRepo: &usageBatchLogRepoStub{}} + usage, err := svc.getOpenAIUsage(context.Background(), &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + }, true) + if err != nil { + t.Fatal(err) + } + if usage.ErrorCode != "quota_refresh_failed" || usage.UpdatedAt != nil { + t.Fatalf("missing upstream quota must remain unknown after failure: %#v", usage) + } + for name, window := range map[string]*UsageProgress{"5h": usage.FiveHour, "7d": usage.SevenDay} { + if window == nil || window.WindowStats == nil || !window.UtilizationUnknown { + t.Errorf("%s should keep local stats while marking quota unknown: %#v", name, window) + } + } +} + func TestBuildCodexUsageProgressFromExtra_ZerosExpiredWindow(t *testing.T) { t.Parallel() now := time.Date(2026, 3, 16, 12, 0, 0, 0, time.UTC) diff --git a/backend/internal/service/channel_monitor_quota_fetcher.go b/backend/internal/service/channel_monitor_quota_fetcher.go index 868def18d3..8e2700137f 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher.go +++ b/backend/internal/service/channel_monitor_quota_fetcher.go @@ -309,7 +309,7 @@ func usageQuotaTiers(usage *UsageInfo) []domain.MonitorQuotaTier { } func appendProgressTier(tiers *[]domain.MonitorQuotaTier, window, label string, p *UsageProgress) { - if p == nil { + if p == nil || p.UtilizationUnknown { return } tier := domain.MonitorQuotaTier{ diff --git a/backend/internal/service/channel_monitor_quota_fetcher_test.go b/backend/internal/service/channel_monitor_quota_fetcher_test.go index b03b9fe33d..e37127bc63 100644 --- a/backend/internal/service/channel_monitor_quota_fetcher_test.go +++ b/backend/internal/service/channel_monitor_quota_fetcher_test.go @@ -694,6 +694,9 @@ func TestUsageQuotaTiers_MapsAllWindowKinds(t *testing.T) { func TestUsageQuotaTiers_NilAndEmptyInputs(t *testing.T) { require.Nil(t, usageQuotaTiers(nil)) require.Nil(t, usageQuotaTiers(&UsageInfo{})) + require.Nil(t, usageQuotaTiers(&UsageInfo{ + FiveHour: &UsageProgress{UtilizationUnknown: true, WindowStats: &WindowStats{Requests: 2}}, + })) // Grok 窗口 limit<=0 时跳过,避免除零。 var zero int64 diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index f6a7533838..39455c6d4f 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -124,11 +124,21 @@