diff --git a/backend/internal/application/account/quota_test.go b/backend/internal/application/account/quota_test.go index b7b73687..20a60b1a 100644 --- a/backend/internal/application/account/quota_test.go +++ b/backend/internal/application/account/quota_test.go @@ -1,12 +1,38 @@ package account import ( + "context" + "errors" + "slices" "testing" "time" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" ) +type quotaResetRepository struct { + repository.AccountRepository + countBatchSizes []int + resetBatchSizes []int +} + +func (r *quotaResetRepository) CountProviderAccountsByIDs(_ context.Context, provider accountdomain.Provider, ids []uint64) (int64, error) { + if provider != accountdomain.ProviderBuild { + return 0, nil + } + r.countBatchSizes = append(r.countBatchSizes, len(ids)) + return int64(len(ids)), nil +} + +func (r *quotaResetRepository) ResetQuotaState(_ context.Context, provider accountdomain.Provider, ids []uint64) error { + if provider != accountdomain.ProviderBuild { + return errors.New("unexpected provider") + } + r.resetBatchSizes = append(r.resetBatchSizes, len(ids)) + return nil +} + func TestNewQuotaViewFreeUsesObservedRollingTokens(t *testing.T) { quota := newQuotaView(&accountdomain.Billing{IsUnifiedBillingUser: true}, 250_000, nil, "grok-4.5-build-free", false) if quota.Type != QuotaTypeFree || quota.Unit != "tokens" || quota.Limit != 1_000_000 || quota.LimitKnown || quota.Confidence != "observed" { @@ -112,3 +138,119 @@ func TestNewQuotaViewBuildSuperEntitlementOverridesFreeSignals(t *testing.T) { t.Fatalf("paid billing must win: %#v", quota) } } + +func TestBatchResetQuotaStatePreservesBillingAndClearsLocalBlocks(t *testing.T) { + ctx := context.Background() + service, accounts := openAccountService(t) + credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "build", SourceKey: "quota-reset-build", + EncryptedAccessToken: "encrypted", Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + next := now.Add(24 * time.Hour) + if err := accounts.SaveBilling(ctx, accountdomain.Billing{AccountID: credential.ID, PlanName: "free", Used: 42, SyncedAt: now}); err != nil { + t.Fatal(err) + } + if err := accounts.SaveQuotaRecovery(ctx, accountdomain.QuotaRecovery{ + AccountID: credential.ID, Kind: accountdomain.QuotaRecoveryKindFree, Status: accountdomain.QuotaRecoveryStatusExhausted, + ExhaustedAt: &now, NextProbeAt: &next, UpdatedAt: now, + }); err != nil { + t.Fatal(err) + } + if err := accounts.UpsertModelQuotaBlock(ctx, accountdomain.ModelQuotaBlock{ + AccountID: credential.ID, UpstreamModel: "grok-test", Reason: "model_quota_depleted", CooldownUntil: next, + }); err != nil { + t.Fatal(err) + } + if err := accounts.UpsertModelQuotaBlock(ctx, accountdomain.ModelQuotaBlock{ + AccountID: credential.ID, UpstreamModel: "grok-denied", Reason: "model_access_denied", CooldownUntil: next, + }); err != nil { + t.Fatal(err) + } + + reset, err := service.BatchResetQuotaState(ctx, []uint64{credential.ID}) + if err != nil || reset != 1 { + t.Fatalf("reset = %d, err = %v", reset, err) + } + if _, err := accounts.GetQuotaRecovery(ctx, credential.ID); !errors.Is(err, repository.ErrNotFound) { + t.Fatalf("quota recovery should be cleared, err = %v", err) + } + billing, err := accounts.GetBilling(ctx, credential.ID) + if err != nil || billing.Used != 42 { + t.Fatalf("billing = %#v, err = %v", billing, err) + } + candidates, err := accounts.ListRoutingCandidates(ctx, accountdomain.ProviderBuild, 0, "grok-test", "") + if err != nil || len(candidates) != 1 || candidates[0].ModelQuotaBlock != nil { + t.Fatalf("candidates = %#v, err = %v", candidates, err) + } + candidates, err = accounts.ListRoutingCandidates(ctx, accountdomain.ProviderBuild, 0, "grok-denied", "") + if err != nil || len(candidates) != 1 || candidates[0].ModelQuotaBlock == nil || candidates[0].ModelQuotaBlock.Reason != "model_access_denied" { + t.Fatalf("access denial must be preserved, candidates = %#v, err = %v", candidates, err) + } +} + +func TestResetAllBuildQuotaStateOnlyProcessesEnabledBuildAccounts(t *testing.T) { + ctx := context.Background() + service, accounts := openAccountService(t) + create := func(providerValue accountdomain.Provider, sourceKey string, enabled bool) accountdomain.Credential { + value, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: providerValue, Name: sourceKey, SourceKey: sourceKey, + EncryptedAccessToken: "encrypted", Enabled: enabled, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + return value + } + enabledBuild := create(accountdomain.ProviderBuild, "reset-all-enabled", true) + disabledBuild := create(accountdomain.ProviderBuild, "reset-all-disabled", false) + web := create(accountdomain.ProviderWeb, "reset-all-web", true) + disabledBuild.Enabled = false + if _, err := accounts.Update(ctx, disabledBuild); err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + next := now.Add(24 * time.Hour) + for _, value := range []accountdomain.Credential{enabledBuild, disabledBuild, web} { + if err := accounts.SaveQuotaRecovery(ctx, accountdomain.QuotaRecovery{ + AccountID: value.ID, Kind: accountdomain.QuotaRecoveryKindFree, Status: accountdomain.QuotaRecoveryStatusExhausted, + ExhaustedAt: &now, NextProbeAt: &next, UpdatedAt: now, + }); err != nil { + t.Fatal(err) + } + } + + reset, err := service.ResetAllBuildQuotaState(ctx) + if err != nil || reset != 1 { + t.Fatalf("reset = %d, err = %v", reset, err) + } + if _, err := accounts.GetQuotaRecovery(ctx, enabledBuild.ID); !errors.Is(err, repository.ErrNotFound) { + t.Fatalf("enabled Build recovery should be cleared, err = %v", err) + } + for _, value := range []accountdomain.Credential{disabledBuild, web} { + if _, err := accounts.GetQuotaRecovery(ctx, value.ID); err != nil { + t.Fatalf("recovery for account %d should remain, err = %v", value.ID, err) + } + } +} + +func TestBatchResetQuotaStateChunksMoreThanAdminPageLimit(t *testing.T) { + repo := "aResetRepository{} + service := &Service{accounts: repo} + ids := make([]uint64, 2501) + for index := range ids { + ids[index] = uint64(index + 1) + } + + reset, err := service.BatchResetQuotaState(context.Background(), ids) + if err != nil || reset != len(ids) { + t.Fatalf("reset = %d, err = %v", reset, err) + } + want := []int{500, 500, 500, 500, 500, 1} + if !slices.Equal(repo.countBatchSizes, want) || !slices.Equal(repo.resetBatchSizes, want) { + t.Fatalf("count batches = %v, reset batches = %v, want %v", repo.countBatchSizes, repo.resetBatchSizes, want) + } +} diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 0183681f..b963c12d 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -61,6 +61,8 @@ const ( maxCredentialExportAccounts = 10000 maxCredentialImportAccounts = 10000 credentialImportChunkSize = 100 + maxQuotaResetAccounts = 10000 + quotaResetChunkSize = 500 maxBuildConversionAccounts = 1000 maxWebConsoleSyncAccounts = 1000 accountTaskBatchSize = 1000 @@ -2791,6 +2793,43 @@ func (s *Service) BatchRefreshBilling(ctx context.Context, ids []uint64) (int, i return s.refreshBillings(ctx, values, nil) } +// BatchResetQuotaState clears local Build quota recovery state without changing +// upstream billing snapshots or historical audit usage. +func (s *Service) BatchResetQuotaState(ctx context.Context, ids []uint64) (int, error) { + values, err := normalizeIDs(ids, maxQuotaResetAccounts) + if err != nil { + return 0, err + } + for start := 0; start < len(values); start += quotaResetChunkSize { + end := min(start+quotaResetChunkSize, len(values)) + count, countErr := s.accounts.CountProviderAccountsByIDs(ctx, accountdomain.ProviderBuild, values[start:end]) + if countErr != nil { + return 0, countErr + } + if count != int64(end-start) { + return 0, invalidInput("仅 Grok Build 账号支持手动重置额度状态") + } + } + reset := 0 + for start := 0; start < len(values); start += quotaResetChunkSize { + if err := ctx.Err(); err != nil { + return reset, err + } + end := min(start+quotaResetChunkSize, len(values)) + if err := s.accounts.ResetQuotaState(ctx, accountdomain.ProviderBuild, values[start:end]); err != nil { + return reset, err + } + reset += end - start + } + return reset, nil +} + +// ResetAllBuildQuotaState clears local quota state for every enabled Build +// account without materializing the complete account ID set in memory. +func (s *Service) ResetAllBuildQuotaState(ctx context.Context) (int64, error) { + return s.accounts.ResetProviderQuotaState(ctx, accountdomain.ProviderBuild, true) +} + // BatchRefreshQuota 使用有限并发同步选中 Web 或 Console 账号的额度窗口。 func (s *Service) BatchRefreshQuota(ctx context.Context, ids []uint64) (int, int, error) { values, err := normalizeBatchIDs(ids) diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index 1a700e53..7c7c73a5 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -36,15 +36,8 @@ const modelAccessDeniedCooldown = 5 * time.Minute const defaultFreeQuotaRecoveryPause = 24 * time.Hour -// paymentRequiredRecoveryPause is only the final fallback for a 402 account -// without an upstream reset, Retry-After, or parseable billing period. -const paymentRequiredRecoveryPause = 20 * time.Hour - type quotaRecoveryHints struct { - Billing *account.Billing - QuotaMode string - RetryAfter time.Duration - Fallback time.Duration + Billing *account.Billing } type candidateSnapshot struct { @@ -596,12 +589,9 @@ func (s *Selector) markSuccess(ctx context.Context, credential account.Credentia } } -func (s *Selector) MarkFreeQuotaExhausted(ctx context.Context, credential account.Credential, used, limit int64, hints quotaRecoveryHints) { +func (s *Selector) MarkFreeQuotaExhausted(ctx context.Context, credential account.Credential, used, limit int64) { now := time.Now().UTC() - if hints.Fallback <= 0 { - hints.Fallback = defaultFreeQuotaRecoveryPause - } - nextProbeAt := s.resolveQuotaRecoveryAt(ctx, credential.ID, now, hints) + nextProbeAt := now.Add(defaultFreeQuotaRecoveryPause) s.markFreeQuotaExhaustedAt(ctx, credential, used, limit, now, nextProbeAt) } @@ -615,13 +605,14 @@ func (s *Selector) markFreeQuotaExhaustedAt(ctx context.Context, credential acco s.invalidateCandidates(credential.Provider) } -func (s *Selector) MarkModelQuotaExhausted(ctx context.Context, credential account.Credential, upstreamModel string, retryAfter time.Duration) { +func (s *Selector) MarkModelQuotaExhausted(ctx context.Context, credential account.Credential, billing *account.Billing, upstreamModel string, retryAfter time.Duration) { upstreamModel = strings.TrimSpace(upstreamModel) if upstreamModel == "" { - s.MarkFreeQuotaExhausted(ctx, credential, 0, 0, quotaRecoveryHints{}) + s.MarkFreeQuotaExhausted(ctx, credential, 0, 0) return } - if retryAfter <= 0 { + knownFreeBuild := (account.RoutingCandidate{Credential: credential, Billing: billing}).IsKnownFreeBuild() + if knownFreeBuild || retryAfter <= 0 { retryAfter = defaultFreeQuotaRecoveryPause } until := time.Now().UTC().Add(retryAfter) @@ -650,8 +641,9 @@ func (s *Selector) MarkModelAccessDenied(ctx context.Context, credential account s.invalidateCandidates(credential.Provider) } -// MarkPaymentQuotaExhausted 将 402/spending-limit 账号移出号池。付费账号按真实账期 -// 进行 Billing 探测;Free/Unknown 依次采用上游 ResetAt、Retry-After、账期时间和 20h fallback。 +// MarkPaymentQuotaExhausted removes a spending-limited account from routing. +// Paid accounts follow their upstream billing period; Free or unknown accounts +// use the fixed local recovery window. func (s *Selector) MarkPaymentQuotaExhausted(ctx context.Context, credential account.Credential, hints quotaRecoveryHints) { now := time.Now().UTC() if hints.Billing != nil && hints.Billing.IsPaid() { @@ -665,36 +657,7 @@ func (s *Selector) MarkPaymentQuotaExhausted(ctx context.Context, credential acc return } } - hints.Fallback = paymentRequiredRecoveryPause - s.MarkFreeQuotaExhausted(ctx, credential, 0, 0, hints) -} - -func (s *Selector) resolveQuotaRecoveryAt(ctx context.Context, accountID uint64, now time.Time, hints quotaRecoveryHints) time.Time { - if mode := strings.TrimSpace(hints.QuotaMode); mode != "" { - if windows, err := s.accounts.GetQuotaWindows(ctx, []uint64{accountID}); err == nil { - var resetAt time.Time - for _, window := range windows[accountID] { - if window.Mode != mode || window.ResetAt == nil || !window.ResetAt.After(now) { - continue - } - if resetAt.IsZero() || window.ResetAt.Before(resetAt) { - resetAt = window.ResetAt.UTC() - } - } - if !resetAt.IsZero() { - return resetAt - } - } - } - if hints.RetryAfter > 0 { - return now.Add(hints.RetryAfter) - } - if hints.Billing != nil { - if periodEnd, ok := hints.Billing.PeriodEnd(); ok && periodEnd.After(now) { - return periodEnd - } - } - return now.Add(hints.Fallback) + s.MarkFreeQuotaExhausted(ctx, credential, 0, 0) } // MarkQuotaStateChanged 在 Billing 探测改变持久化额度状态后立即失效候选快照。 diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index eb2e96bf..39b59feb 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -145,7 +145,7 @@ func TestSelectorSkipsQuotaProbeBeforeDue(t *testing.T) { } } -func TestSelectorQuotaRecoveryUsesBestKnownReset(t *testing.T) { +func TestSelectorQuotaRecoveryUsesFixedFreeAndUpstreamPaidReset(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quota-recovery.db")) if err != nil { @@ -164,45 +164,67 @@ func TestSelectorQuotaRecoveryUsesBestKnownReset(t *testing.T) { t.Fatal(err) } now := time.Now().UTC() - resetAt := now.Add(4 * time.Hour).Truncate(time.Second) - if err := accounts.SaveQuotaWindows(ctx, value.ID, account.WebTierAuto, now, []account.QuotaWindow{{ - AccountID: value.ID, Mode: "fast", Remaining: 0, Total: 20, ResetAt: &resetAt, Source: account.QuotaSourceUpstream, - }}); err != nil { - t.Fatal(err) - } selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) paidPeriodEnd := now.Add(7 * time.Hour).Truncate(time.Second) selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{Billing: &account.Billing{ AccountID: value.ID, PlanCode: "super", MonthlyLimit: 100, BillingPeriodEnd: paidPeriodEnd.Format(time.RFC3339), - }, QuotaMode: "fast", RetryAfter: time.Hour}) + }}) recovery := requireQuotaRecovery(t, ctx, accounts, value.ID) if recovery.Kind != account.QuotaRecoveryKindPaid || recovery.NextProbeAt == nil || !recovery.NextProbeAt.Equal(paidPeriodEnd) { t.Fatalf("paid recovery = %#v", recovery) } - selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{QuotaMode: "fast", RetryAfter: time.Hour}) - recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) - if recovery.Kind != account.QuotaRecoveryKindFree || recovery.NextProbeAt == nil || !recovery.NextProbeAt.Equal(resetAt) { - t.Fatalf("upstream reset recovery = %#v", recovery) - } - - retryStarted := time.Now().UTC() - selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{QuotaMode: "missing", RetryAfter: 90 * time.Minute}) - recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) - assertRecoveryDelay(t, recovery, retryStarted, 90*time.Minute) - - fallbackStarted := time.Now().UTC() - selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{QuotaMode: "missing"}) - recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) - assertRecoveryDelay(t, recovery, fallbackStarted, paymentRequiredRecoveryPause) - freeStarted := time.Now().UTC() - selector.MarkFreeQuotaExhausted(ctx, value, 100, 100, quotaRecoveryHints{QuotaMode: "missing"}) + selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{}) + recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) + if recovery.Kind != account.QuotaRecoveryKindFree { + t.Fatalf("free recovery = %#v", recovery) + } + assertRecoveryDelay(t, recovery, freeStarted, defaultFreeQuotaRecoveryPause) + + freeStarted = time.Now().UTC() + selector.MarkFreeQuotaExhausted(ctx, value, 100, 100) recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) assertRecoveryDelay(t, recovery, freeStarted, defaultFreeQuotaRecoveryPause) } +func TestSelectorModelQuotaUsesFixedFreeAndUpstreamPaidDelay(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-quota-recovery.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + value, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "build", SourceKey: "model-quota-build", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, ObservedModel: "grok-4.5-build-free", + }) + if err != nil { + t.Fatal(err) + } + selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) + freeStarted := time.Now().UTC() + selector.MarkModelQuotaExhausted(ctx, value, &account.Billing{PlanName: "free"}, "free-model", time.Hour) + freeCandidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderBuild, 0, "free-model", "") + if err != nil || len(freeCandidates) != 1 || freeCandidates[0].ModelQuotaBlock == nil { + t.Fatalf("free candidates = %#v, err = %v", freeCandidates, err) + } + assertTimeDelay(t, freeCandidates[0].ModelQuotaBlock.CooldownUntil, freeStarted, defaultFreeQuotaRecoveryPause) + + paidStarted := time.Now().UTC() + selector.MarkModelQuotaExhausted(ctx, value, &account.Billing{PlanName: "SuperGrok"}, "paid-model", 2*time.Hour) + paidCandidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderBuild, 0, "paid-model", "") + if err != nil || len(paidCandidates) != 1 || paidCandidates[0].ModelQuotaBlock == nil { + t.Fatalf("paid candidates = %#v, err = %v", paidCandidates, err) + } + assertTimeDelay(t, paidCandidates[0].ModelQuotaBlock.CooldownUntil, paidStarted, 2*time.Hour) +} + func requireQuotaRecovery(t *testing.T, ctx context.Context, accounts repository.AccountRepository, accountID uint64) account.QuotaRecovery { t.Helper() recovery, err := accounts.GetQuotaRecovery(ctx, accountID) @@ -217,9 +239,14 @@ func assertRecoveryDelay(t *testing.T, recovery account.QuotaRecovery, started t if recovery.NextProbeAt == nil { t.Fatalf("recovery has no next probe: %#v", recovery) } + assertTimeDelay(t, *recovery.NextProbeAt, started, delay) +} + +func assertTimeDelay(t *testing.T, actual, started time.Time, delay time.Duration) { + t.Helper() want := started.Add(delay) - if recovery.NextProbeAt.Before(want.Add(-time.Second)) || recovery.NextProbeAt.After(want.Add(2*time.Second)) { - t.Fatalf("next probe = %s, want around %s", recovery.NextProbeAt, want) + if actual.Before(want.Add(-time.Second)) || actual.After(want.Add(2*time.Second)) { + t.Fatalf("time = %s, want around %s", actual, want) } } diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 0fa80ec4..7ec1992d 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -828,21 +828,17 @@ attemptLoop: s.selector.MarkQuotaStateChanged(credential.Provider) failureHandled = reconcileErr == nil && exhausted } else if used, limit, exhausted := parseFreeQuotaExhaustion(body); exhausted { - s.selector.MarkFreeQuotaExhausted(ctx, credential, used, limit, quotaRecoveryHints{ - Billing: lease.Billing, QuotaMode: lease.QuotaMode, RetryAfter: retryAfter, - }) + s.selector.MarkFreeQuotaExhausted(ctx, credential, used, limit) failureHandled = true } else if lastFailure.ModelQuotaExhausted { - s.selector.MarkModelQuotaExhausted(ctx, credential, route.UpstreamModel, retryAfter) + s.selector.MarkModelQuotaExhausted(ctx, credential, lease.Billing, route.UpstreamModel, retryAfter) failureHandled = true } else if lastFailure.FreeQuotaExhausted { - s.selector.MarkFreeQuotaExhausted(ctx, credential, 0, 0, quotaRecoveryHints{ - Billing: lease.Billing, QuotaMode: lease.QuotaMode, RetryAfter: retryAfter, - }) + s.selector.MarkFreeQuotaExhausted(ctx, credential, 0, 0) failureHandled = true } else if lastFailure.QuotaExhausted { s.selector.MarkPaymentQuotaExhausted(ctx, credential, quotaRecoveryHints{ - Billing: lease.Billing, QuotaMode: lease.QuotaMode, RetryAfter: retryAfter, + Billing: lease.Billing, }) failureHandled = true } diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index 609e8d9c..e68f3c36 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -1875,6 +1875,48 @@ func (r *AccountRepository) ClearQuotaRecovery(ctx context.Context, accountID ui return err } +func (r *AccountRepository) ResetQuotaState(ctx context.Context, provider account.Provider, accountIDs []uint64) error { + if len(accountIDs) == 0 { + return nil + } + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + if err := tx.Where("account_id IN ?", accountIDs).Delete("aRecoveryModel{}).Error; err != nil { + return err + } + return tx.Where("account_id IN ? AND reason = ?", accountIDs, "model_quota_depleted").Delete(&accountModelQuotaBlockModel{}).Error + }) + if err == nil { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountRecoveryChanged, Provider: provider}) + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountModelQuotaChanged, Provider: provider}) + } + return err +} + +func (r *AccountRepository) ResetProviderQuotaState(ctx context.Context, provider account.Provider, activeOnly bool) (int64, error) { + var accountCount int64 + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + accountQuery := func() *gorm.DB { + query := tx.Model(&accountModel{}).Where("provider = ?", provider) + if activeOnly { + query = query.Where("enabled = ? AND auth_status = ?", true, account.AuthStatusActive) + } + return query + } + if err := accountQuery().Count(&accountCount).Error; err != nil { + return err + } + if err := tx.Where("account_id IN (?)", accountQuery().Select("id")).Delete("aRecoveryModel{}).Error; err != nil { + return err + } + return tx.Where("account_id IN (?) AND reason = ?", accountQuery().Select("id"), "model_quota_depleted").Delete(&accountModelQuotaBlockModel{}).Error + }) + if err == nil && accountCount > 0 { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountRecoveryChanged, Provider: provider}) + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountModelQuotaChanged, Provider: provider}) + } + return accountCount, err +} + func (r *AccountRepository) HasQuotaWindows(ctx context.Context, accountID uint64) (bool, error) { var count int64 err := r.db.db.WithContext(ctx).Model("aWindowModel{}).Where("account_id = ? AND synced_at IS NOT NULL", accountID).Count(&count).Error diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index 7b82dcf7..2216d0eb 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -89,6 +89,8 @@ type AccountRepository interface { SaveQuotaRecovery(ctx context.Context, value account.QuotaRecovery) error ClaimQuotaProbe(ctx context.Context, accountID uint64, now, leaseUntil time.Time) (bool, error) ClearQuotaRecovery(ctx context.Context, accountID uint64) error + ResetQuotaState(ctx context.Context, provider account.Provider, accountIDs []uint64) error + ResetProviderQuotaState(ctx context.Context, provider account.Provider, activeOnly bool) (int64, error) HasQuotaWindows(ctx context.Context, accountID uint64) (bool, error) GetQuotaWindows(ctx context.Context, accountIDs []uint64) (map[uint64][]account.QuotaWindow, error) ReplaceQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go index 247be43b..c59f696c 100644 --- a/backend/internal/transport/http/account/handler.go +++ b/backend/internal/transport/http/account/handler.go @@ -148,9 +148,11 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.POST("/accounts/web/:id/nsfw", h.enableWebNSFW) router.POST("/accounts/console/refresh-quotas", h.refreshAllConsoleQuotas) router.POST("/accounts/refresh-billing", h.refreshAllBilling) + router.POST("/accounts/reset-quota", h.resetAllBuildQuota) router.POST("/accounts/refresh-tokens", h.refreshAllTokens) router.POST("/accounts/cleanup", h.cleanup) router.POST("/accounts/batch/refresh-billing", h.batchRefreshBilling) + router.POST("/accounts/batch/reset-quota", h.batchResetQuota) router.POST("/accounts/batch/refresh-quotas", h.batchRefreshQuotas) router.POST("/accounts/batch/refresh-tokens", h.batchRefreshTokens) router.PATCH("/accounts/batch", h.batchUpdate) @@ -477,6 +479,38 @@ func (h *Handler) batchRefreshBilling(c *gin.Context) { response.Success(c, http.StatusOK, gin.H{"succeeded": succeeded, "failed": failed}) } +func (h *Handler) batchResetQuota(c *gin.Context) { + var request batchDeleteRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + ids, err := parseIDs(request.IDs) + if err != nil { + response.Error(c, http.StatusBadRequest, "invalidId", err.Error()) + return + } + if request.Provider != string(accountdomain.ProviderBuild) { + response.Error(c, http.StatusBadRequest, "invalidProvider", "仅 Grok Build 账号支持手动重置额度状态") + return + } + reset, err := h.service.BatchResetQuotaState(c.Request.Context(), ids) + if err != nil { + h.writeServiceError(c, "quotaBatchResetFailed", err, http.StatusInternalServerError, "批量重置额度状态失败") + return + } + response.Success(c, http.StatusOK, gin.H{"reset": reset}) +} + +func (h *Handler) resetAllBuildQuota(c *gin.Context) { + reset, err := h.service.ResetAllBuildQuotaState(c.Request.Context()) + if err != nil { + h.writeServiceError(c, "quotaResetFailed", err, http.StatusInternalServerError, "重置全部 Grok Build 额度状态失败") + return + } + response.Success(c, http.StatusOK, gin.H{"reset": reset}) +} + func (h *Handler) cleanup(c *gin.Context) { var request accountCleanupRequest if c.ShouldBindJSON(&request) != nil { diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts index fe85233a..3cda385d 100644 --- a/frontend/src/features/accounts/accounts-api.ts +++ b/frontend/src/features/accounts/accounts-api.ts @@ -464,6 +464,14 @@ export function refreshAccountsQuota(ids: string[], provider: AccountProvider): return apiRequest("/api/admin/v1/accounts/batch/refresh-quotas", { method: "POST", body: { ids, provider } }, createObjectDecoder("account batch", { succeeded: isNumber, failed: isNumber })); } +export function resetAccountsQuota(ids: string[], provider: AccountProvider): Promise<{ reset: number }> { + return apiRequest("/api/admin/v1/accounts/batch/reset-quota", { method: "POST", body: { ids, provider } }, decodeCountResult<{ reset: number }>("reset")); +} + +export function resetAllAccountQuota(): Promise<{ reset: number }> { + return apiRequest("/api/admin/v1/accounts/reset-quota", { method: "POST" }, decodeCountResult<{ reset: number }>("reset")); +} + export function refreshAccountsTokens(ids: string[], provider: AccountProvider): Promise { return apiRequest("/api/admin/v1/accounts/batch/refresh-tokens", { method: "POST", body: { ids, provider } }, createObjectDecoder("account token refresh batch", { succeeded: isNumber, failed: isNumber, skipped: isNumber })); } diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index ed8802e0..38703ba6 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -50,6 +50,8 @@ import { pollDeviceAuthorization, refreshAccountBilling, refreshAccountsQuota, + resetAccountsQuota, + resetAllAccountQuota, refreshAccountsTokens, refreshAccountToken, refreshAccountQuota, @@ -93,6 +95,7 @@ type BuildConversionProgressState = { }; type WebConversionTarget = "build" | "console"; +type BuildQuotaTask = "sync" | "reset"; type AccountSelection = { provider: AccountProvider; @@ -125,12 +128,15 @@ export function AccountsPage() { const [sort, setSort] = useState({ field: "createdAt", order: "desc" }); const [selection, setSelection] = useState(() => ({ provider: "grok_build", ids: new Set() })); const [batchDeleteOpen, setBatchDeleteOpen] = useState(false); + const [batchQuotaTaskOpen, setBatchQuotaTaskOpen] = useState(false); + const [batchQuotaTask, setBatchQuotaTask] = useState("sync"); const [egressBindingOpen, setEgressBindingOpen] = useState(false); const [egressNodeID, setEgressNodeID] = useState(""); const [cleanupOpen, setCleanupOpen] = useState(false); const [cleanupStatuses, setCleanupStatuses] = useState>(() => new Set()); const [exportOpen, setExportOpen] = useState(false); const [syncAllOpen, setSyncAllOpen] = useState(false); + const [allQuotaTask, setAllQuotaTask] = useState("sync"); const [quotaSyncProgress, setQuotaSyncProgress] = useState(null); const [webConversionTargets, setWebConversionTargets] = useState(null); const [webConversionTarget, setWebConversionTarget] = useState("build"); @@ -330,6 +336,16 @@ export function AccountsPage() { onError: (error) => { if (!isAbortError(error)) showError(error); }, onSettled: () => { quotaSyncAbortRef.current = null; setQuotaSyncProgress(null); invalidateAccountData(); }, }); + + const allQuotaResetMutation = useMutation({ + mutationFn: resetAllAccountQuota, + onSuccess: (result) => { + setSyncAllOpen(false); + toast.success(t("accountQuotaReset.completed", result)); + }, + onError: showError, + onSettled: invalidateAccountData, + }); const conversionMutation = useMutation({ mutationFn: (input: BuildConversionInput) => { const controller = new AbortController(); @@ -461,12 +477,24 @@ export function AccountsPage() { mutationFn: () => refreshAccountsQuota([...selected], provider), onSuccess: (result) => { clearSelection(); + setBatchQuotaTaskOpen(false); invalidateAccountData(); toast.success(t("accounts.batchBillingRefreshed", result)); }, onError: showError, }); + const batchQuotaResetMutation = useMutation({ + mutationFn: () => resetAccountsQuota([...selected], provider), + onSuccess: (result) => { + clearSelection(); + setBatchQuotaTaskOpen(false); + invalidateAccountData(); + toast.success(t("accountQuotaReset.completed", result)); + }, + onError: showError, + }); + const batchTokenMutation = useMutation({ mutationFn: () => refreshAccountsTokens([...selected], provider), onSuccess: (result) => { @@ -723,12 +751,14 @@ export function AccountsPage() { const hasProviderAccounts = providerAccountTotal > 0 || (result?.total ?? 0) > 0; const bindableEgressNodes = (egressNodesQuery.data?.items ?? []).filter((node) => node.enabled && node.proxyConfigured && scopeSupportsAccountProvider(node.scope, provider)); const bulkTaskPending = quotaSyncMutation.isPending + || allQuotaResetMutation.isPending || allTokenMutation.isPending || conversionMutation.isPending || webConsoleSyncMutation.isPending || importMutation.isPending || batchUpdateMutation.isPending || batchBillingMutation.isPending + || batchQuotaResetMutation.isPending || batchTokenMutation.isPending || batchDeleteMutation.isPending || bindEgressMutation.isPending @@ -875,7 +905,14 @@ export function AccountsPage() { {provider === "grok_web" ? : null} {provider === "grok_web" ? : null} - + {provider === "grok_build" ? : null} @@ -883,7 +920,7 @@ export function AccountsPage() {
{provider === "grok_web" && hasProviderAccounts ? : null} {provider === "grok_web" && hasProviderAccounts ? : null} - {hasProviderAccounts ? : null} + {hasProviderAccounts ? : null} {hasProviderAccounts && provider === "grok_build" ? : null} {hasProviderAccounts ? : null}
@@ -990,10 +1027,37 @@ export function AccountsPage() { /> ) : null} - { if (!open) quotaSyncAbortRef.current?.abort(); setSyncAllOpen(open); }}> + { + if (quotaSyncMutation.isPending || allQuotaResetMutation.isPending) return; + if (!open) quotaSyncAbortRef.current?.abort(); + setSyncAllOpen(open); + }}> - {t("accounts.syncAllTitle")}{t(provider === "grok_web" ? "accounts.syncAllWebDescription" : provider === "grok_console" ? "console.syncAllDescription" : "accounts.syncAllDescription")} - {t("common.cancel")} { event.preventDefault(); quotaSyncMutation.mutate(provider); }}>{quotaSyncMutation.isPending ? <>{quotaSyncProgress ? {quotaSyncProgress.completed} / {quotaSyncProgress.total} : t("common.loading")} : t("accounts.syncAll")} + + {t(provider === "grok_build" ? "accountQuotaTask.allTitle" : "accounts.syncAllTitle")} + {t(provider === "grok_build" ? "accountQuotaTask.allDescription" : provider === "grok_web" ? "accounts.syncAllWebDescription" : "console.syncAllDescription")} + + {provider === "grok_build" ? ( +
+ setAllQuotaTask(value as BuildQuotaTask)}> + + {t("accounts.refreshBilling")} + {t("accountQuotaReset.action")} + + +

{t(allQuotaTask === "sync" ? "accounts.syncAllDescription" : "accountQuotaTask.resetAllDescription")}

+
+ ) : null} + + {t("common.cancel")} + { + event.preventDefault(); + if (provider === "grok_build" && allQuotaTask === "reset") allQuotaResetMutation.mutate(); + else quotaSyncMutation.mutate(provider); + }}> + {quotaSyncMutation.isPending ? <>{quotaSyncProgress ? {quotaSyncProgress.completed} / {quotaSyncProgress.total} : t("common.loading")} : allQuotaResetMutation.isPending ? : t(provider === "grok_build" ? "accountQuotaTask.execute" : "accounts.syncAll")} + +
@@ -1207,6 +1271,38 @@ export function AccountsPage() {
+ { + if (batchBillingMutation.isPending || batchQuotaResetMutation.isPending) return; + setBatchQuotaTaskOpen(open); + }}> + + + {t("accountQuotaTask.title", { count: selected.size })} + {t("accountQuotaTask.description")} + +
+ setBatchQuotaTask(value as BuildQuotaTask)}> + + {t("accounts.refreshBilling")} + {t("accountQuotaReset.action")} + + +

