diff --git a/backend/internal/application/account/batch_update_test.go b/backend/internal/application/account/batch_update_test.go new file mode 100644 index 00000000..e1e16289 --- /dev/null +++ b/backend/internal/application/account/batch_update_test.go @@ -0,0 +1,79 @@ +package account + +import ( + "context" + "errors" + "slices" + "testing" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +type batchUpdateRepository struct { + repository.AccountRepository + updateErr error + updatedIDs []uint64 +} + +func (r *batchUpdateRepository) UpdateMany(_ context.Context, providerValue accountdomain.Provider, ids []uint64, _ repository.AccountUpdates) (int64, error) { + if providerValue != accountdomain.ProviderBuild { + return 0, errors.New("unexpected provider") + } + r.updatedIDs = append([]uint64(nil), ids...) + if r.updateErr != nil { + return 0, r.updateErr + } + return int64(len(ids)), nil +} + +func TestBatchUpdateSupportsMoreThanAdminPageLimit(t *testing.T) { + ids := make([]uint64, 2501) + for index := range ids { + ids[index] = uint64(index + 1) + } + repo := &batchUpdateRepository{} + service := NewService(repo, nil, nil, nil, nil, nil, nil) + maxConcurrent := 3 + + updated, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent}) + if err != nil { + t.Fatal(err) + } + if updated != int64(len(ids)) || !slices.Equal(repo.updatedIDs, ids) { + t.Fatalf("updated = %d, ids = %d", updated, len(repo.updatedIDs)) + } +} + +func TestBatchUpdatePreservesProviderMismatchSemantics(t *testing.T) { + ids := make([]uint64, 501) + for index := range ids { + ids[index] = uint64(index + 1) + } + repo := &batchUpdateRepository{updateErr: repository.ErrAccountPoolMismatch} + service := NewService(repo, nil, nil, nil, nil, nil, nil) + maxConcurrent := 3 + + _, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent}) + if !errors.Is(err, ErrAccountPoolMismatch) { + t.Fatalf("error = %v, want account pool mismatch", err) + } +} + +func TestBatchUpdateRetainsBoundedRequestSize(t *testing.T) { + ids := make([]uint64, maxBatchUpdateAccounts+1) + for index := range ids { + ids[index] = uint64(index + 1) + } + repo := &batchUpdateRepository{} + service := NewService(repo, nil, nil, nil, nil, nil, nil) + maxConcurrent := 3 + + _, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent}) + if !errors.Is(err, ErrInvalidInput) { + t.Fatalf("error = %v, want invalid input", err) + } + if len(repo.updatedIDs) != 0 { + t.Fatal("oversized update reached repository") + } +} diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 9c77f343..ac32b117 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "slices" "strconv" "strings" "sync" @@ -22,18 +23,19 @@ import ( ) var ( - ErrDevicePending = errors.New("Device OAuth 等待用户授权") - ErrDeviceSlowDown = errors.New("Device OAuth 轮询过快") - ErrDeviceDenied = errors.New("Device OAuth 已拒绝或过期") - ErrInvalidFilter = errors.New("账号筛选条件无效") - ErrInvalidInput = errors.New("账号参数无效") - ErrInvalidImport = errors.New("账号凭据格式无效") - ErrImportLimit = errors.New("导入账号数量超过限制") - ErrExportLimit = errors.New("导出账号数量超过限制") - ErrNotFound = errors.New("账号不存在") - ErrUnsupported = errors.New("账号来源不支持该操作") - ErrConversionBusy = errors.New("账号正在转换为 Grok Build") - ErrConflict = errors.New("账号操作存在冲突") + ErrDevicePending = errors.New("Device OAuth 等待用户授权") + ErrDeviceSlowDown = errors.New("Device OAuth 轮询过快") + ErrDeviceDenied = errors.New("Device OAuth 已拒绝或过期") + ErrInvalidFilter = errors.New("账号筛选条件无效") + ErrInvalidInput = errors.New("账号参数无效") + ErrInvalidImport = errors.New("账号凭据格式无效") + ErrImportLimit = errors.New("导入账号数量超过限制") + ErrExportLimit = errors.New("导出账号数量超过限制") + ErrNotFound = errors.New("账号不存在") + ErrUnsupported = errors.New("账号来源不支持该操作") + ErrConversionBusy = errors.New("账号正在转换为 Grok Build") + ErrConflict = errors.New("账号操作存在冲突") + ErrAccountPoolMismatch = errors.New("批量操作包含不属于当前号池的账号") ) var ErrCredentialRefreshPermanent = errors.New("OAuth refresh token 已永久失效") @@ -63,6 +65,7 @@ const ( credentialImportChunkSize = 100 maxQuotaResetAccounts = 10000 quotaResetChunkSize = 500 + maxBatchUpdateAccounts = 10000 maxBuildConversionAccounts = 1000 maxWebConsoleSyncAccounts = 1000 accountTaskBatchSize = 1000 @@ -561,12 +564,16 @@ func validAssociationFilter(providerValue, association string) bool { } } -// BatchUpdate 对一组账号应用同一组路由参数,单次最多处理一个管理端最大分页。 -func (s *Service) BatchUpdate(ctx context.Context, ids []uint64, input UpdateInput) (int64, error) { - ids, err := normalizeBatchIDs(ids) +// BatchUpdate 对同一号池的一组账号应用相同路由参数。 +func (s *Service) BatchUpdate(ctx context.Context, providerValue accountdomain.Provider, ids []uint64, input UpdateInput) (int64, error) { + ids, err := normalizeIDs(ids, maxBatchUpdateAccounts) if err != nil { return 0, err } + if !providerValue.IsValid() { + return 0, invalidInput("账号来源无效") + } + slices.Sort(ids) if input.MaxConcurrent != nil && (*input.MaxConcurrent < 1 || *input.MaxConcurrent > accountdomain.MaxConcurrent) { return 0, invalidInput("maxConcurrent 必须在 1 到 256 之间") } @@ -576,13 +583,17 @@ func (s *Service) BatchUpdate(ctx context.Context, ids []uint64, input UpdateInp if input.Name != nil { return 0, invalidInput("批量更新不支持修改账号名称") } - updated, err := s.accounts.UpdateMany(ctx, ids, repository.AccountUpdates{Enabled: input.Enabled, Priority: input.Priority, MaxConcurrent: input.MaxConcurrent, MinimumRemaining: input.MinimumRemaining}) + updated, err := s.accounts.UpdateMany(ctx, providerValue, ids, repository.AccountUpdates{Enabled: input.Enabled, Priority: input.Priority, MaxConcurrent: input.MaxConcurrent, MinimumRemaining: input.MinimumRemaining}) if err != nil { - return 0, err + return 0, mapRepositoryError(err) } - if input.Enabled != nil && !*input.Enabled { - for _, id := range ids { - _ = s.sticky.DeleteByAccount(ctx, id) + if input.Enabled != nil && !*input.Enabled && s.sticky != nil { + if batchDeleter, ok := s.sticky.(repository.StickySessionBatchDeleter); ok { + _ = batchDeleter.DeleteByAccounts(ctx, ids) + } else { + for _, id := range ids { + _ = s.sticky.DeleteByAccount(ctx, id) + } } } return updated, nil @@ -3277,6 +3288,9 @@ func mapLinkedDeleteError(err error) error { } func mapRepositoryError(err error) error { + if errors.Is(err, repository.ErrAccountPoolMismatch) { + return ErrAccountPoolMismatch + } if errors.Is(err, repository.ErrNotFound) { return ErrNotFound } diff --git a/backend/internal/infra/persistence/relational/account_batch_update_test.go b/backend/internal/infra/persistence/relational/account_batch_update_test.go new file mode 100644 index 00000000..9c8fe4e4 --- /dev/null +++ b/backend/internal/infra/persistence/relational/account_batch_update_test.go @@ -0,0 +1,112 @@ +package relational + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestAccountRepositoryUpdateManyChunksLargeAccountPool(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewAccountRepository(database) + rows := seedBatchUpdateAccounts(t, database, 2001) + ids := accountModelIDs(rows) + maxConcurrent := 3 + + updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if err != nil { + t.Fatal(err) + } + if updated != int64(len(ids)) { + t.Fatalf("updated = %d, want %d", updated, len(ids)) + } + var count int64 + if err := database.db.Model(&accountModel{}).Where("max_concurrent = ?", maxConcurrent).Count(&count).Error; err != nil { + t.Fatal(err) + } + if count != int64(len(ids)) { + t.Fatalf("stored count = %d, want %d", count, len(ids)) + } +} + +func TestAccountRepositoryUpdateManyRollsBackAllChunks(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewAccountRepository(database) + rows := seedBatchUpdateAccounts(t, database, accountUpdateBatchSize+1) + ids := accountModelIDs(rows) + failingID := ids[len(ids)-1] + trigger := fmt.Sprintf(`CREATE TRIGGER fail_batch_account_update BEFORE UPDATE OF max_concurrent ON provider_accounts WHEN NEW.id = %d BEGIN SELECT RAISE(ABORT, 'forced batch failure'); END`, failingID) + if err := database.db.Exec(trigger).Error; err != nil { + t.Fatal(err) + } + maxConcurrent := 3 + + updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if err == nil || updated != 0 { + t.Fatalf("updated = %d, error = %v", updated, err) + } + var changed int64 + if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&changed).Error; err != nil { + t.Fatal(err) + } + if changed != 0 { + t.Fatalf("transaction left %d changed rows", changed) + } +} + +func TestAccountRepositoryUpdateManyRejectsMixedProviderBeforeWriting(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewAccountRepository(database) + rows := seedBatchUpdateAccounts(t, database, accountUpdateBatchSize+1) + ids := accountModelIDs(rows) + if err := database.db.Model(&accountModel{}).Where("id = ?", ids[len(ids)-1]).Update("provider", account.ProviderWeb).Error; err != nil { + t.Fatal(err) + } + maxConcurrent := 3 + + updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if !errors.Is(err, repository.ErrAccountPoolMismatch) || updated != 0 { + t.Fatalf("updated = %d, error = %v", updated, err) + } + var changed int64 + if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&changed).Error; err != nil { + t.Fatal(err) + } + if changed != 0 { + t.Fatalf("provider mismatch left %d changed rows", changed) + } +} + +func seedBatchUpdateAccounts(t *testing.T, database *Database, count int) []accountModel { + t.Helper() + now := time.Now().UTC() + rows := make([]accountModel, count) + for index := range rows { + rows[index] = accountModel{ + IdentityKey: fmt.Sprintf("%064x", index+1), + Provider: string(account.ProviderBuild), Name: fmt.Sprintf("batch-%d", index+1), SourceKey: fmt.Sprintf("batch-%d", index+1), + Enabled: true, AuthStatus: string(account.AuthStatusActive), Priority: account.DefaultPriority, MaxConcurrent: account.DefaultMaxConcurrent, + BuildRouteMode: string(account.BuildRouteAuto), CreatedAt: now, UpdatedAt: now, + } + } + if err := database.db.CreateInBatches(&rows, 200).Error; err != nil { + t.Fatal(err) + } + return rows +} + +func accountModelIDs(rows []accountModel) []uint64 { + ids := make([]uint64, len(rows)) + for index := range rows { + ids[index] = rows[index].ID + } + return ids +} diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index 8454da74..7684b0b8 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -38,6 +38,7 @@ type quotaBreakdownJSON struct { } const ( + accountUpdateBatchSize = 500 accountPaidPlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey'))` accountFreePlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic'))` accountPaidBillingSignals = `(` + accountPaidPlanSignal + ` OR billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0)` @@ -1255,7 +1256,7 @@ func (r *AccountRepository) markWebProfileTimestamp(ctx context.Context, id uint })) } -func (r *AccountRepository) UpdateMany(ctx context.Context, ids []uint64, updates repository.AccountUpdates) (int64, error) { +func (r *AccountRepository) UpdateMany(ctx context.Context, providerValue account.Provider, ids []uint64, updates repository.AccountUpdates) (int64, error) { if len(ids) == 0 { return 0, nil } @@ -1275,11 +1276,40 @@ func (r *AccountRepository) UpdateMany(ctx context.Context, ids []uint64, update if len(values) == 0 { return 0, nil } - result := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id IN ?", ids).Updates(values) - if result.Error == nil && result.RowsAffected > 0 { + var updated int64 + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + for start := 0; start < len(ids); start += accountUpdateBatchSize { + end := min(start+accountUpdateBatchSize, len(ids)) + var rows []accountModel + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id", "provider").Where("id IN ?", ids[start:end]).Order("id ASC").Find(&rows).Error; err != nil { + return err + } + if len(rows) != end-start { + return repository.ErrAccountPoolMismatch + } + for _, row := range rows { + if account.Provider(row.Provider) != providerValue { + return repository.ErrAccountPoolMismatch + } + } + } + for start := 0; start < len(ids); start += accountUpdateBatchSize { + end := min(start+accountUpdateBatchSize, len(ids)) + result := tx.Model(&accountModel{}).Where("provider = ? AND id IN ?", providerValue, ids[start:end]).Updates(values) + if result.Error != nil { + return result.Error + } + updated += result.RowsAffected + } + return nil + }) + if err != nil { + return 0, err + } + if updated > 0 { r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountStateChanged}) } - return result.RowsAffected, result.Error + return updated, nil } // UpdateEgressBindings assigns one egress node to multiple accounts of one diff --git a/backend/internal/infra/persistence/relational/postgres_account_batch_update_test.go b/backend/internal/infra/persistence/relational/postgres_account_batch_update_test.go new file mode 100644 index 00000000..37af7c1b --- /dev/null +++ b/backend/internal/infra/persistence/relational/postgres_account_batch_update_test.go @@ -0,0 +1,44 @@ +package relational + +import ( + "context" + "os" + "testing" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestPostgresAccountBatchUpdateBeyondAdminPageLimit(t *testing.T) { + dsn := os.Getenv("TEST_POSTGRES_DSN") + if dsn == "" { + t.Skip("TEST_POSTGRES_DSN is not configured") + } + ctx := context.Background() + database, err := OpenPostgres(ctx, dsn, 5, 2) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + rows := seedBatchUpdateAccounts(t, database, 2001) + ids := accountModelIDs(rows) + maxConcurrent := 3 + + updated, err := NewAccountRepository(database).UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent}) + if err != nil { + t.Fatal(err) + } + if updated != int64(len(ids)) { + t.Fatalf("updated = %d, want %d", updated, len(ids)) + } + var count int64 + if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&count).Error; err != nil { + t.Fatal(err) + } + if count != int64(len(ids)) { + t.Fatalf("stored count = %d, want %d", count, len(ids)) + } +} diff --git a/backend/internal/infra/persistence/relational/postgres_integration_test.go b/backend/internal/infra/persistence/relational/postgres_integration_test.go index bdf48f0d..a41334c5 100644 --- a/backend/internal/infra/persistence/relational/postgres_integration_test.go +++ b/backend/internal/infra/persistence/relational/postgres_integration_test.go @@ -959,7 +959,7 @@ func TestPostgresRoutingProjectionAndCredentialHydration(t *testing.T) { t.Fatalf("cross-provider credential error = %v, want ErrNotFound", err) } disabled := false - if _, err := accounts.UpdateMany(ctx, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { + if _, err := accounts.UpdateMany(ctx, account.ProviderBuild, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { t.Fatal(err) } if _, err := accounts.GetCredentialMaterial(ctx, created.ID, account.ProviderWeb); !errors.Is(err, repository.ErrNotFound) { diff --git a/backend/internal/infra/persistence/relational/routing_projection_test.go b/backend/internal/infra/persistence/relational/routing_projection_test.go index c317fcdc..3d90cdd7 100644 --- a/backend/internal/infra/persistence/relational/routing_projection_test.go +++ b/backend/internal/infra/persistence/relational/routing_projection_test.go @@ -146,7 +146,7 @@ func TestGetCredentialMaterialHydratesOneAccountAndMapsNotFound(t *testing.T) { t.Fatalf("cross-provider credential material error = %v, want ErrNotFound", err) } disabled := false - if _, err := accounts.UpdateMany(ctx, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { + if _, err := accounts.UpdateMany(ctx, account.ProviderBuild, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil { t.Fatal(err) } if _, err := accounts.GetCredentialMaterial(ctx, created.ID, account.ProviderBuild); !errors.Is(err, repository.ErrNotFound) { diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index a71e58da..541de173 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -87,7 +87,7 @@ type AccountRepository interface { GetQuotaRecoveries(ctx context.Context, accountIDs []uint64) (map[uint64]account.QuotaRecovery, error) UpsertByIdentity(ctx context.Context, value account.Credential) (account.Credential, bool, error) Update(ctx context.Context, value account.Credential) (account.Credential, error) - UpdateMany(ctx context.Context, ids []uint64, updates AccountUpdates) (int64, error) + UpdateMany(ctx context.Context, provider account.Provider, ids []uint64, updates AccountUpdates) (int64, error) Delete(ctx context.Context, id uint64) error DeleteMany(ctx context.Context, ids []uint64) (int64, error) // ResolveLinkedDeleteIDs expands root account IDs with one-hop (or Build/Console two-hop via Web) diff --git a/backend/internal/repository/errors.go b/backend/internal/repository/errors.go index 42fcb1ef..b59de8fe 100644 --- a/backend/internal/repository/errors.go +++ b/backend/internal/repository/errors.go @@ -6,10 +6,11 @@ import ( ) var ( - ErrNotFound = errors.New("repository: not found") - ErrConflict = errors.New("repository: conflict") - ErrLimitExceeded = errors.New("repository: limit exceeded") - ErrInvalidRecord = errors.New("repository: invalid record") + ErrNotFound = errors.New("repository: not found") + ErrConflict = errors.New("repository: conflict") + ErrLimitExceeded = errors.New("repository: limit exceeded") + ErrInvalidRecord = errors.New("repository: invalid record") + ErrAccountPoolMismatch = errors.New("repository: account pool mismatch") ) // InvalidBatchRecordError identifies a deterministic invalid record without diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go index efaca4ee..aa16ebe8 100644 --- a/backend/internal/transport/http/account/handler.go +++ b/backend/internal/transport/http/account/handler.go @@ -438,10 +438,7 @@ func (h *Handler) batchUpdate(c *gin.Context) { response.Error(c, http.StatusBadRequest, "invalidId", err.Error()) return } - if !h.validateProviderIDs(c, ids, request.Provider) { - return - } - updated, err := h.service.BatchUpdate(c.Request.Context(), ids, accountapp.UpdateInput{Enabled: request.Enabled, Priority: request.Priority, MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining}) + updated, err := h.service.BatchUpdate(c.Request.Context(), accountdomain.Provider(request.Provider), ids, accountapp.UpdateInput{Enabled: request.Enabled, Priority: request.Priority, MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining}) if err != nil { h.writeServiceError(c, "accountBatchUpdateFailed", err, http.StatusInternalServerError, "批量更新账号失败") return @@ -1284,6 +1281,8 @@ func (h *Handler) writeServiceError(c *gin.Context, code string, err error, fall response.Error(c, http.StatusBadRequest, "accountExportLimitExceeded", err.Error()) case errors.Is(err, accountapp.ErrInvalidInput), errors.Is(err, accountapp.ErrInvalidImport): response.Error(c, http.StatusBadRequest, code, err.Error()) + case errors.Is(err, accountapp.ErrAccountPoolMismatch): + response.Error(c, http.StatusConflict, "accountPoolMismatch", err.Error()) case errors.Is(err, accountapp.ErrConflict): response.Error(c, http.StatusConflict, code, err.Error()) case errors.Is(err, accountapp.ErrNotFound): diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts index ba5493cf..71531404 100644 --- a/frontend/src/features/accounts/accounts-api.ts +++ b/frontend/src/features/accounts/accounts-api.ts @@ -541,6 +541,10 @@ export function updateAccountsEnabled(ids: string[], enabled: boolean, provider: return apiRequest("/api/admin/v1/accounts/batch", { method: "PATCH", body: { ids, enabled, provider } }, decodeCountResult<{ updated: number }>("updated")); } +export function updateAccountsMaxConcurrent(ids: string[], maxConcurrent: number, provider: AccountProvider): Promise<{ updated: number }> { + return apiRequest("/api/admin/v1/accounts/batch", { method: "PATCH", body: { ids, maxConcurrent, provider } }, decodeCountResult<{ updated: number }>("updated")); +} + export function refreshAccountsQuota(ids: string[], provider: AccountProvider): Promise<{ succeeded: number; failed: number }> { return apiRequest("/api/admin/v1/accounts/batch/refresh-quotas", { method: "POST", body: { ids, provider } }, createObjectDecoder("account batch", { succeeded: isNumber, failed: isNumber })); } diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index 49c49c1b..d6274127 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -68,6 +68,7 @@ import { syncWebAccountsToConsole, updateAccount, updateAccountsEnabled, + updateAccountsMaxConcurrent, type AccountDTO, type AccountCleanupStatus, type AccountProvider, @@ -133,6 +134,8 @@ 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 [batchConcurrencyOpen, setBatchConcurrencyOpen] = useState(false); + const [batchMaxConcurrent, setBatchMaxConcurrent] = useState("1"); const [batchQuotaTaskOpen, setBatchQuotaTaskOpen] = useState(false); const [batchQuotaTask, setBatchQuotaTask] = useState("sync"); const [egressConfigurationOpen, setEgressConfigurationOpen] = useState(false); @@ -645,6 +648,17 @@ export function AccountsPage() { onError: showError, }); + const batchConcurrencyMutation = useMutation({ + mutationFn: (maxConcurrent: number) => updateAccountsMaxConcurrent([...selected], maxConcurrent, provider), + onSuccess: () => { + setBatchConcurrencyOpen(false); + clearSelection(); + invalidateAccountData(); + toast.success(t("accounts.batchConcurrencyUpdated")); + }, + onError: showError, + }); + const batchBillingMutation = useMutation({ mutationFn: () => refreshAccountsQuota([...selected], provider), onSuccess: (result) => { @@ -1024,6 +1038,7 @@ export function AccountsPage() { || webConsoleSyncMutation.isPending || importMutation.isPending || batchUpdateMutation.isPending + || batchConcurrencyMutation.isPending || batchBillingMutation.isPending || batchQuotaResetMutation.isPending || batchTokenMutation.isPending @@ -1172,6 +1187,10 @@ export function AccountsPage() { + + + + + + { if (!open && batchDeleteMutation.isPending) return; setBatchDeleteOpen(open); diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 448cf1e7..77a61712 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -589,6 +589,10 @@ const resources = { linkedDeleteHint: "仅删除已关联的账号;未关联账号保持不变。", linkedDeletePreviewFailed: "关联数量加载失败,请取消勾选后重试,或稍后再删。", batchUpdated: "所选账号已更新", + batchSetConcurrency: "设置并发", + batchConcurrencyTitle: "设置所选 {{count}} 个账号的并发?", + batchConcurrencyDescription: "同一账号同时处理的请求数,允许范围为 1–256。大号池可从 1 开始,降低单账号并发压力。", + batchConcurrencyUpdated: "所选账号并发已更新", batchBillingRefreshed: "额度同步完成:成功 {{succeeded}},失败 {{failed}}", batchDeleteTitle: "删除所选 {{count}} 个账号?", cleanupAction: "账号清理", @@ -1295,7 +1299,7 @@ const resources = { accountQuotaTask: { title: "Process quota for {{count}} selected accounts", description: "Choose the quota task to run for the selected Grok Build accounts.", allTitle: "Process quota for all accounts", allDescription: "Choose the quota task to run for all enabled Grok Build accounts.", syncDescription: "Request upstream Billing and update local quota snapshots, account tiers, and recovery state.", resetAllDescription: "Clear local waiting-reset and exhausted-quota blocks for all enabled Grok Build accounts without changing upstream Billing or audit history.", execute: "Run task" }, accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" }, dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, - accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control. 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", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, + accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control. 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", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, models: { title: "Model routes", description: "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" }, keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning supports low / medium / high; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, audits: {