From 2db3f651b78e19cc49e7529bb84d7f81993d45de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B0=95=E6=B0=99?= Date: Tue, 14 Jul 2026 18:09:49 +0800 Subject: [PATCH] feat: improve account batch workflows and admin preferences --- backend/internal/app/application.go | 2 + .../application/account/batch_quota_test.go | 93 ++++++ .../application/account/conversion_test.go | 143 ++++++++- .../internal/application/account/service.go | 288 +++++++++++++++--- .../account/web_console_sync_test.go | 114 ++++++- .../internal/application/settings/service.go | 23 +- .../application/settings/service_test.go | 34 ++- backend/internal/domain/settings/settings.go | 3 +- backend/internal/infra/config/config.go | 9 +- backend/internal/infra/config/config_test.go | 3 +- .../relational/account_repository.go | 141 ++++++++- .../infra/persistence/relational/models.go | 4 +- .../persistence/relational/repository_test.go | 50 ++- backend/internal/repository/account.go | 12 +- .../transport/http/account/handler.go | 75 +++-- .../transport/http/account/handler_test.go | 14 + .../transport/http/settings/handler.go | 7 +- .../src/features/accounts/accounts-api.ts | 22 +- .../src/features/accounts/accounts-page.tsx | 61 +++- .../src/features/dashboard/dashboard-page.tsx | 43 ++- .../src/features/settings/settings-api.ts | 4 +- .../src/features/settings/settings-model.ts | 1 + .../src/features/settings/settings-page.tsx | 1 + frontend/src/shared/i18n/index.ts | 71 ++++- 24 files changed, 1082 insertions(+), 136 deletions(-) create mode 100644 backend/internal/application/account/batch_quota_test.go diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index cc1b010a..eee7b8d8 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -188,6 +188,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat accountService.SetLogger(logger) accountService.SetQuotaRecoveryQueue(quotaQueue) accountService.SetTaskPools(conversionPool, syncPool, refreshPool) + accountService.UpdateAccountTaskBatchSize(cfg.Batch.AccountTaskBatchSize) windows, err := accountRepo.ListQuotaRecoveryWindows(ctx, 100000) if err != nil { if runtimeStore != nil { @@ -253,6 +254,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat conversionPool.UpdateLimit(next.Batch.ConversionConcurrency) syncPool.UpdateLimit(next.Batch.SyncConcurrency) refreshPool.UpdateLimit(next.Batch.RefreshConcurrency) + accountService.UpdateAccountTaskBatchSize(next.Batch.AccountTaskBatchSize) for _, pool := range []*batch.Pool{importPool, conversionPool, syncPool, refreshPool} { pool.UpdateJitter(next.Batch.RandomDelay.Value()) } diff --git a/backend/internal/application/account/batch_quota_test.go b/backend/internal/application/account/batch_quota_test.go new file mode 100644 index 00000000..75b03f87 --- /dev/null +++ b/backend/internal/application/account/batch_quota_test.go @@ -0,0 +1,93 @@ +package account + +import ( + "context" + "encoding/base64" + "fmt" + "path/filepath" + "sync/atomic" + "testing" + "time" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" + "github.com/chenyme/grok2api/backend/internal/infra/security" +) + +func TestBatchRefreshQuotaSupportsWebAndConsole(t *testing.T) { + for _, providerValue := range []accountdomain.Provider{accountdomain.ProviderWeb, accountdomain.ProviderConsole} { + t.Run(string(providerValue), func(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quota.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encryptedToken, err := cipher.Encrypt("test-token") + if err != nil { + t.Fatal(err) + } + repository := relational.NewAccountRepository(database) + ids := make([]uint64, 0, 2) + for index := 1; index <= 2; index++ { + value, _, createErr := repository.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: providerValue, AuthType: accountdomain.AuthTypeSSO, + Name: fmt.Sprintf("account-%d", index), SourceKey: fmt.Sprintf("source-%d", index), + EncryptedAccessToken: encryptedToken, Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if createErr != nil { + t.Fatal(createErr) + } + ids = append(ids, value.ID) + } + adapter := &selectedQuotaAdapter{providerValue: providerValue} + service := NewService(repository, nil, nil, nil, provider.NewRegistry(adapter), cipher, memory.NewLockStore()) + + succeeded, failed, err := service.BatchRefreshQuota(ctx, ids) + if err != nil { + t.Fatal(err) + } + if succeeded != 2 || failed != 0 || adapter.calls.Load() != 2 { + t.Fatalf("succeeded=%d failed=%d calls=%d", succeeded, failed, adapter.calls.Load()) + } + windows, err := repository.GetQuotaWindows(ctx, ids) + if err != nil { + t.Fatal(err) + } + for _, id := range ids { + if len(windows[id]) != 1 || windows[id][0].Remaining != 7 { + t.Fatalf("account %d windows = %#v", id, windows[id]) + } + } + }) + } +} + +type selectedQuotaAdapter struct { + providerValue accountdomain.Provider + calls atomic.Int64 +} + +func (a *selectedQuotaAdapter) Provider() accountdomain.Provider { return a.providerValue } + +func (a *selectedQuotaAdapter) SyncQuota(_ context.Context, _ accountdomain.Credential) (provider.QuotaSnapshot, error) { + a.calls.Add(1) + now := time.Now().UTC() + return provider.QuotaSnapshot{ + Tier: accountdomain.WebTierSuper, SyncedAt: now, + Windows: []accountdomain.QuotaWindow{{Mode: "default", Remaining: 7, Total: 10, SyncedAt: &now, UpdatedAt: now}}, + }, nil +} + +func (a *selectedQuotaAdapter) SyncQuotaMode(_ context.Context, _ accountdomain.Credential, mode string) (accountdomain.QuotaWindow, error) { + return accountdomain.QuotaWindow{Mode: mode}, nil +} diff --git a/backend/internal/application/account/conversion_test.go b/backend/internal/application/account/conversion_test.go index f8fc8e98..5dd05f6c 100644 --- a/backend/internal/application/account/conversion_test.go +++ b/backend/internal/application/account/conversion_test.go @@ -3,6 +3,7 @@ package account import ( "context" "encoding/base64" + "fmt" "path/filepath" "sync/atomic" "testing" @@ -13,6 +14,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" "github.com/chenyme/grok2api/backend/internal/infra/security" + "github.com/chenyme/grok2api/backend/internal/repository" ) func TestConvertWebAccountsToBuildIsIdempotent(t *testing.T) { @@ -50,13 +52,20 @@ func TestConvertWebAccountsToBuildIsIdempotent(t *testing.T) { if first.Created != 1 || first.Linked != 0 || first.Skipped != 0 || first.Failed != 0 || len(first.BuildAccountIDs) != 1 { t.Fatalf("first conversion = %#v", first) } - second, err := service.ConvertWebAccountsToBuild(ctx, []uint64{webAccount.ID}) + var secondProgress [][2]int + second, err := service.ConvertWebAccountsToBuildWithProgress(ctx, []uint64{webAccount.ID}, nil, func(completed, total int) error { + secondProgress = append(secondProgress, [2]int{completed, total}) + return nil + }) if err != nil { t.Fatal(err) } if second.Created != 0 || second.Linked != 0 || second.Skipped != 1 || second.Failed != 0 || adapter.calls.Load() != 1 { t.Fatalf("second conversion = %#v, calls = %d", second, adapter.calls.Load()) } + if len(secondProgress) != 1 || secondProgress[0] != [2]int{0, 0} { + t.Fatalf("second progress = %#v", secondProgress) + } linkedWeb, err := repository.Get(ctx, webAccount.ID) if err != nil { t.Fatal(err) @@ -66,6 +75,61 @@ func TestConvertWebAccountsToBuildIsIdempotent(t *testing.T) { } } +func TestConvertWebAccountsToBuildAllRefreshesLinkedCredential(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "conversion-refresh.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encryptedSSO, err := cipher.Encrypt("test-sso") + if err != nil { + t.Fatal(err) + } + repository := relational.NewAccountRepository(database) + webAccount, _, err := repository.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO, Name: "web", SourceKey: "web-source", + EncryptedAccessToken: encryptedSSO, Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + adapter := &buildConversionAdapter{} + service := NewService(repository, nil, nil, nil, provider.NewRegistry(adapter), cipher, memory.NewLockStore()) + first, err := service.ConvertWebAccountsToBuild(ctx, []uint64{webAccount.ID}) + if err != nil { + t.Fatal(err) + } + refreshed, err := service.ConvertWebAccountsToBuildWithStrategy(ctx, []uint64{webAccount.ID}, BuildConversionAll, nil, nil) + if err != nil { + t.Fatal(err) + } + if refreshed.Created != 0 || refreshed.Linked != 1 || refreshed.Skipped != 0 || refreshed.Failed != 0 || len(refreshed.BuildAccountIDs) != 1 { + t.Fatalf("refreshed conversion = %#v", refreshed) + } + if refreshed.BuildAccountIDs[0] != first.BuildAccountIDs[0] || adapter.calls.Load() != 2 { + t.Fatalf("build ids first=%v refreshed=%v calls=%d", first.BuildAccountIDs, refreshed.BuildAccountIDs, adapter.calls.Load()) + } + buildAccount, err := repository.Get(ctx, first.BuildAccountIDs[0]) + if err != nil { + t.Fatal(err) + } + accessToken, err := cipher.Decrypt(buildAccount.EncryptedAccessToken) + if err != nil { + t.Fatal(err) + } + if accessToken != "access-2" { + t.Fatalf("access token = %q", accessToken) + } +} + func TestConvertAllWebAccountsToBuildUsesUnlinkedPool(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "conversion-all.db")) @@ -127,16 +191,89 @@ func TestConvertAllWebAccountsToBuildUsesUnlinkedPool(t *testing.T) { if empty.Created != 0 || empty.Linked != 0 || empty.Skipped != 0 || empty.Failed != 0 || len(empty.BuildAccountIDs) != 0 || adapter.calls.Load() != 2 { t.Fatalf("empty conversion = %#v, calls = %d", empty, adapter.calls.Load()) } + resynced, err := service.ConvertAllWebAccountsToBuildWithStrategy(ctx, BuildConversionAll, nil, nil) + if err != nil { + t.Fatal(err) + } + if resynced.Created != 0 || resynced.Linked != 2 || resynced.Skipped != 0 || resynced.Failed != 0 || len(resynced.BuildAccountIDs) != 2 || adapter.calls.Load() != 4 { + t.Fatalf("resynced conversion = %#v, calls = %d", resynced, adapter.calls.Load()) + } } +func TestConvertAllWebAccountsToBuildProcessesMoreThanLegacyLimitInBatches(t *testing.T) { + const totalAccounts = maxBuildConversionAccounts + 1 + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encryptedSSO, err := cipher.Encrypt("test-sso") + if err != nil { + t.Fatal(err) + } + repository := &conversionBatchRepository{total: totalAccounts, encryptedSSO: encryptedSSO} + adapter := &buildConversionAdapter{} + service := NewService(repository, nil, nil, nil, provider.NewRegistry(adapter), cipher, memory.NewLockStore()) + service.UpdateAccountTaskBatchSize(400) + progress := make([][2]int, 0, totalAccounts+1) + result, err := service.ConvertAllWebAccountsToBuildWithProgress(context.Background(), nil, func(completed, total int) error { + progress = append(progress, [2]int{completed, total}) + return nil + }) + if err != nil { + t.Fatal(err) + } + if result.Created != totalAccounts || result.Linked != 0 || result.Skipped != 0 || result.Failed != 0 || len(result.BuildAccountIDs) != totalAccounts { + t.Fatalf("conversion result = %#v", result) + } + if adapter.calls.Load() != totalAccounts || repository.listCalls != 3 { + t.Fatalf("adapter calls = %d, repository batches = %d", adapter.calls.Load(), repository.listCalls) + } + if len(progress) != totalAccounts+1 || progress[0] != [2]int{0, totalAccounts} || progress[len(progress)-1] != [2]int{totalAccounts, totalAccounts} { + t.Fatalf("progress first=%v last=%v count=%d", progress[0], progress[len(progress)-1], len(progress)) + } +} + +type conversionBatchRepository struct { + repository.AccountRepository + total int + encryptedSSO string + listCalls int + nextBuildID atomic.Uint64 +} + +func (r *conversionBatchRepository) ListUnlinkedWebAccountIDs(_ context.Context, afterID uint64, limit int) ([]uint64, int64, error) { + r.listCalls++ + ids := make([]uint64, 0, limit) + for id := afterID + 1; id <= uint64(r.total) && len(ids) < limit; id++ { + ids = append(ids, id) + } + return ids, int64(r.total), nil +} + +func (r *conversionBatchRepository) Get(_ context.Context, id uint64) (accountdomain.Credential, error) { + return accountdomain.Credential{ + ID: id, Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO, + Name: fmt.Sprintf("web-%d", id), SourceKey: fmt.Sprintf("web-source-%d", id), + EncryptedAccessToken: r.encryptedSSO, Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }, nil +} + +func (r *conversionBatchRepository) UpsertByIdentity(_ context.Context, value accountdomain.Credential) (accountdomain.Credential, bool, error) { + value.ID = 10_000 + r.nextBuildID.Add(1) + return value, true, nil +} + +func (r *conversionBatchRepository) LinkWebToBuild(context.Context, uint64, uint64) error { return nil } + type buildConversionAdapter struct{ calls atomic.Int64 } func (a *buildConversionAdapter) Provider() accountdomain.Provider { return accountdomain.ProviderWeb } func (a *buildConversionAdapter) ConvertToBuild(_ context.Context, credential accountdomain.Credential) (provider.CredentialSeed, error) { - a.calls.Add(1) + call := a.calls.Add(1) return provider.CredentialSeed{ Provider: accountdomain.ProviderBuild, AuthType: accountdomain.AuthTypeOAuth, Name: "build", UserID: credential.SourceKey, - SourceKey: "converted", OIDCClientID: "client", AccessToken: "access", RefreshToken: "refresh", ExpiresAt: time.Now().UTC().Add(time.Hour), + SourceKey: fmt.Sprintf("converted:%s:%d", credential.SourceKey, call), OIDCClientID: "client", + AccessToken: fmt.Sprintf("access-%d", call), RefreshToken: fmt.Sprintf("refresh-%d", call), ExpiresAt: time.Now().UTC().Add(time.Hour), }, nil } diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 60e03faf..d04a3878 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" @@ -50,6 +51,8 @@ const ( credentialImportChunkSize = 100 maxBuildConversionAccounts = 1000 maxWebConsoleSyncAccounts = 1000 + defaultAccountTaskBatchSize = 1000 + maxAccountTaskBatchSize = 1000 ) type webQuotaRefreshState struct { @@ -122,9 +125,24 @@ type DeviceStartResult struct { type ImportResult struct { Created int Updated int + Skipped int AccountIDs []uint64 } +type BuildConversionStrategy string + +const ( + BuildConversionAll BuildConversionStrategy = "all" + BuildConversionMissing BuildConversionStrategy = "missing" +) + +type WebConsoleSyncStrategy string + +const ( + WebConsoleSyncAll WebConsoleSyncStrategy = "all" + WebConsoleSyncMissing WebConsoleSyncStrategy = "missing" +) + type ImportedAccountObserver func(accountID uint64) error // BatchProgressObserver 在单个账号任务结束后报告批次完成数。 @@ -222,6 +240,7 @@ type Service struct { conversionPool *batch.Pool syncPool *batch.Pool refreshPool *batch.Pool + accountTaskBatchSize atomic.Int64 credentialRefreshWake chan struct{} logger *slog.Logger now func() time.Time @@ -232,7 +251,7 @@ func (s *Service) SetQuotaRecoveryQueue(queue repository.QuotaRecoveryQueue) { } func NewService(accounts repository.AccountRepository, audits repository.AuditRepository, deviceSessions repository.DeviceSessionRepository, sticky repository.StickySessionRepository, providers *provider.Registry, cipher *security.Cipher, refreshLock repository.DistributedLock) *Service { - return &Service{ + service := &Service{ accounts: accounts, audits: audits, deviceSessions: deviceSessions, sticky: sticky, providers: providers, cipher: cipher, refreshLock: refreshLock, lastRefreshAt: make(map[uint64]time.Time), quotaRefreshes: make(map[string]*webQuotaRefreshState), @@ -241,6 +260,8 @@ func NewService(accounts repository.AccountRepository, audits repository.AuditRe conversionPool: batch.NewPool(25), syncPool: batch.NewPool(25), refreshPool: batch.NewPool(25), logger: slog.Default(), now: func() time.Time { return time.Now().UTC() }, } + service.accountTaskBatchSize.Store(defaultAccountTaskBatchSize) + return service } func (s *Service) SetBulkPool(pool *batch.Pool) { @@ -262,6 +283,23 @@ func (s *Service) SetTaskPools(conversion, syncPool, refresh *batch.Pool) { } } +// UpdateAccountTaskBatchSize 热更新“全部”账号任务每次从仓储获取的账号数量。 +func (s *Service) UpdateAccountTaskBatchSize(value int) { + if value < 1 { + value = defaultAccountTaskBatchSize + } + value = min(value, maxAccountTaskBatchSize) + s.accountTaskBatchSize.Store(int64(value)) +} + +func (s *Service) currentAccountTaskBatchSize() int { + value := s.accountTaskBatchSize.Load() + if value < 1 { + return defaultAccountTaskBatchSize + } + return int(value) +} + func (s *Service) SetLogger(logger *slog.Logger) { if logger != nil { s.logger = logger @@ -731,10 +769,26 @@ func (s *Service) persistImportedSeeds(ctx context.Context, seeds []provider.Cre // SyncWebAccountsToConsoleWithProgress 使用 Web 账号的同一份 SSO 创建或更新 Console 账号。 func (s *Service) SyncWebAccountsToConsoleWithProgress(ctx context.Context, ids []uint64, observer ImportedAccountObserver, progress BatchProgressObserver) (ImportResult, error) { + return s.SyncWebAccountsToConsoleWithStrategy(ctx, ids, WebConsoleSyncAll, observer, progress) +} + +func (s *Service) SyncWebAccountsToConsoleWithStrategy(ctx context.Context, ids []uint64, strategy WebConsoleSyncStrategy, observer ImportedAccountObserver, progress BatchProgressObserver) (ImportResult, error) { + if strategy != WebConsoleSyncAll && strategy != WebConsoleSyncMissing { + return ImportResult{}, invalidInput("Grok Web 到 Console 同步策略无效") + } ids, err := normalizeIDs(ids, maxWebConsoleSyncAccounts) if err != nil { return ImportResult{}, err } + if strategy == WebConsoleSyncMissing { + values, err := s.accounts.ListMissingConsoleSyncAccounts(ctx, ids) + if err != nil { + return ImportResult{}, mapRepositoryError(err) + } + result, err := s.syncWebCredentialsToConsole(ctx, values, observer, progress) + result.Skipped = len(ids) - len(values) + return result, err + } values := make([]accountdomain.Credential, 0, len(ids)) for _, id := range ids { value, getErr := s.accounts.Get(ctx, id) @@ -748,17 +802,60 @@ func (s *Service) SyncWebAccountsToConsoleWithProgress(ctx context.Context, ids // SyncAllWebAccountsToConsoleWithProgress 同步完整 Web 号池,避免前端分页遗漏账号。 func (s *Service) SyncAllWebAccountsToConsoleWithProgress(ctx context.Context, observer ImportedAccountObserver, progress BatchProgressObserver) (ImportResult, error) { - values, total, err := s.accounts.List(ctx, repository.AccountListQuery{ - Page: repository.PageQuery{Limit: maxWebConsoleSyncAccounts + 1}, - Filter: repository.AccountListFilter{Provider: string(accountdomain.ProviderWeb)}, - }) - if err != nil { - return ImportResult{}, err + return s.SyncAllWebAccountsToConsoleWithStrategy(ctx, WebConsoleSyncAll, observer, progress) +} + +func (s *Service) SyncAllWebAccountsToConsoleWithStrategy(ctx context.Context, strategy WebConsoleSyncStrategy, observer ImportedAccountObserver, progress BatchProgressObserver) (ImportResult, error) { + if strategy != WebConsoleSyncAll && strategy != WebConsoleSyncMissing { + return ImportResult{}, invalidInput("Grok Web 到 Console 同步策略无效") } - if total > maxWebConsoleSyncAccounts || len(values) > maxWebConsoleSyncAccounts { - return ImportResult{}, invalidInput("Grok Web 账号超过 1000 个,请分批勾选同步") + batchSize := s.currentAccountTaskBatchSize() + result := ImportResult{AccountIDs: make([]uint64, 0)} + var afterID uint64 + completed := 0 + total := 0 + initialized := false + for { + var ( + values []accountdomain.Credential + count int64 + skipped int64 + err error + ) + if strategy == WebConsoleSyncMissing { + values, count, skipped, err = s.accounts.ListMissingConsoleSyncBatch(ctx, afterID, batchSize) + } else { + values, count, err = s.accounts.ListProviderAccountBatch(ctx, accountdomain.ProviderWeb, afterID, batchSize) + } + if err != nil { + return result, err + } + if !initialized { + total = int(count) + result.Skipped = int(skipped) + initialized = true + if progress != nil { + if err := progress(0, total); err != nil { + return result, err + } + } + } + if len(values) == 0 { + return result, nil + } + current, err := s.syncWebCredentialsToConsole(ctx, values, observer, offsetBatchProgress(progress, completed, total)) + result.Created += current.Created + result.Updated += current.Updated + result.AccountIDs = append(result.AccountIDs, current.AccountIDs...) + if err != nil { + return result, err + } + completed += len(values) + afterID = values[len(values)-1].ID + if len(values) < batchSize { + return result, nil + } } - return s.syncWebCredentialsToConsole(ctx, values, observer, progress) } func (s *Service) syncWebCredentialsToConsole(ctx context.Context, values []accountdomain.Credential, observer ImportedAccountObserver, progress BatchProgressObserver) (ImportResult, error) { @@ -804,52 +901,142 @@ func webConsoleAccountName(webName, fallback string) string { // ConvertWebAccountsToBuild 使用 Web SSO 自动完成 xAI Device Flow,并建立唯一的 Web/Build 账号关联。 func (s *Service) ConvertWebAccountsToBuild(ctx context.Context, ids []uint64) (BuildConversionResult, error) { - return s.ConvertWebAccountsToBuildWithObserver(ctx, ids, nil) + return s.ConvertWebAccountsToBuildWithStrategy(ctx, ids, BuildConversionMissing, nil, nil) } func (s *Service) ConvertWebAccountsToBuildWithObserver(ctx context.Context, ids []uint64, observer ImportedAccountObserver) (BuildConversionResult, error) { - return s.ConvertWebAccountsToBuildWithProgress(ctx, ids, observer, nil) + return s.ConvertWebAccountsToBuildWithStrategy(ctx, ids, BuildConversionMissing, observer, nil) } // ConvertWebAccountsToBuildWithProgress 转换指定账号,并向调用方报告真实完成数。 func (s *Service) ConvertWebAccountsToBuildWithProgress(ctx context.Context, ids []uint64, observer ImportedAccountObserver, progress BatchProgressObserver) (BuildConversionResult, error) { + return s.ConvertWebAccountsToBuildWithStrategy(ctx, ids, BuildConversionMissing, observer, progress) +} + +func (s *Service) ConvertWebAccountsToBuildWithStrategy(ctx context.Context, ids []uint64, strategy BuildConversionStrategy, observer ImportedAccountObserver, progress BatchProgressObserver) (BuildConversionResult, error) { + if strategy != BuildConversionAll && strategy != BuildConversionMissing { + return BuildConversionResult{}, invalidInput("Grok Web 到 Build 转换策略无效") + } ids, err := normalizeIDs(ids, maxBuildConversionAccounts) if err != nil { return BuildConversionResult{}, err } - return s.convertWebAccountsToBuild(ctx, ids, observer, progress) + prefilteredSkipped := 0 + if strategy == BuildConversionMissing { + candidates, err := s.accounts.FilterMissingBuildConversionIDs(ctx, ids) + if err != nil { + return BuildConversionResult{}, mapRepositoryError(err) + } + prefilteredSkipped = len(ids) - len(candidates) + ids = candidates + } + result, err := s.convertWebAccountsToBuild(ctx, ids, strategy, observer, progress) + result.Skipped += prefilteredSkipped + return result, err } // ConvertAllWebAccountsToBuild 转换全部尚未建立 Build 关联的 Grok Web 账号。 func (s *Service) ConvertAllWebAccountsToBuild(ctx context.Context) (BuildConversionResult, error) { - return s.ConvertAllWebAccountsToBuildWithObserver(ctx, nil) + return s.ConvertAllWebAccountsToBuildWithStrategy(ctx, BuildConversionMissing, nil, nil) } func (s *Service) ConvertAllWebAccountsToBuildWithObserver(ctx context.Context, observer ImportedAccountObserver) (BuildConversionResult, error) { - return s.ConvertAllWebAccountsToBuildWithProgress(ctx, observer, nil) + return s.ConvertAllWebAccountsToBuildWithStrategy(ctx, BuildConversionMissing, observer, nil) } // ConvertAllWebAccountsToBuildWithProgress 转换完整未关联号池,并向调用方报告真实完成数。 func (s *Service) ConvertAllWebAccountsToBuildWithProgress(ctx context.Context, observer ImportedAccountObserver, progress BatchProgressObserver) (BuildConversionResult, error) { - ids, err := s.accounts.ListUnlinkedWebAccountIDs(ctx, maxBuildConversionAccounts+1) - if err != nil { - return BuildConversionResult{}, err - } - if len(ids) > maxBuildConversionAccounts { - return BuildConversionResult{}, invalidInput("未关联账号超过 1000 个,请分批勾选转换") - } - if len(ids) == 0 { - if progress != nil { - if err := progress(0, 0); err != nil { - return BuildConversionResult{}, err - } - } - return BuildConversionResult{}, nil - } - return s.convertWebAccountsToBuild(ctx, ids, observer, progress) + return s.ConvertAllWebAccountsToBuildWithStrategy(ctx, BuildConversionMissing, observer, progress) } -func (s *Service) convertWebAccountsToBuild(ctx context.Context, ids []uint64, observer ImportedAccountObserver, progress BatchProgressObserver) (BuildConversionResult, error) { +func (s *Service) ConvertAllWebAccountsToBuildWithStrategy(ctx context.Context, strategy BuildConversionStrategy, observer ImportedAccountObserver, progress BatchProgressObserver) (BuildConversionResult, error) { + if strategy != BuildConversionAll && strategy != BuildConversionMissing { + return BuildConversionResult{}, invalidInput("Grok Web 到 Build 转换策略无效") + } + batchSize := s.currentAccountTaskBatchSize() + result := BuildConversionResult{BuildAccountIDs: make([]uint64, 0)} + seenBuildIDs := make(map[uint64]struct{}) + var observed sync.Map + batchObserver := observer + if observer != nil { + batchObserver = func(accountID uint64) error { + if _, loaded := observed.LoadOrStore(accountID, struct{}{}); loaded { + return nil + } + return observer(accountID) + } + } + var afterID uint64 + completed := 0 + total := 0 + initialized := false + for { + var ( + ids []uint64 + count int64 + err error + ) + if strategy == BuildConversionMissing { + ids, count, err = s.accounts.ListUnlinkedWebAccountIDs(ctx, afterID, batchSize) + } else { + var values []accountdomain.Credential + values, count, err = s.accounts.ListProviderAccountBatch(ctx, accountdomain.ProviderWeb, afterID, batchSize) + ids = make([]uint64, 0, len(values)) + for _, value := range values { + ids = append(ids, value.ID) + } + } + if err != nil { + return result, err + } + if !initialized { + total = int(count) + initialized = true + if progress != nil { + if err := progress(0, total); err != nil { + return result, err + } + } + } + if len(ids) == 0 { + return result, nil + } + current, err := s.convertWebAccountsToBuild(ctx, ids, strategy, batchObserver, offsetBatchProgress(progress, completed, total)) + result.Created += current.Created + result.Linked += current.Linked + result.Skipped += current.Skipped + result.Failed += current.Failed + for _, buildID := range current.BuildAccountIDs { + if _, exists := seenBuildIDs[buildID]; exists { + continue + } + seenBuildIDs[buildID] = struct{}{} + result.BuildAccountIDs = append(result.BuildAccountIDs, buildID) + } + if err != nil { + return result, err + } + completed += len(ids) + afterID = ids[len(ids)-1] + if len(ids) < batchSize { + return result, nil + } + } +} + +func offsetBatchProgress(progress BatchProgressObserver, offset, total int) BatchProgressObserver { + if progress == nil { + return nil + } + return func(completed, _ int) error { + if completed == 0 { + return nil + } + return progress(offset+completed, total) + } +} + +func (s *Service) convertWebAccountsToBuild(ctx context.Context, ids []uint64, strategy BuildConversionStrategy, observer ImportedAccountObserver, progress BatchProgressObserver) (BuildConversionResult, error) { if progress != nil { if err := progress(0, len(ids)); err != nil { return BuildConversionResult{}, err @@ -869,7 +1056,7 @@ func (s *Service) convertWebAccountsToBuild(ctx context.Context, ids []uint64, o runCtx, cancel := context.WithCancel(ctx) defer cancel() results, summary, runErr := batch.MapObserved(runCtx, ids, batch.Options{Workers: s.conversionPool.Limit(), Pool: s.conversionPool}, func(workCtx context.Context, id uint64) (outcome, error) { - buildID, created, skipped, convertErr := s.convertWebAccountToBuild(workCtx, id) + buildID, created, skipped, convertErr := s.convertWebAccountToBuild(workCtx, id, strategy) return outcome{accountID: id, buildID: buildID, created: created, skipped: skipped, err: convertErr}, nil }, func(_ int, execution batch.Result[outcome]) { observerMu.Lock() @@ -934,7 +1121,7 @@ func (s *Service) convertWebAccountsToBuild(ctx context.Context, ids []uint64, o return result, nil } -func (s *Service) convertWebAccountToBuild(ctx context.Context, id uint64) (uint64, bool, bool, error) { +func (s *Service) convertWebAccountToBuild(ctx context.Context, id uint64, strategy BuildConversionStrategy) (uint64, bool, bool, error) { value, err := s.accounts.Get(ctx, id) if err != nil { return 0, false, false, mapRepositoryError(err) @@ -942,7 +1129,7 @@ func (s *Service) convertWebAccountToBuild(ctx context.Context, id uint64) (uint if value.Provider != accountdomain.ProviderWeb || value.AuthType != accountdomain.AuthTypeSSO { return 0, false, false, ErrUnsupported } - if value.LinkedAccountID != 0 { + if value.LinkedAccountID != 0 && strategy == BuildConversionMissing { return value.LinkedAccountID, false, true, nil } release, acquired, err := s.refreshLock.Acquire(ctx, "web-build-conversion:"+strconv.FormatUint(id, 10), 2*time.Minute) @@ -957,9 +1144,20 @@ func (s *Service) convertWebAccountToBuild(ctx context.Context, id uint64) (uint if err != nil { return 0, false, false, mapRepositoryError(err) } - if value.LinkedAccountID != 0 { + if value.LinkedAccountID != 0 && strategy == BuildConversionMissing { return value.LinkedAccountID, false, true, nil } + linkedBuildSourceKey := "" + if value.LinkedAccountID != 0 { + linkedBuild, getErr := s.accounts.Get(ctx, value.LinkedAccountID) + if getErr != nil { + return 0, false, false, mapRepositoryError(getErr) + } + if linkedBuild.Provider != accountdomain.ProviderBuild || strings.TrimSpace(linkedBuild.SourceKey) == "" { + return 0, false, false, fmt.Errorf("已关联 Grok Build 账号身份无效") + } + linkedBuildSourceKey = linkedBuild.SourceKey + } converter, ok := s.providers.BuildConverter(accountdomain.ProviderWeb) if !ok { return 0, false, false, fmt.Errorf("Grok Web SSO 转换能力未注册") @@ -973,10 +1171,16 @@ func (s *Service) convertWebAccountToBuild(ctx context.Context, id uint64) (uint } seed.Provider = accountdomain.ProviderBuild seed.AuthType = accountdomain.AuthTypeOAuth + if linkedBuildSourceKey != "" { + seed.SourceKey = linkedBuildSourceKey + } buildAccount, created, err := s.persistSeed(ctx, seed) if err != nil { return 0, false, false, err } + if value.LinkedAccountID != 0 && buildAccount.ID != value.LinkedAccountID { + return 0, false, false, fmt.Errorf("重新转换后的 Grok Build 账号身份不一致") + } if err := s.accounts.LinkWebToBuild(ctx, id, buildAccount.ID); err != nil { return 0, false, false, mapRepositoryError(err) } @@ -1867,6 +2071,18 @@ func (s *Service) BatchRefreshBilling(ctx context.Context, ids []uint64) (int, i return s.refreshBillings(ctx, values, nil) } +// BatchRefreshQuota 使用有限并发同步选中 Web 或 Console 账号的额度窗口。 +func (s *Service) BatchRefreshQuota(ctx context.Context, ids []uint64) (int, int, error) { + values, err := normalizeBatchIDs(ids) + if err != nil { + return 0, 0, err + } + return s.runAccountBatch(ctx, "quota_sync", values, s.syncPool, nil, func(workCtx context.Context, id uint64) error { + _, err := s.RefreshQuota(workCtx, id) + return err + }) +} + func (s *Service) refreshBillings(ctx context.Context, ids []uint64, progress BatchProgressObserver) (int, int, error) { return s.runAccountBatch(ctx, "billing_sync", ids, s.syncPool, progress, func(workCtx context.Context, id uint64) error { _, err := s.RefreshBilling(workCtx, id) diff --git a/backend/internal/application/account/web_console_sync_test.go b/backend/internal/application/account/web_console_sync_test.go index e4060623..0bb01dd8 100644 --- a/backend/internal/application/account/web_console_sync_test.go +++ b/backend/internal/application/account/web_console_sync_test.go @@ -3,8 +3,10 @@ package account import ( "context" "encoding/base64" + "fmt" "path/filepath" "strings" + "sync/atomic" "testing" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" @@ -58,7 +60,8 @@ func TestSyncWebAccountsToConsoleIsIdempotentAndPreservesBuildLink(t *testing.T) if err := accounts.LinkWebToBuild(ctx, webAccount.ID, buildAccount.ID); err != nil { t.Fatal(err) } - service := NewService(accounts, nil, nil, nil, provider.NewRegistry(consoleSSOCodecAdapter{}), cipher, memory.NewLockStore()) + var parseCalls atomic.Int64 + service := NewService(accounts, nil, nil, nil, provider.NewRegistry(consoleSSOCodecAdapter{parseCalls: &parseCalls}), cipher, memory.NewLockStore()) var observed []uint64 var progress [][2]int first, err := service.SyncWebAccountsToConsoleWithProgress(ctx, []uint64{webAccount.ID}, func(accountID uint64) error { @@ -96,6 +99,36 @@ func TestSyncWebAccountsToConsoleIsIdempotentAndPreservesBuildLink(t *testing.T) if second.Created != 0 || second.Updated != 1 || len(second.AccountIDs) != 1 || second.AccountIDs[0] != consoleAccount.ID { t.Fatalf("second sync = %#v", second) } + secondToken := "missing-sso-token" + missingWeb, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO, + Name: "Grok Web missing", SourceKey: "sso:" + security.HashToken(secondToken), + EncryptedAccessToken: encrypt(secondToken), Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + var missingProgress [][2]int + missing, err := service.SyncAllWebAccountsToConsoleWithStrategy(ctx, WebConsoleSyncMissing, nil, func(completed, total int) error { + missingProgress = append(missingProgress, [2]int{completed, total}) + return nil + }) + if err != nil { + t.Fatal(err) + } + if missing.Created != 1 || missing.Updated != 0 || missing.Skipped != 1 || len(missing.AccountIDs) != 1 || parseCalls.Load() != 3 { + t.Fatalf("missing-only sync = %#v, parse calls = %d", missing, parseCalls.Load()) + } + if len(missingProgress) != 2 || missingProgress[0] != [2]int{0, 1} || missingProgress[1] != [2]int{1, 1} { + t.Fatalf("missing-only progress = %#v", missingProgress) + } + selectedMissing, err := service.SyncWebAccountsToConsoleWithStrategy(ctx, []uint64{missingWeb.ID}, WebConsoleSyncMissing, nil, nil) + if err != nil { + t.Fatal(err) + } + if selectedMissing.Created != 0 || selectedMissing.Updated != 0 || selectedMissing.Skipped != 1 || parseCalls.Load() != 3 { + t.Fatalf("selected missing-only sync = %#v, parse calls = %d", selectedMissing, parseCalls.Load()) + } updatedWeb, err := accounts.Get(ctx, webAccount.ID) if err != nil { t.Fatal(err) @@ -109,16 +142,89 @@ func TestSyncWebAccountsToConsoleIsIdempotentAndPreservesBuildLink(t *testing.T) if err != nil { t.Fatal(err) } - if total != 1 { + if total != 2 { t.Fatalf("console account count = %d", total) } } -type consoleSSOCodecAdapter struct{} +func TestSyncAllWebAccountsToConsoleProcessesMoreThanLegacyLimitInBatches(t *testing.T) { + const totalAccounts = maxWebConsoleSyncAccounts + 1 + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + values := make([]accountdomain.Credential, 0, totalAccounts) + for index := 1; index <= totalAccounts; index++ { + token := fmt.Sprintf("sso-token-%d", index) + encrypted, encryptErr := cipher.Encrypt(token) + if encryptErr != nil { + t.Fatal(encryptErr) + } + values = append(values, accountdomain.Credential{ + ID: uint64(index), Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO, + Name: fmt.Sprintf("Grok Web %d", index), SourceKey: "sso:" + security.HashToken(token), + EncryptedAccessToken: encrypted, Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + } + repository := &webConsoleBatchRepository{values: values} + service := NewService(repository, nil, nil, nil, provider.NewRegistry(consoleSSOCodecAdapter{}), cipher, memory.NewLockStore()) + service.UpdateAccountTaskBatchSize(400) + progress := make([][2]int, 0, totalAccounts+1) + result, err := service.SyncAllWebAccountsToConsoleWithProgress(context.Background(), nil, func(completed, total int) error { + progress = append(progress, [2]int{completed, total}) + return nil + }) + if err != nil { + t.Fatal(err) + } + if result.Created != totalAccounts || result.Updated != 0 || len(result.AccountIDs) != totalAccounts { + t.Fatalf("sync result = %#v", result) + } + if repository.listCalls != 3 { + t.Fatalf("repository batches = %d", repository.listCalls) + } + if len(progress) != totalAccounts+1 || progress[0] != [2]int{0, totalAccounts} || progress[len(progress)-1] != [2]int{totalAccounts, totalAccounts} { + t.Fatalf("progress first=%v last=%v count=%d", progress[0], progress[len(progress)-1], len(progress)) + } +} + +type webConsoleBatchRepository struct { + repository.AccountRepository + values []accountdomain.Credential + listCalls int + nextID atomic.Uint64 +} + +func (r *webConsoleBatchRepository) ListProviderAccountBatch(_ context.Context, providerValue accountdomain.Provider, afterID uint64, limit int) ([]accountdomain.Credential, int64, error) { + r.listCalls++ + values := make([]accountdomain.Credential, 0, limit) + for _, value := range r.values { + if value.Provider == providerValue && value.ID > afterID { + values = append(values, value) + if len(values) == limit { + break + } + } + } + return values, int64(len(r.values)), nil +} + +func (r *webConsoleBatchRepository) UpsertManyByIdentity(_ context.Context, values []accountdomain.Credential) ([]repository.AccountUpsertResult, error) { + results := make([]repository.AccountUpsertResult, len(values)) + for index := range values { + results[index] = repository.AccountUpsertResult{ID: 10_000 + r.nextID.Add(1), Created: true} + } + return results, nil +} + +type consoleSSOCodecAdapter struct{ parseCalls *atomic.Int64 } func (consoleSSOCodecAdapter) Provider() accountdomain.Provider { return accountdomain.ProviderConsole } -func (consoleSSOCodecAdapter) ParseImportedCredentials(data []byte) ([]provider.CredentialSeed, error) { +func (a consoleSSOCodecAdapter) ParseImportedCredentials(data []byte) ([]provider.CredentialSeed, error) { + if a.parseCalls != nil { + a.parseCalls.Add(1) + } token := strings.TrimSpace(string(data)) return []provider.CredentialSeed{{ Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO, diff --git a/backend/internal/application/settings/service.go b/backend/internal/application/settings/service.go index f1a3d15c..d9e85c03 100644 --- a/backend/internal/application/settings/service.go +++ b/backend/internal/application/settings/service.go @@ -55,8 +55,9 @@ type ProviderConsoleConfig struct { ChatTimeout string } -// BatchConfig 是管理接口使用的批量任务并发输入。 +// BatchConfig 是管理接口使用的批量任务输入。 type BatchConfig struct { + AccountTaskBatchSize int ImportConcurrency int ConversionConcurrency int SyncConcurrency int @@ -272,8 +273,13 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C if value.Batch.RandomDelay != nil { randomDelay = *value.Batch.RandomDelay } + accountTaskBatchSize := value.Batch.AccountTaskBatchSize + if accountTaskBatchSize <= 0 { + accountTaskBatchSize = base.Batch.AccountTaskBatchSize + } base.Batch = config.BatchConfig{ - ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, + AccountTaskBatchSize: accountTaskBatchSize, + ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, SyncConcurrency: value.Batch.SyncConcurrency, RefreshConcurrency: value.Batch.RefreshConcurrency, RandomDelay: config.Duration(randomDelay), } @@ -317,7 +323,8 @@ func toDomainConfig(value config.Config) settingsdomain.Config { ChatTimeout: value.Provider.Console.ChatTimeout.Value(), }, Batch: settingsdomain.BatchConfig{ - ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, + AccountTaskBatchSize: value.Batch.AccountTaskBatchSize, + ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, SyncConcurrency: value.Batch.SyncConcurrency, RefreshConcurrency: value.Batch.RefreshConcurrency, RandomDelay: &randomDelay, }, @@ -382,8 +389,13 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, next.Provider.Web.AllowNSFW = input.ProviderWeb.AllowNSFW next.Provider.Console.BaseURL = strings.TrimSpace(input.ProviderConsole.BaseURL) next.Provider.Console.UserAgent = strings.TrimSpace(input.ProviderConsole.UserAgent) + accountTaskBatchSize := input.Batch.AccountTaskBatchSize + if accountTaskBatchSize <= 0 { + accountTaskBatchSize = current.Batch.AccountTaskBatchSize + } next.Batch = config.BatchConfig{ - ImportConcurrency: input.Batch.ImportConcurrency, ConversionConcurrency: input.Batch.ConversionConcurrency, + AccountTaskBatchSize: accountTaskBatchSize, + ImportConcurrency: input.Batch.ImportConcurrency, ConversionConcurrency: input.Batch.ConversionConcurrency, SyncConcurrency: input.Batch.SyncConcurrency, RefreshConcurrency: input.Batch.RefreshConcurrency, } next.Media.MaxImageBytes = input.Media.MaxImageBytes @@ -450,7 +462,8 @@ func toEditable(cfg config.Config) EditableConfig { ChatTimeout: cfg.Provider.Console.ChatTimeout.String(), }, Batch: BatchConfig{ - ImportConcurrency: cfg.Batch.ImportConcurrency, ConversionConcurrency: cfg.Batch.ConversionConcurrency, + AccountTaskBatchSize: cfg.Batch.AccountTaskBatchSize, + ImportConcurrency: cfg.Batch.ImportConcurrency, ConversionConcurrency: cfg.Batch.ConversionConcurrency, SyncConcurrency: cfg.Batch.SyncConcurrency, RefreshConcurrency: cfg.Batch.RefreshConcurrency, RandomDelay: cfg.Batch.RandomDelay.String(), }, diff --git a/backend/internal/application/settings/service_test.go b/backend/internal/application/settings/service_test.go index a31d60ee..90dbcbb3 100644 --- a/backend/internal/application/settings/service_test.go +++ b/backend/internal/application/settings/service_test.go @@ -53,7 +53,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { input.ProviderConsole.BaseURL = "https://console.example.com" input.ProviderConsole.UserAgent = "console-test-agent" input.ProviderConsole.ChatTimeout = "6m" - input.Batch = BatchConfig{ImportConcurrency: 26, ConversionConcurrency: 27, SyncConcurrency: 28, RefreshConcurrency: 29, RandomDelay: "750ms"} + input.Batch = BatchConfig{AccountTaskBatchSize: 777, ImportConcurrency: 26, ConversionConcurrency: 27, SyncConcurrency: 28, RefreshConcurrency: 29, RandomDelay: "750ms"} snapshot, err := service.Update(context.Background(), service.Get().Revision, input) if err != nil { @@ -68,7 +68,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if applied.Frontend.PublicAPIBaseURLOverride != "http://public.example.com" || applied.Frontend.EffectivePublicAPIBaseURL() != "http://public.example.com" { t.Fatalf("frontend configuration was not applied: %#v", applied.Frontend) } - if applied.Batch.ImportConcurrency != 26 || applied.Batch.ConversionConcurrency != 27 || applied.Batch.SyncConcurrency != 28 || applied.Batch.RefreshConcurrency != 29 || applied.Batch.RandomDelay.Value() != 750*time.Millisecond { + if applied.Batch.AccountTaskBatchSize != 777 || applied.Batch.ImportConcurrency != 26 || applied.Batch.ConversionConcurrency != 27 || applied.Batch.SyncConcurrency != 28 || applied.Batch.RefreshConcurrency != 29 || applied.Batch.RandomDelay.Value() != 750*time.Millisecond { t.Fatalf("batch configuration was not applied: %#v", applied.Batch) } if applied.Provider.Console.BaseURL != "https://console.example.com" || applied.Provider.Console.UserAgent != "console-test-agent" || applied.Provider.Console.ChatTimeout.Value() != 6*time.Minute { @@ -81,7 +81,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if err != nil { t.Fatal(err) } - if reloaded.Routing.MaxAttempts != 5 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" { + if reloaded.Routing.MaxAttempts != 5 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.AccountTaskBatchSize != 777 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" { t.Fatalf("configuration was not persisted") } } @@ -100,6 +100,20 @@ func TestLoadPersistedKeepsConsoleDefaultsWhenFieldIsMissing(t *testing.T) { } } +func TestLoadPersistedKeepsAccountTaskBatchSizeWhenFieldIsMissing(t *testing.T) { + cfg := testConfig(t) + value := toDomainConfig(cfg) + value.Batch.AccountTaskBatchSize = 0 + repository := &runtimeSettingsRepositoryStub{value: value, found: true} + loaded, _, _, err := LoadPersisted(context.Background(), cfg, repository) + if err != nil { + t.Fatal(err) + } + if loaded.Batch.AccountTaskBatchSize != cfg.Batch.AccountTaskBatchSize { + t.Fatalf("account task batch size = %d, want %d", loaded.Batch.AccountTaskBatchSize, cfg.Batch.AccountTaskBatchSize) + } +} + func TestSnapshotIncludesRecommendedBuildBaseline(t *testing.T) { service := NewService(testConfig(t), time.Time{}, 0, &runtimeSettingsRepositoryStub{}, nil, nil) recommended := service.Get().RecommendedProviderBuild @@ -122,6 +136,20 @@ func TestUpdateRejectsBatchConcurrencyOutsideSafeRange(t *testing.T) { } } +func TestUpdateRejectsAccountTaskBatchSizeOutsideSafeRange(t *testing.T) { + cfg := testConfig(t) + repository := &runtimeSettingsRepositoryStub{} + service := NewService(cfg, time.Time{}, 0, repository, nil, nil) + input := service.Get().Config + input.Batch.AccountTaskBatchSize = 1001 + if _, err := service.Update(context.Background(), 0, input); !errors.Is(err, ErrInvalidInput) { + t.Fatalf("error = %v", err) + } + if repository.found { + t.Fatal("invalid account task batch size was persisted") + } +} + func TestBatchRandomDelayCanBeDisabledAndPersisted(t *testing.T) { cfg := testConfig(t) repository := &runtimeSettingsRepositoryStub{} diff --git a/backend/internal/domain/settings/settings.go b/backend/internal/domain/settings/settings.go index bcb7242d..9716988a 100644 --- a/backend/internal/domain/settings/settings.go +++ b/backend/internal/domain/settings/settings.go @@ -48,8 +48,9 @@ type ProviderWebConfig struct { RecoveryBackoffMax time.Duration } -// BatchConfig 定义账号导入、转换、同步和凭据刷新的并发上限。 +// BatchConfig 定义账号批量任务的取数与并发边界。 type BatchConfig struct { + AccountTaskBatchSize int ImportConcurrency int ConversionConcurrency int SyncConcurrency int diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 4f7f0d1f..96c6b46f 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -149,8 +149,9 @@ type ConsoleProviderConfig struct { ChatTimeout Duration `yaml:"chatTimeout"` } -// BatchConfig 定义可热加载的账号批量任务并发上限。 +// BatchConfig 定义可热加载的账号批量任务边界。 type BatchConfig struct { + AccountTaskBatchSize int ImportConcurrency int ConversionConcurrency int SyncConcurrency int @@ -428,6 +429,9 @@ func (c Config) Validate() error { c.Batch.RefreshConcurrency < 1 || c.Batch.RefreshConcurrency > 50 { return errors.New("批量任务并发必须在 1 到 50 之间") } + if c.Batch.AccountTaskBatchSize < 1 || c.Batch.AccountTaskBatchSize > 1000 { + return errors.New("全部账号任务每批数量必须在 1 到 1000 之间") + } if c.Batch.RandomDelay.Value() < 0 || c.Batch.RandomDelay.Value() > 5*time.Second { return errors.New("批量任务随机延迟必须在 0 到 5 秒之间") } @@ -488,7 +492,8 @@ func defaultConfig() Config { }, }, Batch: BatchConfig{ - ImportConcurrency: 25, ConversionConcurrency: 25, SyncConcurrency: 25, + AccountTaskBatchSize: 1000, + ImportConcurrency: 25, ConversionConcurrency: 25, SyncConcurrency: 25, RefreshConcurrency: 25, RandomDelay: Duration(500 * time.Millisecond), }, Media: MediaConfig{ diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index c9a93b11..c7c84df8 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -45,7 +45,7 @@ bootstrapAdmin: if cfg.BootstrapAdmin.Username != "admin" || cfg.BootstrapAdmin.Password != "password123" { t.Fatalf("bootstrapAdmin = %#v", cfg.BootstrapAdmin) } - if cfg.Batch.ImportConcurrency != 25 || cfg.Batch.ConversionConcurrency != 25 || cfg.Batch.SyncConcurrency != 25 || cfg.Batch.RefreshConcurrency != 25 || cfg.Batch.RandomDelay.Value() != 500*time.Millisecond { + if cfg.Batch.AccountTaskBatchSize != 1000 || cfg.Batch.ImportConcurrency != 25 || cfg.Batch.ConversionConcurrency != 25 || cfg.Batch.SyncConcurrency != 25 || cfg.Batch.RefreshConcurrency != 25 || cfg.Batch.RandomDelay.Value() != 500*time.Millisecond { t.Fatalf("batch defaults = %#v", cfg.Batch) } expectedDatabasePath := filepath.Join(dir, "data", "backend.db") @@ -151,6 +151,7 @@ func TestValidateRejectsUnsafeRuntimeLimits(t *testing.T) { "image size": func(cfg *Config) { cfg.Media.MaxImageBytes = 33 << 20 }, "media total": func(cfg *Config) { cfg.Media.MaxTotalBytes = 1 }, "batch limit": func(cfg *Config) { cfg.Batch.SyncConcurrency = 51 }, + "batch size": func(cfg *Config) { cfg.Batch.AccountTaskBatchSize = 1001 }, "batch jitter": func(cfg *Config) { cfg.Batch.RandomDelay = Duration(6 * time.Second) }, "console url": func(cfg *Config) { cfg.Provider.Console.BaseURL = "http://console.x.ai" }, "console ua": func(cfg *Config) { cfg.Provider.Console.UserAgent = "" }, diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index 9aace44d..21a444ed 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -29,6 +29,7 @@ const ( providerQuotaExhaustedPredicate = `((provider_accounts.provider = 'grok_web' AND ((EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly' AND quota.remaining > 0)) OR (NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))) OR (provider_accounts.provider = 'grok_console' AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))` accountTypeSortExpression = `CASE WHEN provider_accounts.provider = 'grok_web' THEN COALESCE((SELECT profile.tier FROM web_account_profiles profile WHERE profile.account_id = provider_accounts.id), 'auto') WHEN ` + accountPaidBillingPredicate + ` THEN 'paid' WHEN ` + accountFreeSignalPredicate + ` THEN 'free' ELSE 'unknown' END` accountStatusSortExpression = `CASE WHEN provider_accounts.enabled = FALSE THEN 4 WHEN provider_accounts.auth_status = 'reauthRequired' THEN 5 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'probing') THEN 3 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'exhausted') OR ` + providerQuotaExhaustedPredicate + ` THEN 2 WHEN provider_accounts.cooldown_until > CURRENT_TIMESTAMP THEN 1 ELSE 0 END` + missingConsoleAccountPredicate = `NOT EXISTS (SELECT 1 FROM provider_accounts AS console_account WHERE console_account.provider = ? AND console_account.source_key = ('console-' || provider_accounts.source_key))` ) func (r *AccountRepository) List(ctx context.Context, input repository.AccountListQuery) ([]account.Credential, int64, error) { @@ -95,6 +96,42 @@ func (r *AccountRepository) List(ctx context.Context, input repository.AccountLi return out, total, nil } +func (r *AccountRepository) ListProviderAccountBatch(ctx context.Context, providerValue account.Provider, afterID uint64, limit int) ([]account.Credential, int64, error) { + if limit < 1 { + return []account.Credential{}, 0, nil + } + var total int64 + if afterID == 0 { + if err := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("provider = ?", providerValue).Count(&total).Error; err != nil { + return nil, 0, err + } + } + var rows []accountModel + if err := r.db.db.WithContext(ctx). + Preload("Credential").Preload("WebProfile"). + Where("provider = ? AND id > ?", providerValue, afterID). + Order("id ASC").Limit(limit).Find(&rows).Error; err != nil { + return nil, 0, err + } + out := make([]account.Credential, 0, len(rows)) + for _, row := range rows { + out = append(out, toAccountDomain(row)) + } + if err := r.attachAccountLinks(ctx, out); err != nil { + return nil, 0, err + } + return out, total, nil +} + +func (r *AccountRepository) ListAccountSourceKeys(ctx context.Context, providerValue account.Provider) ([]string, error) { + var values []string + err := r.db.db.WithContext(ctx).Model(&accountModel{}). + Where("provider = ?", providerValue). + Order("id ASC"). + Pluck("source_key", &values).Error + return values, err +} + func (r *AccountRepository) Summarize(ctx context.Context, now time.Time) ([]repository.AccountSummary, error) { var rows []repository.AccountSummary selectFields := ` @@ -257,20 +294,110 @@ func (r *AccountRepository) ListEnabledAccountIDs(ctx context.Context, provider return ids, err } -func (r *AccountRepository) ListUnlinkedWebAccountIDs(ctx context.Context, limit int) ([]uint64, error) { - if limit < 1 { +func (r *AccountRepository) FilterMissingBuildConversionIDs(ctx context.Context, ids []uint64) ([]uint64, error) { + if len(ids) == 0 { return []uint64{}, nil } + var linkedIDs []uint64 + if err := r.db.db.WithContext(ctx).Model(&accountProviderLinkModel{}). + Where("web_account_id IN ?", ids).Pluck("web_account_id", &linkedIDs).Error; err != nil { + return nil, err + } + linked := make(map[uint64]struct{}, len(linkedIDs)) + for _, id := range linkedIDs { + linked[id] = struct{}{} + } + values := make([]uint64, 0, len(ids)-len(linked)) + for _, id := range ids { + if _, exists := linked[id]; !exists { + values = append(values, id) + } + } + return values, nil +} + +func (r *AccountRepository) ListUnlinkedWebAccountIDs(ctx context.Context, afterID uint64, limit int) ([]uint64, int64, error) { + if limit < 1 { + return []uint64{}, 0, nil + } + query := func() *gorm.DB { + return r.db.db.WithContext(ctx). + Table("provider_accounts AS account"). + Joins("LEFT JOIN account_provider_links AS link ON link.web_account_id = account.id"). + Where("account.provider = ? AND link.web_account_id IS NULL", account.ProviderWeb) + } + var total int64 + if afterID == 0 { + if err := query().Count(&total).Error; err != nil { + return nil, 0, err + } + } var ids []uint64 - err := r.db.db.WithContext(ctx). - Table("provider_accounts AS account"). + err := query(). Select("account.id"). - Joins("LEFT JOIN account_provider_links AS link ON link.web_account_id = account.id"). - Where("account.provider = ? AND link.web_account_id IS NULL", account.ProviderWeb). + Where("account.id > ?", afterID). Order("account.id ASC"). Limit(limit). Scan(&ids).Error - return ids, err + return ids, total, err +} + +func (r *AccountRepository) ListMissingConsoleSyncAccounts(ctx context.Context, ids []uint64) ([]account.Credential, error) { + if len(ids) == 0 { + return []account.Credential{}, nil + } + var existing int64 + if err := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id IN ?", ids).Count(&existing).Error; err != nil { + return nil, err + } + if existing != int64(len(ids)) { + return nil, repository.ErrNotFound + } + var rows []accountModel + if err := r.db.db.WithContext(ctx). + Preload("Credential").Preload("WebProfile"). + Where("id IN ?", ids). + Where("(provider <> ? OR "+missingConsoleAccountPredicate+")", account.ProviderWeb, account.ProviderConsole). + Order("id ASC").Find(&rows).Error; err != nil { + return nil, err + } + values := make([]account.Credential, 0, len(rows)) + for _, row := range rows { + values = append(values, toAccountDomain(row)) + } + return values, nil +} + +func (r *AccountRepository) ListMissingConsoleSyncBatch(ctx context.Context, afterID uint64, limit int) ([]account.Credential, int64, int64, error) { + if limit < 1 { + return []account.Credential{}, 0, 0, nil + } + query := func() *gorm.DB { + return r.db.db.WithContext(ctx).Model(&accountModel{}). + Where("provider = ?", account.ProviderWeb). + Where(missingConsoleAccountPredicate, account.ProviderConsole) + } + var total, skipped int64 + if afterID == 0 { + if err := query().Count(&total).Error; err != nil { + return nil, 0, 0, err + } + var all int64 + if err := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("provider = ?", account.ProviderWeb).Count(&all).Error; err != nil { + return nil, 0, 0, err + } + skipped = max(0, all-total) + } + var rows []accountModel + if err := query().Preload("Credential").Preload("WebProfile"). + Where("id > ?", afterID).Order("id ASC").Limit(limit).Find(&rows).Error; err != nil { + return nil, 0, 0, err + } + values := make([]account.Credential, 0, len(rows)) + for _, row := range rows { + values = append(values, toAccountDomain(row)) + } + return values, total, skipped, nil } func (r *AccountRepository) HasActive(ctx context.Context, provider account.Provider) (bool, error) { diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 3b496cf6..5ff19246 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -27,12 +27,12 @@ func (adminSessionModel) TableName() string { return "admin_sessions" } type accountModel struct { ID uint64 `gorm:"primaryKey;autoIncrement"` IdentityKey string `gorm:"size:64;uniqueIndex;not null;check:chk_accounts_identity_key,length(identity_key) = 64"` - Provider string `gorm:"size:32;not null;check:chk_accounts_provider,provider IN ('grok_build','grok_web','grok_console')"` + Provider string `gorm:"size:32;not null;check:chk_accounts_provider,provider IN ('grok_build','grok_web','grok_console');index:idx_accounts_provider_source,priority:1"` Name string `gorm:"size:160;not null;check:chk_accounts_name,length(trim(name)) BETWEEN 1 AND 160"` Email string `gorm:"size:255;check:chk_accounts_email,length(email) <= 255"` UserID string `gorm:"size:255;check:chk_accounts_user_id,length(user_id) <= 255"` TeamID string `gorm:"size:255;check:chk_accounts_team_id,length(team_id) <= 255"` - SourceKey string `gorm:"size:512;not null;check:chk_accounts_source_key,length(trim(source_key)) BETWEEN 1 AND 512"` + SourceKey string `gorm:"size:512;not null;check:chk_accounts_source_key,length(trim(source_key)) BETWEEN 1 AND 512;index:idx_accounts_provider_source,priority:2"` Enabled bool `gorm:"not null"` AuthStatus string `gorm:"size:32;not null;check:chk_accounts_auth_status,auth_status IN ('active','reauthRequired')"` Priority int `gorm:"not null;default:1"` diff --git a/backend/internal/infra/persistence/relational/repository_test.go b/backend/internal/infra/persistence/relational/repository_test.go index 7c511b5b..42f5f4b7 100644 --- a/backend/internal/infra/persistence/relational/repository_test.go +++ b/backend/internal/infra/persistence/relational/repository_test.go @@ -170,12 +170,56 @@ func TestAccountRepositoryLinksWebAndBuildAccountsOnce(t *testing.T) { if err != nil { t.Fatal(err) } - unlinkedIDs, err := repo.ListUnlinkedWebAccountIDs(ctx, 10) + unlinkedIDs, total, err := repo.ListUnlinkedWebAccountIDs(ctx, 0, 1) if err != nil { t.Fatal(err) } - if len(unlinkedIDs) != 1 || unlinkedIDs[0] != unlinkedWeb.ID { - t.Fatalf("unlinked web ids = %#v", unlinkedIDs) + if total != 1 || len(unlinkedIDs) != 1 || unlinkedIDs[0] != unlinkedWeb.ID { + t.Fatalf("unlinked web ids = %#v, total = %d", unlinkedIDs, total) + } + nextUnlinkedIDs, nextTotal, err := repo.ListUnlinkedWebAccountIDs(ctx, unlinkedWeb.ID, 1) + if err != nil { + t.Fatal(err) + } + if nextTotal != 0 || len(nextUnlinkedIDs) != 0 { + t.Fatalf("next unlinked web ids = %#v, total = %d", nextUnlinkedIDs, nextTotal) + } + buildCandidates, err := repo.FilterMissingBuildConversionIDs(ctx, []uint64{web.ID, build.ID, unlinkedWeb.ID, 999_999}) + if err != nil { + t.Fatal(err) + } + if len(buildCandidates) != 3 || buildCandidates[0] != build.ID || buildCandidates[1] != unlinkedWeb.ID || buildCandidates[2] != 999_999 { + t.Fatalf("build conversion candidates = %#v", buildCandidates) + } + if _, _, err := repo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, Name: "console", SourceKey: "console-" + web.SourceKey, + EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive, + }); err != nil { + t.Fatal(err) + } + consoleCandidates, err := repo.ListMissingConsoleSyncAccounts(ctx, []uint64{web.ID, build.ID, unlinkedWeb.ID}) + if err != nil { + t.Fatal(err) + } + if len(consoleCandidates) != 2 || consoleCandidates[0].ID != build.ID || consoleCandidates[1].ID != unlinkedWeb.ID { + t.Fatalf("console sync candidates = %#v", consoleCandidates) + } + if _, err := repo.ListMissingConsoleSyncAccounts(ctx, []uint64{web.ID, 999_999}); !errors.Is(err, repository.ErrNotFound) { + t.Fatalf("missing console candidate error = %v", err) + } + consoleBatch, consoleTotal, consoleSkipped, err := repo.ListMissingConsoleSyncBatch(ctx, 0, 10) + if err != nil { + t.Fatal(err) + } + if consoleTotal != 1 || consoleSkipped != 1 || len(consoleBatch) != 1 || consoleBatch[0].ID != unlinkedWeb.ID { + t.Fatalf("console sync batch = %#v, total = %d, skipped = %d", consoleBatch, consoleTotal, consoleSkipped) + } + webSourceKeys, err := repo.ListAccountSourceKeys(ctx, account.ProviderWeb) + if err != nil { + t.Fatal(err) + } + if len(webSourceKeys) != 2 || webSourceKeys[0] != "web" || webSourceKeys[1] != "web-2" { + t.Fatalf("web source keys = %#v", webSourceKeys) } otherBuild, _, err := repo.UpsertByIdentity(ctx, account.Credential{Provider: account.ProviderBuild, Name: "build-2", SourceKey: "build-2", EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive}) if err != nil { diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index faaa0fac..eda0ca4f 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -23,10 +23,20 @@ type AccountUpsertResult struct { // AccountRepository 定义 OAuth 账号和额度快照持久化能力。 type AccountRepository interface { List(ctx context.Context, query AccountListQuery) ([]account.Credential, int64, error) + // ListProviderAccountBatch 以 ID 游标取一批账号;total 仅在 afterID 为 0 时返回。 + ListProviderAccountBatch(ctx context.Context, provider account.Provider, afterID uint64, limit int) ([]account.Credential, int64, error) + ListAccountSourceKeys(ctx context.Context, provider account.Provider) ([]string, error) Summarize(ctx context.Context, now time.Time) ([]AccountSummary, error) ListEnabled(ctx context.Context, provider account.Provider) ([]account.Credential, error) ListEnabledAccountIDs(ctx context.Context, provider account.Provider, refreshableOnly bool) ([]uint64, error) - ListUnlinkedWebAccountIDs(ctx context.Context, limit int) ([]uint64, error) + // FilterMissingBuildConversionIDs 从指定账号中排除已经关联 Build 的 Web 账号。 + FilterMissingBuildConversionIDs(ctx context.Context, ids []uint64) ([]uint64, error) + // ListUnlinkedWebAccountIDs 以 ID 游标取未关联 Web 账号;total 仅在 afterID 为 0 时返回。 + ListUnlinkedWebAccountIDs(ctx context.Context, afterID uint64, limit int) ([]uint64, int64, error) + // ListMissingConsoleSyncAccounts 从指定账号中排除已有对应 Console 账号的 Web 账号。 + ListMissingConsoleSyncAccounts(ctx context.Context, ids []uint64) ([]account.Credential, error) + // ListMissingConsoleSyncBatch 以 ID 游标取缺少 Console 账号的 Web 账号;total/skipped 仅在 afterID 为 0 时返回。 + ListMissingConsoleSyncBatch(ctx context.Context, afterID uint64, limit int) ([]account.Credential, int64, int64, error) HasActive(ctx context.Context, provider account.Provider) (bool, error) ListRoutingCandidates(ctx context.Context, provider account.Provider, upstreamModel, quotaMode string) ([]account.RoutingCandidate, error) Get(ctx context.Context, id uint64) (account.Credential, error) diff --git a/backend/internal/transport/http/account/handler.go b/backend/internal/transport/http/account/handler.go index 8cf8002c..0c6a64cd 100644 --- a/backend/internal/transport/http/account/handler.go +++ b/backend/internal/transport/http/account/handler.go @@ -173,9 +173,16 @@ type batchDeleteRequest struct { Provider string `json:"provider" binding:"required"` } -type accountSelectionRequest struct { - IDs []string `json:"ids"` - All bool `json:"all"` +type buildConversionRequest struct { + IDs []string `json:"ids"` + All bool `json:"all"` + Strategy accountapp.BuildConversionStrategy `json:"strategy"` +} + +type webConsoleSyncRequest struct { + IDs []string `json:"ids"` + All bool `json:"all"` + Strategy accountapp.WebConsoleSyncStrategy `json:"strategy"` } type buildConversionResponse struct { @@ -207,6 +214,7 @@ type accountTokenRefreshResponse struct { type accountImportResponse struct { Created int `json:"created"` Updated int `json:"updated"` + Skipped int `json:"skipped"` Synced int `json:"synced"` SyncFailed int `json:"syncFailed"` } @@ -408,13 +416,20 @@ func (h *Handler) batchRefreshBilling(c *gin.Context) { response.Error(c, http.StatusBadRequest, "invalidId", err.Error()) return } - if request.Provider != string(accountdomain.ProviderBuild) || !h.validateProviderIDs(c, ids, request.Provider) { - if request.Provider != string(accountdomain.ProviderBuild) { - response.Error(c, http.StatusBadRequest, "invalidProvider", "Grok Web 账号不支持 Billing 批量同步") - } + providerValue := accountdomain.Provider(request.Provider) + if !providerValue.IsValid() { + response.Error(c, http.StatusBadRequest, "invalidProvider", "账号来源无效") return } - succeeded, failed, err := h.service.BatchRefreshBilling(c.Request.Context(), ids) + if !h.validateProviderIDs(c, ids, request.Provider) { + return + } + var succeeded, failed int + if providerValue == accountdomain.ProviderBuild { + succeeded, failed, err = h.service.BatchRefreshBilling(c.Request.Context(), ids) + } else { + succeeded, failed, err = h.service.BatchRefreshQuota(c.Request.Context(), ids) + } if err != nil { h.writeServiceError(c, "billingBatchRefreshFailed", err, http.StatusBadGateway, "批量同步账号额度失败") return @@ -486,7 +501,7 @@ func (h *Handler) importConsoleAuth(c *gin.Context) { } func (h *Handler) convertWebToBuild(c *gin.Context) { - var request accountSelectionRequest + var request buildConversionRequest if c.ShouldBindJSON(&request) != nil { response.Error(c, http.StatusBadRequest, "invalidRequest", "转换请求无效") return @@ -495,6 +510,13 @@ func (h *Handler) convertWebToBuild(c *gin.Context) { response.Error(c, http.StatusBadRequest, "invalidRequest", "全部转换与指定账号不能同时提交") return } + if request.Strategy == "" { + request.Strategy = accountapp.BuildConversionMissing + } + if request.Strategy != accountapp.BuildConversionAll && request.Strategy != accountapp.BuildConversionMissing { + response.Error(c, http.StatusBadRequest, "invalidRequest", "转换策略无效") + return + } var ids []uint64 if !request.All { var err error @@ -504,11 +526,11 @@ func (h *Handler) convertWebToBuild(c *gin.Context) { return } } - h.streamWebToBuildConversion(c, request.All, ids) + h.streamWebToBuildConversion(c, request.All, ids, request.Strategy) } func (h *Handler) syncWebToConsole(c *gin.Context) { - var request accountSelectionRequest + var request webConsoleSyncRequest if c.ShouldBindJSON(&request) != nil { response.Error(c, http.StatusBadRequest, "invalidRequest", "同步请求无效") return @@ -517,6 +539,13 @@ func (h *Handler) syncWebToConsole(c *gin.Context) { response.Error(c, http.StatusBadRequest, "invalidRequest", "全部同步与指定账号不能同时提交") return } + if request.Strategy == "" { + request.Strategy = accountapp.WebConsoleSyncAll + } + if request.Strategy != accountapp.WebConsoleSyncAll && request.Strategy != accountapp.WebConsoleSyncMissing { + response.Error(c, http.StatusBadRequest, "invalidRequest", "同步策略无效") + return + } var ids []uint64 if !request.All { var err error @@ -526,56 +555,56 @@ func (h *Handler) syncWebToConsole(c *gin.Context) { return } } - h.streamWebToConsoleSync(c, request.All, ids) + h.streamWebToConsoleSync(c, request.All, ids, request.Strategy) } -func (h *Handler) runWebToConsoleSync(ctx context.Context, all bool, ids []uint64, progress accountapp.BatchProgressObserver, syncProgress func(completed, total int)) (accountapp.ImportResult, accountsyncapp.Result, error) { +func (h *Handler) runWebToConsoleSync(ctx context.Context, all bool, ids []uint64, strategy accountapp.WebConsoleSyncStrategy, progress accountapp.BatchProgressObserver, syncProgress func(completed, total int)) (accountapp.ImportResult, accountsyncapp.Result, error) { pipeline := h.startSyncPipeline(ctx, syncProgress) var ( result accountapp.ImportResult err error ) if all { - result, err = h.service.SyncAllWebAccountsToConsoleWithProgress(pipeline.ctx, pipeline.Observe, progress) + result, err = h.service.SyncAllWebAccountsToConsoleWithStrategy(pipeline.ctx, strategy, pipeline.Observe, progress) } else { - result, err = h.service.SyncWebAccountsToConsoleWithProgress(pipeline.ctx, ids, pipeline.Observe, progress) + result, err = h.service.SyncWebAccountsToConsoleWithStrategy(pipeline.ctx, ids, strategy, pipeline.Observe, progress) } syncResult := pipeline.Finish(err != nil) return result, syncResult, err } -func (h *Handler) streamWebToConsoleSync(c *gin.Context, all bool, ids []uint64) { +func (h *Handler) streamWebToConsoleSync(c *gin.Context, all bool, ids []uint64, strategy accountapp.WebConsoleSyncStrategy) { stream := newAccountEventStream(c) defer stream.Close() var total atomic.Int64 - result, syncResult, err := h.runWebToConsoleSync(c.Request.Context(), all, ids, stream.PhaseProgressObserver("importing", &total), stream.SyncProgressObserver()) + result, syncResult, err := h.runWebToConsoleSync(c.Request.Context(), all, ids, strategy, stream.PhaseProgressObserver("importing", &total), stream.SyncProgressObserver()) if err != nil { stream.WriteError("accountConsoleSyncFailed", "Grok Web 账号同步到 Console 失败") return } - _ = stream.Write("complete", accountImportResponse{Created: result.Created, Updated: result.Updated, Synced: syncResult.Succeeded, SyncFailed: syncResult.Failed}) + _ = stream.Write("complete", accountImportResponse{Created: result.Created, Updated: result.Updated, Skipped: result.Skipped, Synced: syncResult.Succeeded, SyncFailed: syncResult.Failed}) } -func (h *Handler) runWebToBuildConversion(ctx context.Context, all bool, ids []uint64, progress accountapp.BatchProgressObserver, syncProgress func(completed, total int)) (accountapp.BuildConversionResult, accountsyncapp.Result, error) { +func (h *Handler) runWebToBuildConversion(ctx context.Context, all bool, ids []uint64, strategy accountapp.BuildConversionStrategy, progress accountapp.BatchProgressObserver, syncProgress func(completed, total int)) (accountapp.BuildConversionResult, accountsyncapp.Result, error) { pipeline := h.startSyncPipeline(ctx, syncProgress) var ( result accountapp.BuildConversionResult err error ) if all { - result, err = h.service.ConvertAllWebAccountsToBuildWithProgress(pipeline.ctx, pipeline.Observe, progress) + result, err = h.service.ConvertAllWebAccountsToBuildWithStrategy(pipeline.ctx, strategy, pipeline.Observe, progress) } else { - result, err = h.service.ConvertWebAccountsToBuildWithProgress(pipeline.ctx, ids, pipeline.Observe, progress) + result, err = h.service.ConvertWebAccountsToBuildWithStrategy(pipeline.ctx, ids, strategy, pipeline.Observe, progress) } syncResult := pipeline.Finish(err != nil) return result, syncResult, err } -func (h *Handler) streamWebToBuildConversion(c *gin.Context, all bool, ids []uint64) { +func (h *Handler) streamWebToBuildConversion(c *gin.Context, all bool, ids []uint64, strategy accountapp.BuildConversionStrategy) { stream := newAccountEventStream(c) defer stream.Close() var total atomic.Int64 - result, syncResult, err := h.runWebToBuildConversion(c.Request.Context(), all, ids, stream.PhaseProgressObserver("converting", &total), stream.SyncProgressObserver()) + result, syncResult, err := h.runWebToBuildConversion(c.Request.Context(), all, ids, strategy, stream.PhaseProgressObserver("converting", &total), stream.SyncProgressObserver()) if err != nil { stream.WriteError("accountConversionFailed", "Grok Web 账号转换失败") return diff --git a/backend/internal/transport/http/account/handler_test.go b/backend/internal/transport/http/account/handler_test.go index 6777c225..88617779 100644 --- a/backend/internal/transport/http/account/handler_test.go +++ b/backend/internal/transport/http/account/handler_test.go @@ -92,6 +92,20 @@ func TestWriteBuildConversionEventUsesSSEFormat(t *testing.T) { } } +func TestConvertWebToBuildRejectsInvalidStrategy(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest("POST", "/api/admin/v1/accounts/web/convert-to-build", strings.NewReader(`{"ids":["1"],"strategy":"invalid"}`)) + ctx.Request.Header.Set("Content-Type", "application/json") + + new(Handler).convertWebToBuild(ctx) + + if recorder.Code != 400 || !strings.Contains(recorder.Body.String(), `"code":"invalidRequest"`) { + t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String()) + } +} + func TestAccountProgressEventIncludesOptionalPhase(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() diff --git a/backend/internal/transport/http/settings/handler.go b/backend/internal/transport/http/settings/handler.go index 2b975ddc..d2510e98 100644 --- a/backend/internal/transport/http/settings/handler.go +++ b/backend/internal/transport/http/settings/handler.go @@ -75,6 +75,7 @@ type providerWebConfigDTO struct { } type batchConfigDTO struct { + AccountTaskBatchSize int `json:"accountTaskBatchSize"` ImportConcurrency int `json:"importConcurrency"` ConversionConcurrency int `json:"conversionConcurrency"` SyncConcurrency int `json:"syncConcurrency"` @@ -166,7 +167,8 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { ChatTimeout: value.ProviderConsole.ChatTimeout, }, Batch: settingsapp.BatchConfig{ - ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, + AccountTaskBatchSize: value.Batch.AccountTaskBatchSize, + ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, SyncConcurrency: value.Batch.SyncConcurrency, RefreshConcurrency: value.Batch.RefreshConcurrency, RandomDelay: value.Batch.RandomDelay, }, @@ -213,7 +215,8 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { ChatTimeout: config.ProviderConsole.ChatTimeout, }, Batch: batchConfigDTO{ - ImportConcurrency: config.Batch.ImportConcurrency, ConversionConcurrency: config.Batch.ConversionConcurrency, + AccountTaskBatchSize: config.Batch.AccountTaskBatchSize, + ImportConcurrency: config.Batch.ImportConcurrency, ConversionConcurrency: config.Batch.ConversionConcurrency, SyncConcurrency: config.Batch.SyncConcurrency, RefreshConcurrency: config.Batch.RefreshConcurrency, RandomDelay: config.Batch.RandomDelay, }, diff --git a/frontend/src/features/accounts/accounts-api.ts b/frontend/src/features/accounts/accounts-api.ts index 95a2d301..3a692a02 100644 --- a/frontend/src/features/accounts/accounts-api.ts +++ b/frontend/src/features/accounts/accounts-api.ts @@ -231,11 +231,17 @@ export type BuildConversionResultDTO = { syncFailed: number; }; -export type BuildConversionInput = - | { all: true; ids?: never } - | { all?: false; ids: string[] }; +export type AccountSyncStrategy = "missing" | "all"; +export type BuildConversionStrategy = AccountSyncStrategy; +export type WebConsoleSyncStrategy = AccountSyncStrategy; -export type WebConsoleSyncInput = BuildConversionInput; +export type BuildConversionInput = + | { all: true; ids?: never; strategy?: BuildConversionStrategy } + | { all?: false; ids: string[]; strategy?: BuildConversionStrategy }; + +export type WebConsoleSyncInput = + | { all: true; ids?: never; strategy: WebConsoleSyncStrategy } + | { all?: false; ids: string[]; strategy: WebConsoleSyncStrategy }; export type AccountTaskProgressDTO = { completed: number; @@ -250,6 +256,8 @@ export type AccountImportResultDTO = { syncFailed: number; }; +export type WebConsoleSyncResultDTO = AccountImportResultDTO & { skipped: number }; + type AccountTaskStreamPayload = Partial & { code?: string; message?: string; @@ -352,8 +360,8 @@ export function convertWebAccountsToBuild(input: BuildConversionInput, onProgres return runAccountTask("/api/admin/v1/accounts/web/convert-to-build", input, ["created", "linked", "skipped", "failed", "synced", "syncFailed"], onProgress, signal); } -export function syncWebAccountsToConsole(input: WebConsoleSyncInput, onProgress?: (value: AccountTaskProgressDTO) => void, signal?: AbortSignal): Promise { - return runAccountTask("/api/admin/v1/accounts/web/sync-to-console", input, ["created", "updated", "synced", "syncFailed"], onProgress, signal); +export function syncWebAccountsToConsole(input: WebConsoleSyncInput, onProgress?: (value: AccountTaskProgressDTO) => void, signal?: AbortSignal): Promise { + return runAccountTask("/api/admin/v1/accounts/web/sync-to-console", input, ["created", "updated", "skipped", "synced", "syncFailed"], onProgress, signal); } export function importAccounts(files: readonly File[], onProgress?: (value: AccountTaskProgressDTO) => void, signal?: AbortSignal): Promise { @@ -386,7 +394,7 @@ 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 refreshAccountsBilling(ids: string[], provider: AccountProvider): Promise<{ succeeded: number; failed: number }> { +export function refreshAccountsQuota(ids: string[], provider: AccountProvider): Promise<{ succeeded: number; failed: number }> { return apiRequest("/api/admin/v1/accounts/batch/refresh-billing", { 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 cfe61bb8..2be3b20c 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -44,7 +44,7 @@ import { listAccounts, pollDeviceAuthorization, refreshAccountBilling, - refreshAccountsBilling, + refreshAccountsQuota, refreshAccountToken, refreshAccountQuota, refreshAllAccountBilling, @@ -60,6 +60,7 @@ import { type AccountUpdateInput, type AccountTaskProgressDTO, type BuildConversionInput, + type BuildConversionStrategy, type WebConsoleSyncInput, type DeviceSessionDTO, type QuotaDTO, @@ -99,8 +100,10 @@ export function AccountsPage() { const [syncAllOpen, setSyncAllOpen] = useState(false); const [syncProgress, setSyncProgress] = useState(null); const [conversionTargets, setConversionTargets] = useState(null); + const [conversionStrategy, setConversionStrategy] = useState("missing"); const [conversionProgress, setConversionProgress] = useState(null); const [webConsoleSyncTargets, setWebConsoleSyncTargets] = useState(null); + const [webConsoleSyncStrategy, setWebConsoleSyncStrategy] = useState<"missing" | "all">("missing"); const [webConsoleSyncProgress, setWebConsoleSyncProgress] = useState(null); const [renewAllOpen, setRenewAllOpen] = useState(false); const [renewalProgress, setRenewalProgress] = useState(null); @@ -264,7 +267,7 @@ export function AccountsPage() { mutationFn: (input: BuildConversionInput) => { const controller = new AbortController(); conversionAbortRef.current = controller; - setConversionProgress(Array.isArray(conversionTargets) ? { converting: { completed: 0, total: conversionTargets.length, phase: "converting" } } : null); + setConversionProgress(null); return convertWebAccountsToBuild(input, (progress) => { const phase = progress.phase === "syncing" ? "syncing" : "converting"; setConversionProgress((current) => ({ ...(current ?? {}), [phase]: progress })); @@ -364,7 +367,7 @@ export function AccountsPage() { }); const batchBillingMutation = useMutation({ - mutationFn: () => refreshAccountsBilling([...selected], provider), + mutationFn: () => refreshAccountsQuota([...selected], provider), onSuccess: (result) => { setSelected(new Set()); invalidateAccountData(); @@ -443,6 +446,16 @@ export function AccountsPage() { importMutation.mutate([new File([value], filename, { type: "text/plain" })]); } + function openWebConsoleSync(targets: string[] | "all"): void { + setWebConsoleSyncStrategy("missing"); + setWebConsoleSyncTargets(targets); + } + + function openBuildConversion(targets: string[] | "all"): void { + setConversionStrategy("missing"); + setConversionTargets(targets); + } + async function startDeviceLogin(): Promise { setDeviceOpen(true); setDeviceStatus("starting"); @@ -594,15 +607,15 @@ export function AccountsPage() { {t("common.selectedCount", { count: selected.size })} - {provider === "grok_web" ? : null} - {provider === "grok_web" ? : null} - {provider === "grok_build" ? : null} + {provider === "grok_web" ? : null} + {provider === "grok_web" ? : null} + ) : (
- {provider === "grok_web" && webSummary.total > 0 ? : null} - {provider === "grok_web" && webSummary.total > 0 ? : null} + {provider === "grok_web" && webSummary.total > 0 ? : null} + {provider === "grok_web" && webSummary.total > 0 ? : null} {hasProviderAccounts ? : null} {hasProviderAccounts && provider === "grok_build" ? : null} @@ -696,8 +709,8 @@ export function AccountsPage() { beginEdit(account)}>{t("common.edit")} - {provider === "grok_web" && !account.linkedAccountId ? setConversionTargets([account.id])}>{t("accounts.convertToBuild")} : null} - {provider === "grok_web" ? setWebConsoleSyncTargets([account.id])}>{t("webConsoleSync.action")} : null} + {provider === "grok_web" ? openBuildConversion([account.id])}>{t("accounts.convertToBuild")} : null} + {provider === "grok_web" ? openWebConsoleSync([account.id])}>{t("webConsoleSync.action")} : null} {provider === "grok_build" ? tokenMutation.mutate(account.id)}>{t("accounts.refreshToken")} : null} provider === "grok_build" ? billingMutation.mutate(account.id) : quotaMutation.mutate(account.id)}>{provider === "grok_build" ? t("accounts.refreshBilling") : t("accounts.refreshModeQuota")} @@ -725,12 +738,20 @@ export function AccountsPage() { {t(webConsoleSyncTargets === "all" ? "webConsoleSync.allTitle" : "webConsoleSync.selectedTitle")} - {webConsoleSyncTargets === "all" ? t("webConsoleSync.allDescription") : t("webConsoleSync.selectedDescription", { count: webConsoleSyncTargets?.length ?? 0 })} + {t(webConsoleSyncTargets === "all" ? "webConsoleSync.allDescription" : "webConsoleSync.selectedDescription")} +
+

{t("webConsoleSync.strategyTitle")}

+
+ + +
+

{t(webConsoleSyncStrategy === "missing" ? "webConsoleSync.missingStrategyDescription" : "webConsoleSync.allStrategyDescription")}

+
{t("common.cancel")} - { event.preventDefault(); if (webConsoleSyncTargets === "all") webConsoleSyncMutation.mutate({ all: true }); else if (webConsoleSyncTargets) webConsoleSyncMutation.mutate({ ids: webConsoleSyncTargets }); }}> - {webConsoleSyncMutation.isPending ? <>{webConsoleSyncProgress ? {webConsoleSyncProgress.completed} / {webConsoleSyncProgress.total} : t("common.loading")} : t(webConsoleSyncTargets === "all" ? "webConsoleSync.allAction" : "webConsoleSync.action")} + { event.preventDefault(); if (webConsoleSyncTargets === "all") webConsoleSyncMutation.mutate({ all: true, strategy: webConsoleSyncStrategy }); else if (webConsoleSyncTargets) webConsoleSyncMutation.mutate({ ids: webConsoleSyncTargets, strategy: webConsoleSyncStrategy }); }}> + {webConsoleSyncMutation.isPending ? <>{webConsoleSyncProgress ? {webConsoleSyncProgress.completed} / {webConsoleSyncProgress.total} : t("common.loading")} : t(webConsoleSyncStrategy === "missing" ? "webConsoleSync.syncMissing" : "webConsoleSync.syncAll")}
@@ -740,12 +761,20 @@ export function AccountsPage() { {t(conversionTargets === "all" ? "accountBulk.convertAllToBuildTitle" : "accounts.convertToBuildTitle")} - {conversionTargets === "all" ? t("accountBulk.convertAllToBuildDescription") : t("accounts.convertToBuildDescription", { count: conversionTargets?.length ?? 0 })} + {t(conversionTargets === "all" ? "accountBulk.convertAllToBuildDescription" : "accountBulk.selectedDescription")} +
+

{t("accountBulk.strategyTitle")}

+
+ + +
+

{t(conversionStrategy === "missing" ? "accountBulk.missingStrategyDescription" : "accountBulk.allStrategyDescription")}

+
{t("common.cancel")} - { event.preventDefault(); if (conversionTargets === "all") conversionMutation.mutate({ all: true }); else if (conversionTargets) conversionMutation.mutate({ ids: conversionTargets }); }}> - {conversionMutation.isPending ? <>{activeConversionProgress ? {t(activeConversionProgress.phase === "syncing" ? "accounts.syncingProgress" : "accounts.convertingProgress", activeConversionProgress)} : t("common.loading")} : t(conversionTargets === "all" ? "accountBulk.convertAllToBuild" : "accounts.convertToBuild")} + { event.preventDefault(); if (conversionTargets === "all") conversionMutation.mutate({ all: true, strategy: conversionStrategy }); else if (conversionTargets) conversionMutation.mutate({ ids: conversionTargets, strategy: conversionStrategy }); }}> + {conversionMutation.isPending ? <>{activeConversionProgress ? {t(activeConversionProgress.phase === "syncing" ? "accounts.syncingProgress" : "accounts.convertingProgress", activeConversionProgress)} : t("common.loading")} : t(conversionStrategy === "missing" ? "accountBulk.convertMissing" : "accountBulk.convertAll")}
diff --git a/frontend/src/features/dashboard/dashboard-page.tsx b/frontend/src/features/dashboard/dashboard-page.tsx index cd5c29ab..c5ac9b75 100644 --- a/frontend/src/features/dashboard/dashboard-page.tsx +++ b/frontend/src/features/dashboard/dashboard-page.tsx @@ -1,6 +1,6 @@ import { useQuery } from "@tanstack/react-query"; import { Activity, Box, CircleDollarSign, RefreshCw, Users } from "lucide-react"; -import { useRef, useState, type ReactNode } from "react"; +import { useEffect, useRef, useState, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { Area, Bar, CartesianGrid, ComposedChart, Line, XAxis, YAxis } from "recharts"; @@ -13,12 +13,17 @@ import { ErrorState } from "@/shared/components/data-state"; import { PeriodSelector } from "@/shared/components/period-selector"; import { cn } from "@/shared/lib/cn"; import { formatDateTime, formatNumber } from "@/shared/lib/format"; -import { toPeriodValue, type PeriodDays } from "@/shared/lib/period"; +import { PERIOD_DAYS, toPeriodValue, type PeriodDays } from "@/shared/lib/period"; const USD_TICKS = 10_000_000_000; type TrendMetric = "tokens" | "billing"; +type DashboardPreferences = { periodDays: PeriodDays; trendMetric: TrendMetric }; + +const DASHBOARD_PREFERENCES_KEY = "grok2api:dashboard-preferences"; +const DEFAULT_DASHBOARD_PREFERENCES: DashboardPreferences = { periodDays: 30, trendMetric: "tokens" }; + const MODEL_CHART_COLORS = [ { light: "oklch(0.76 0.1 205)", dark: "oklch(0.72 0.1 205)" }, { light: "oklch(0.77 0.1 160)", dark: "oklch(0.73 0.1 160)" }, @@ -35,12 +40,15 @@ const MODEL_CHART_COLORS = [ export function DashboardPage() { const { t, i18n } = useTranslation(); const { admin } = useAuth(); - const [periodDays, setPeriodDays] = useState(30); - const [trendMetric, setTrendMetric] = useState("tokens"); + const [preferences, setPreferences] = useState(readDashboardPreferences); + const { periodDays, trendMetric } = preferences; const [manualRefreshing, setManualRefreshing] = useState(false); const forceRefresh = useRef(false); const period: DashboardPeriod = toPeriodValue(periodDays); const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + useEffect(() => { + saveDashboardPreferences(preferences); + }, [preferences]); const dashboardQuery = useQuery({ queryKey: ["dashboard", period, timezone], queryFn: () => getDashboard(period, timezone, forceRefresh.current), @@ -88,7 +96,7 @@ export function DashboardPage() {

{t("dashboard.usage")}

- + setPreferences((current) => ({ ...current, periodDays: value }))} ariaLabel={t("dashboard.usage")} />
@@ -100,13 +108,36 @@ export function DashboardPage() { - + setPreferences((current) => ({ ...current, trendMetric: value }))} locale={i18n.language} loading={loading} /> ); } +function readDashboardPreferences(): DashboardPreferences { + if (typeof window === "undefined") return DEFAULT_DASHBOARD_PREFERENCES; + try { + const value: unknown = JSON.parse(window.localStorage.getItem(DASHBOARD_PREFERENCES_KEY) ?? "null"); + if (!value || typeof value !== "object") return DEFAULT_DASHBOARD_PREFERENCES; + const candidate = value as Record; + const periodDays = PERIOD_DAYS.find((days) => days === candidate.periodDays); + const trendMetric = candidate.trendMetric; + if (periodDays === undefined || (trendMetric !== "tokens" && trendMetric !== "billing")) return DEFAULT_DASHBOARD_PREFERENCES; + return { periodDays, trendMetric }; + } catch { + return DEFAULT_DASHBOARD_PREFERENCES; + } +} + +function saveDashboardPreferences(value: DashboardPreferences): void { + try { + window.localStorage.setItem(DASHBOARD_PREFERENCES_KEY, JSON.stringify(value)); + } catch { + return; + } +} + function MetricCard({ icon, label, value, detail, loading }: { icon: ReactNode; label: string; value: string; detail: string; loading: boolean }) { return (
diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index d38d8722..5238bf5d 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -11,7 +11,7 @@ export type SettingsConfigDTO = { recoveryBackoffBase: string; recoveryBackoffMax: string; }; providerConsole: { baseURL: string; userAgent: string; chatTimeout: string }; - batch: { importConcurrency: number; conversionConcurrency: number; syncConcurrency: number; refreshConcurrency: number; randomDelay: string }; + batch: { accountTaskBatchSize: number; importConcurrency: number; conversionConcurrency: number; syncConcurrency: number; refreshConcurrency: number; randomDelay: string }; media: { maxImageBytes: number; maxTotalBytes: number; cleanupThresholdPercent: number; cleanupInterval: string; @@ -51,7 +51,7 @@ const settingsConfigValidator = hasShape({ statsigMode: isOneOf("manual", "url"), statsigManualValue: isOptional(isString), statsigManualConfigured: isBoolean, statsigSignerURL: isString, mediaConcurrency: isNumber, allowNSFW: isBoolean, recoveryBackoffBase: isString, recoveryBackoffMax: isString, }), - batch: hasShape({ importConcurrency: isNumber, conversionConcurrency: isNumber, syncConcurrency: isNumber, refreshConcurrency: isNumber, randomDelay: isString }), + batch: hasShape({ accountTaskBatchSize: isNumber, importConcurrency: isNumber, conversionConcurrency: isNumber, syncConcurrency: isNumber, refreshConcurrency: isNumber, randomDelay: isString }), media: hasShape({ maxImageBytes: isNumber, maxTotalBytes: isNumber, cleanupThresholdPercent: isNumber, cleanupInterval: isString }), frontend: hasShape({ publicApiBaseURL: isString }), routing: hasShape({ stickyTTL: isString, cooldownBase: isString, cooldownMax: isString, capacityWait: isString, maxAttempts: isNumber }), diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index 7cb2353f..75fd8761 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -78,6 +78,7 @@ export const settingsSchema = z.object({ chatTimeout: consoleChatDuration, }), batch: z.object({ + accountTaskBatchSize: positiveInteger.max(1_000), importConcurrency: positiveInteger.max(50), conversionConcurrency: positiveInteger.max(50), syncConcurrency: positiveInteger.max(50), diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index 4cf4763d..c778b689 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -166,6 +166,7 @@ export function SettingsPage() {
+ diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index fb7724c6..b96cff3e 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -8,16 +8,31 @@ const resources = { accountBulk: { convertAllToBuild: "转换为 Build", convertAllToBuildTitle: "转换所有 Grok Web 账号?", - convertAllToBuildDescription: "将转换号池内全部尚未关联 Grok Build 的账号,最多处理 1000 个,并按系统配置的并发度执行。", + convertAllToBuildDescription: "为完整 Web 号池选择转换范围,任务将按后台批次执行。", + selectedDescription: "为所选 Web 账号选择转换范围;任务进度只统计实际待转换账号。", + strategyTitle: "转换范围", + missingStrategy: "仅转换缺失", + missingStrategyDescription: "只为尚未关联 Build 的 Web 账号执行 Device OAuth;已关联账号直接跳过。", + allStrategy: "重新转换全部", + allStrategyDescription: "为全部目标重新执行 Device OAuth,并更新已有 Build 凭据。", + convertMissing: "转换缺失账号", + convertAll: "重新转换全部", }, webConsoleSync: { action: "转换为 Console", allAction: "转换为 Console", selectedTitle: "将所选 Web 账号同步到 Console?", - selectedDescription: "将复用所选 {{count}} 个 Web 账号的 SSO 创建或更新 Console 账号。", + selectedDescription: "为所选 Web 账号选择同步范围;任务进度只统计实际待同步账号。", allTitle: "将全部 Web 账号同步到 Console?", - allDescription: "将复用完整 Web 号池的 SSO 创建或更新 Console 账号,已有账号会幂等更新。", - completed: "同步完成:新增 {{created}},更新 {{updated}},初始同步成功 {{synced}},失败 {{syncFailed}}", + allDescription: "为完整 Web 号池选择同步范围,任务将按后台批次执行。", + strategyTitle: "同步范围", + missingStrategy: "仅同步缺失", + missingStrategyDescription: "只创建尚无对应 Console 账号的 SSO;已有账号直接跳过。", + allStrategy: "重新同步全部", + allStrategyDescription: "创建缺失账号,并重新写入已有 Console 账号。", + syncMissing: "同步缺失账号", + syncAll: "重新同步全部", + completed: "同步完成:新增 {{created}},更新 {{updated}},跳过 {{skipped}},初始同步成功 {{synced}},失败 {{syncFailed}}", }, console: { name: "Grok Console", @@ -229,7 +244,7 @@ const resources = { connectAccount: "账号接入", convertToBuild: "转换为 Build", convertToBuildTitle: "将 Grok Web 账号转换为 Grok Build?", - convertToBuildDescription: "将使用所选 {{count}} 个账号的 SSO 自动完成 Device OAuth。已关联账号会跳过,转换过程可能需要一些时间。", + convertToBuildDescription: "为所选 Web 账号选择转换范围;任务进度只统计实际待转换账号。", convertingProgress: "转换 {{completed}} / {{total}}", syncingProgress: "同步 {{completed}} / {{total}}", conversionCompleted: "转换完成:新增 {{created}},关联现有 {{linked}},跳过 {{skipped}},失败 {{failed}}", @@ -533,7 +548,7 @@ const resources = { groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略" }, provider: { title: "Grok Build", baseURL: "上游地址", clientVersion: "客户端版本", clientIdentifier: "客户端标识", tokenAuth: "Token Auth", userAgent: "User-Agent", recommendedVersion: "推荐 {{version}}", syncRecommendedVersion: "同步推荐版本", recommendedVersionApplied: "已是推荐版本", syncRecommendedVersionDescription: "填入后端当前已完成兼容回归的版本和 User-Agent,保存后生效。" }, web: { title: "Grok Web", baseURL: "上游地址", statsigMode: "x-statsig 获取方式", statsigManual: "手动填写", statsigURL: "URL 获取", statsigValue: "x-statsig-id", statsigConfigured: "已配置", statsigKeepConfigured: "留空保持当前配置", statsigValuePlaceholder: "粘贴 x-statsig-id", statsigSignerURL: "签名服务 URL", quotaTimeout: "额度请求超时", chatTimeout: "聊天超时", imageTimeout: "图片超时", videoTimeout: "视频超时", mediaConcurrency: "媒体任务并发", recoveryBackoffBase: "额度恢复退避", recoveryBackoffMax: "额度恢复最大退避", allowNSFW: "允许 NSFW 图片" }, - batch: { title: "批量任务", importConcurrency: "导入同步并发", conversionConcurrency: "账号转换并发", syncConcurrency: "数据同步并发", refreshConcurrency: "凭据刷新并发", randomDelay: "随机延迟上限(ms)" }, + batch: { title: "批量任务", accountTaskBatchSize: "全部任务每批账号数", importConcurrency: "导入同步并发", conversionConcurrency: "账号转换并发", syncConcurrency: "数据同步并发", refreshConcurrency: "凭据刷新并发", randomDelay: "随机延迟上限(ms)" }, media: { title: "媒体存储", maxImageSize: "单张图片上限", maxTotalSize: "媒体存储上限", cleanupThresholdPercent: "自动清理阈值", cleanupInterval: "容量检查间隔", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时使用 config.yaml 配置;仍为空则使用 http://127.0.0.1:8000。" }, egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 与 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H,可携带用户名和密码。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败" }, routing: { title: "路由策略", stickyTTL: "会话粘性时长", cooldownBase: "基础冷却时间", cooldownMax: "最大冷却时间", capacityWait: "账号满载等待", maxAttempts: "最大尝试次数" }, @@ -749,16 +764,31 @@ const resources = { accountBulk: { convertAllToBuild: "Convert to Build", convertAllToBuildTitle: "Convert all Grok Web accounts?", - convertAllToBuildDescription: "Convert up to 1000 pool accounts that are not linked to Grok Build, using the configured concurrency limit.", + convertAllToBuildDescription: "Choose the conversion scope for the complete Web pool. The task runs in backend-managed batches.", + selectedDescription: "Choose the conversion scope for the selected Web accounts. Progress counts only accounts that need conversion.", + strategyTitle: "Conversion scope", + missingStrategy: "Missing only", + missingStrategyDescription: "Run Device OAuth only for Web accounts without a Build link and skip linked accounts.", + allStrategy: "Reconvert all", + allStrategyDescription: "Run Device OAuth for every target and update existing Build credentials.", + convertMissing: "Convert missing accounts", + convertAll: "Reconvert all", }, webConsoleSync: { action: "Convert to Console", allAction: "Convert to Console", selectedTitle: "Sync selected Web accounts to Console?", - selectedDescription: "Reuse the SSO credentials from {{count}} selected Web accounts to create or update Console accounts.", + selectedDescription: "Choose the sync scope for the selected Web accounts. Progress counts only accounts that need syncing.", allTitle: "Sync all Web accounts to Console?", - allDescription: "Reuse the complete Web pool to create or idempotently update Console accounts.", - completed: "Sync complete: {{created}} created, {{updated}} updated, {{synced}} initial syncs succeeded, {{syncFailed}} failed", + allDescription: "Choose the sync scope for the complete Web pool. The task runs in backend-managed batches.", + strategyTitle: "Sync scope", + missingStrategy: "Missing only", + missingStrategyDescription: "Create SSO accounts that are absent from Console and skip existing accounts.", + allStrategy: "Resync all", + allStrategyDescription: "Create missing accounts and rewrite existing Console accounts.", + syncMissing: "Sync missing accounts", + syncAll: "Resync all", + completed: "Sync complete: {{created}} created, {{updated}} updated, {{skipped}} skipped, {{synced}} initial syncs succeeded, {{syncFailed}} failed", }, console: { name: "Grok Console", @@ -791,7 +821,7 @@ const resources = { 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" }, 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", 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", resourcesTitle: "Resource status", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 models", model: "Model", share: "Call share", noTopModels: "No model calls 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", 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: "The selected {{count}} accounts will use SSO to complete Device OAuth automatically. Linked accounts are skipped and 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 directly. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export all accounts", exported: "Account credentials exported", exportTitle: "Export all account credentials?", exportDescription: "The exported JSON contains OAuth credentials that can access the upstream service. Store it only in a trusted location and never upload, share, or commit it to version control.", 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}}", 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", 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", 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: "Open 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?" }, + 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 directly. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export all accounts", exported: "Account credentials exported", exportTitle: "Export all account credentials?", exportDescription: "The exported JSON contains OAuth credentials that can access the upstream service. Store it only in a trusted location and never upload, share, or commit it to version control.", 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}}", 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", 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", 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: "Open 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?" }, models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes.", 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: "When enabled, only selected accounts are routed and treated as manually confirmed to support the model. Otherwise model sync decides automatically.", 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.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", 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: { @@ -884,7 +914,24 @@ const resources = { errorFrameCount_one: "{{count}} error frame", errorFrameCount_other: "{{count}} error frames", }, - settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use config.yaml; if that is also empty, http://127.0.0.1:8000 is used." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, + settings: { + title: "Runtime settings", + description: "Manage hot-reloadable gateway runtime parameters.", + saved: "Settings saved and applied", + restartRequired: "Restart required", + invalidValue: "Enter a valid value", + durationUnit: "Duration unit", + groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, + provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, + web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, + batch: { title: "Batch tasks", accountTaskBatchSize: "Accounts per all-task batch", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, + media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use config.yaml; if that is also empty, http://127.0.0.1:8000 is used." }, + egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, + routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, + audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, + clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, + units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" }, + }, docs: { title: "API documentation", description: "OpenAI Responses compatibility, account routing, and conversation-state behavior for this gateway.",