{t(batchQuotaTask === "sync" ? "accountQuotaTask.syncDescription" : "accountQuotaReset.description")}

+
+ + {t("common.cancel")} + { + event.preventDefault(); + if (batchQuotaTask === "reset") batchQuotaResetMutation.mutate(); + else batchBillingMutation.mutate(); + }}> + {batchBillingMutation.isPending || batchQuotaResetMutation.isPending ? : null} + {t("accountQuotaTask.execute")} + + +
+
+ { if (bindEgressMutation.isPending) return; setEgressBindingOpen(open); diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 4db097bc..9ae2a6ae 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -577,6 +577,20 @@ const resources = { cleanupCompleted: "已删除 {{deleted}} 个账号", cleanupStart: "开始清理", }, + accountQuotaReset: { + action: "重置额度", + description: "仅清除本地待重置和模型额度阻断,不会修改上游 Billing 或审计记录。若账号仍已耗尽,真实请求会再次将其标记为待重置。", + completed: "已重置 {{reset}} 个账号的本地额度状态", + }, + accountQuotaTask: { + title: "处理所选 {{count}} 个账号的额度", + description: "选择要对所选 Grok Build 账号执行的额度任务。", + allTitle: "处理全部账号的额度", + allDescription: "选择要对全部已启用 Grok Build 账号执行的额度任务。", + syncDescription: "请求上游 Billing 并更新本地额度快照、账号类型和恢复状态。", + resetAllDescription: "清除全部已启用 Grok Build 账号的本地待重置和额度耗尽阻断;不会修改上游 Billing 或审计记录。", + execute: "执行任务", + }, quotaProducts: { thirdParty: "第三方", api: "API", @@ -982,6 +996,8 @@ const resources = { auditListFailed: "获取请求审计记录失败", authImportFailed: "导入授权文件失败", billingBatchRefreshFailed: "批量同步额度失败", + quotaBatchResetFailed: "批量重置额度状态失败", + quotaResetFailed: "重置全部额度状态失败", billingRefreshFailed: "同步额度失败", quotaRefreshFailed: "同步 Grok Web 额度失败", clientKeyBatchDeleteFailed: "批量删除密钥失败", @@ -1211,6 +1227,8 @@ 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" }, + 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" }, 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.", 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. This may affect video generation and other permissions.", 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", 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.", batchUpdated: "Selected accounts updated", 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", cleanupStart: "Start cleanup" }, models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes. 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 custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", 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" }, @@ -1472,6 +1490,8 @@ const resources = { adminUnauthorized: "Your admin session has expired. Sign in again.", auditListFailed: "Failed to load request audits", authImportFailed: "Failed to import the authorization file", + quotaBatchResetFailed: "Failed to reset quota state in batch", + quotaResetFailed: "Failed to reset quota state for all accounts", billingBatchRefreshFailed: "Failed to sync quotas in batch", billingRefreshFailed: "Failed to sync the quota", quotaRefreshFailed: "Failed to sync the Grok Web quota",