mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge pull request #635 from piexian/fix/console-batch-audit-dashboard
feat: 完善账号批处理:同步策略、候选预筛与任务进度
This commit is contained in:
14 files changed
+992
-122
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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,88 @@ 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())
|
||||
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 != 2 {
|
||||
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
|
||||
}
|
||||
@@ -50,6 +50,7 @@ const (
|
||||
credentialImportChunkSize = 100
|
||||
maxBuildConversionAccounts = 1000
|
||||
maxWebConsoleSyncAccounts = 1000
|
||||
accountTaskBatchSize = 1000
|
||||
)
|
||||
|
||||
type webQuotaRefreshState struct {
|
||||
@@ -122,9 +123,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 在单个账号任务结束后报告批次完成数。
|
||||
@@ -731,10 +747,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 +780,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 := accountTaskBatchSize
|
||||
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 +879,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 := accountTaskBatchSize
|
||||
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 +1034,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 +1099,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 +1107,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 +1122,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 +1149,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)
|
||||
}
|
||||
@@ -1882,6 +2064,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)
|
||||
|
||||
@@ -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,88 @@ 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())
|
||||
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 != 2 {
|
||||
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,
|
||||
|
||||
@@ -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,33 @@ 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) Summarize(ctx context.Context, now time.Time) ([]repository.AccountSummary, error) {
|
||||
var rows []repository.AccountSummary
|
||||
selectFields := `
|
||||
@@ -257,20 +285,111 @@ 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 ? AND provider = ?", ids, account.ProviderWeb).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 ? AND provider = ?", ids, account.ProviderWeb).
|
||||
Where(missingConsoleAccountPredicate, 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) {
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -170,12 +170,52 @@ 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, unlinkedWeb.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(consoleCandidates) != 1 || consoleCandidates[0].ID != unlinkedWeb.ID {
|
||||
t.Fatalf("console sync candidates = %#v", consoleCandidates)
|
||||
}
|
||||
if _, err := repo.ListMissingConsoleSyncAccounts(ctx, []uint64{build.ID}); !errors.Is(err, repository.ErrNotFound) {
|
||||
t.Fatalf("non-web console candidate error = %v", err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
otherBuild, _, err := repo.UpsertByIdentity(ctx, account.Credential{Provider: account.ProviderBuild, Name: "build-2", SourceKey: "build-2", EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive})
|
||||
if err != nil {
|
||||
|
||||
@@ -23,10 +23,19 @@ 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)
|
||||
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)
|
||||
|
||||
@@ -142,6 +142,7 @@ func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
router.POST("/accounts/refresh-billing", h.refreshAllBilling)
|
||||
router.POST("/accounts/refresh-tokens", h.refreshAllTokens)
|
||||
router.POST("/accounts/batch/refresh-billing", h.batchRefreshBilling)
|
||||
router.POST("/accounts/batch/refresh-quotas", h.batchRefreshQuotas)
|
||||
router.PATCH("/accounts/batch", h.batchUpdate)
|
||||
router.DELETE("/accounts", h.batchDelete)
|
||||
router.PATCH("/accounts/:id", h.update)
|
||||
@@ -173,9 +174,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 +215,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,15 +417,48 @@ 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 批量同步")
|
||||
}
|
||||
if request.Provider != string(accountdomain.ProviderBuild) {
|
||||
response.Error(c, http.StatusBadRequest, "invalidProvider", "仅 Grok Build 账号支持 Billing 同步")
|
||||
return
|
||||
}
|
||||
if !h.validateProviderIDs(c, ids, request.Provider) {
|
||||
return
|
||||
}
|
||||
succeeded, failed, err := h.service.BatchRefreshBilling(c.Request.Context(), ids)
|
||||
if err != nil {
|
||||
h.writeServiceError(c, "billingBatchRefreshFailed", err, http.StatusBadGateway, "批量同步账号额度失败")
|
||||
h.writeServiceError(c, "billingBatchRefreshFailed", err, http.StatusBadGateway, "批量同步 Billing 失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, gin.H{"succeeded": succeeded, "failed": failed})
|
||||
}
|
||||
|
||||
func (h *Handler) batchRefreshQuotas(c *gin.Context) {
|
||||
var request batchDeleteRequest
|
||||
if c.ShouldBindJSON(&request) != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效")
|
||||
return
|
||||
}
|
||||
ids, err := parseIDs(request.IDs)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "invalidId", err.Error())
|
||||
return
|
||||
}
|
||||
providerValue := accountdomain.Provider(request.Provider)
|
||||
if !providerValue.IsValid() {
|
||||
response.Error(c, http.StatusBadRequest, "invalidProvider", "账号来源无效")
|
||||
return
|
||||
}
|
||||
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, "quotaBatchRefreshFailed", err, http.StatusBadGateway, "批量同步账号额度失败")
|
||||
return
|
||||
}
|
||||
response.Success(c, http.StatusOK, gin.H{"succeeded": succeeded, "failed": failed})
|
||||
@@ -486,7 +528,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 +537,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
|
||||
@@ -503,12 +552,15 @@ func (h *Handler) convertWebToBuild(c *gin.Context) {
|
||||
response.Error(c, http.StatusBadRequest, "invalidId", err.Error())
|
||||
return
|
||||
}
|
||||
if !h.validateProviderIDs(c, ids, string(accountdomain.ProviderWeb)) {
|
||||
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 +569,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
|
||||
@@ -525,57 +584,60 @@ func (h *Handler) syncWebToConsole(c *gin.Context) {
|
||||
response.Error(c, http.StatusBadRequest, "invalidId", err.Error())
|
||||
return
|
||||
}
|
||||
if !h.validateProviderIDs(c, ids, string(accountdomain.ProviderWeb)) {
|
||||
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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<BuildConversionResultDTO & AccountTaskProgressDTO & AccountTokenRefreshResultDTO & AccountImportResultDTO> & {
|
||||
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<AccountImportResultDTO> {
|
||||
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<WebConsoleSyncResultDTO> {
|
||||
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<AccountImportResultDTO> {
|
||||
@@ -386,8 +394,8 @@ 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 }> {
|
||||
return apiRequest("/api/admin/v1/accounts/batch/refresh-billing", { method: "POST", body: { ids, provider } }, createObjectDecoder("account batch", { succeeded: isNumber, failed: isNumber }));
|
||||
export function refreshAccountsQuota(ids: string[], provider: AccountProvider): Promise<{ succeeded: number; failed: number }> {
|
||||
return apiRequest("/api/admin/v1/accounts/batch/refresh-quotas", { method: "POST", body: { ids, provider } }, createObjectDecoder("account batch", { succeeded: isNumber, failed: isNumber }));
|
||||
}
|
||||
|
||||
export function deleteAccounts(ids: string[], provider: AccountProvider): Promise<{ deleted: number }> {
|
||||
|
||||
@@ -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 [quotaSyncProgress, setQuotaSyncProgress] = useState<AccountTaskProgressDTO | null>(null);
|
||||
const [conversionTargets, setConversionTargets] = useState<string[] | "all" | null>(null);
|
||||
const [conversionStrategy, setConversionStrategy] = useState<BuildConversionStrategy>("missing");
|
||||
const [conversionProgress, setConversionProgress] = useState<BuildConversionProgressState | null>(null);
|
||||
const [webConsoleSyncTargets, setWebConsoleSyncTargets] = useState<string[] | "all" | null>(null);
|
||||
const [webConsoleSyncStrategy, setWebConsoleSyncStrategy] = useState<"missing" | "all">("missing");
|
||||
const [webConsoleSyncProgress, setWebConsoleSyncProgress] = useState<AccountTaskProgressDTO | null>(null);
|
||||
const [renewAllOpen, setRenewAllOpen] = useState(false);
|
||||
const [renewalProgress, setRenewalProgress] = useState<AccountTaskProgressDTO | null>(null);
|
||||
@@ -236,7 +239,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 }));
|
||||
@@ -336,7 +339,7 @@ export function AccountsPage() {
|
||||
});
|
||||
|
||||
const batchBillingMutation = useMutation({
|
||||
mutationFn: () => refreshAccountsBilling([...selected], provider),
|
||||
mutationFn: () => refreshAccountsQuota([...selected], provider),
|
||||
onSuccess: (result) => {
|
||||
setSelected(new Set());
|
||||
invalidateAccountData();
|
||||
@@ -415,6 +418,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<void> {
|
||||
setDeviceOpen(true);
|
||||
setDeviceStatus("starting");
|
||||
@@ -573,15 +586,15 @@ export function AccountsPage() {
|
||||
<span className="mr-1 text-xs text-muted-foreground">{t("common.selectedCount", { count: selected.size })}</span>
|
||||
<Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => batchUpdateMutation.mutate(true)}>{t("common.enable")}</Button>
|
||||
<Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => batchUpdateMutation.mutate(false)}>{t("common.disable")}</Button>
|
||||
{provider === "grok_web" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setConversionTargets([...selected])}>{t("accounts.convertToBuild")}</Button> : null}
|
||||
{provider === "grok_web" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setWebConsoleSyncTargets([...selected])}>{t("webConsoleSync.action")}</Button> : null}
|
||||
{provider === "grok_build" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => batchBillingMutation.mutate()}>{t("accounts.refreshBilling")}</Button> : null}
|
||||
{provider === "grok_web" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => openBuildConversion([...selected])}>{t("accounts.convertToBuild")}</Button> : null}
|
||||
{provider === "grok_web" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => openWebConsoleSync([...selected])}>{t("webConsoleSync.action")}</Button> : null}
|
||||
<Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => batchBillingMutation.mutate()}>{t("accountCredential.quotaSyncAction")}</Button>
|
||||
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" disabled={bulkTaskPending} onClick={() => setBatchDeleteOpen(true)}>{t("common.delete")}</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setConversionTargets("all")}>{t("accountBulk.convertAllToBuild")}</Button> : null}
|
||||
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setWebConsoleSyncTargets("all")}>{t("webConsoleSync.allAction")}</Button> : null}
|
||||
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => openBuildConversion("all")}>{t("accountBulk.convertAllToBuild")}</Button> : null}
|
||||
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => openWebConsoleSync("all")}>{t("webConsoleSync.allAction")}</Button> : null}
|
||||
{hasProviderAccounts ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setSyncAllOpen(true)}>{t("accountCredential.quotaSyncAction")}</Button> : null}
|
||||
{hasProviderAccounts && provider === "grok_build" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setRenewAllOpen(true)}>{t("accountCredential.refreshAction")}</Button> : null}
|
||||
<DropdownMenu>
|
||||
@@ -675,8 +688,8 @@ export function AccountsPage() {
|
||||
<DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="size-8" aria-label={t("common.actions")}><MoreHorizontal /></Button></DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => beginEdit(account)}><Pencil />{t("common.edit")}</DropdownMenuItem>
|
||||
{provider === "grok_web" && !account.linkedAccountId ? <DropdownMenuItem onClick={() => setConversionTargets([account.id])}><ArrowRight />{t("accounts.convertToBuild")}</DropdownMenuItem> : null}
|
||||
{provider === "grok_web" ? <DropdownMenuItem onClick={() => setWebConsoleSyncTargets([account.id])}><ArrowRight />{t("webConsoleSync.action")}</DropdownMenuItem> : null}
|
||||
{provider === "grok_web" ? <DropdownMenuItem onClick={() => openBuildConversion([account.id])}><ArrowRight />{t("accounts.convertToBuild")}</DropdownMenuItem> : null}
|
||||
{provider === "grok_web" ? <DropdownMenuItem onClick={() => openWebConsoleSync([account.id])}><ArrowRight />{t("webConsoleSync.action")}</DropdownMenuItem> : null}
|
||||
{provider === "grok_build" ? <DropdownMenuItem onClick={() => tokenMutation.mutate(account.id)}><RotateCw />{t("accounts.refreshToken")}</DropdownMenuItem> : null}
|
||||
<DropdownMenuItem onClick={() => provider === "grok_build" ? billingMutation.mutate(account.id) : quotaMutation.mutate(account.id)}><RefreshCw />{provider === "grok_build" ? t("accounts.refreshBilling") : t("accounts.refreshModeQuota")}</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
@@ -704,12 +717,20 @@ export function AccountsPage() {
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t(webConsoleSyncTargets === "all" ? "webConsoleSync.allTitle" : "webConsoleSync.selectedTitle")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{webConsoleSyncTargets === "all" ? t("webConsoleSync.allDescription") : t("webConsoleSync.selectedDescription", { count: webConsoleSyncTargets?.length ?? 0 })}</AlertDialogDescription>
|
||||
<AlertDialogDescription>{t(webConsoleSyncTargets === "all" ? "webConsoleSync.allDescription" : "webConsoleSync.selectedDescription")}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="space-y-2">
|
||||
<p id="web-console-sync-strategy" className="text-xs font-medium">{t("webConsoleSync.strategyTitle")}</p>
|
||||
<div role="radiogroup" aria-labelledby="web-console-sync-strategy" className="grid grid-cols-2 rounded-md bg-muted p-1">
|
||||
<Button type="button" role="radio" aria-checked={webConsoleSyncStrategy === "missing"} variant={webConsoleSyncStrategy === "missing" ? "secondary" : "ghost"} size="sm" className="h-8 rounded-sm px-3 text-xs font-normal shadow-none" onClick={() => setWebConsoleSyncStrategy("missing")}>{t("webConsoleSync.missingStrategy")}</Button>
|
||||
<Button type="button" role="radio" aria-checked={webConsoleSyncStrategy === "all"} variant={webConsoleSyncStrategy === "all" ? "secondary" : "ghost"} size="sm" className="h-8 rounded-sm px-3 text-xs font-normal shadow-none" onClick={() => setWebConsoleSyncStrategy("all")}>{t("webConsoleSync.allStrategy")}</Button>
|
||||
</div>
|
||||
<p className="min-h-8 text-xs text-muted-foreground">{t(webConsoleSyncStrategy === "missing" ? "webConsoleSync.missingStrategyDescription" : "webConsoleSync.allStrategyDescription")}</p>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction disabled={webConsoleSyncMutation.isPending || webConsoleSyncTargets === null || (Array.isArray(webConsoleSyncTargets) && webConsoleSyncTargets.length === 0)} onClick={(event) => { event.preventDefault(); if (webConsoleSyncTargets === "all") webConsoleSyncMutation.mutate({ all: true }); else if (webConsoleSyncTargets) webConsoleSyncMutation.mutate({ ids: webConsoleSyncTargets }); }}>
|
||||
{webConsoleSyncMutation.isPending ? <><Spinner />{webConsoleSyncProgress ? <span className="tabular-nums">{webConsoleSyncProgress.completed} / {webConsoleSyncProgress.total}</span> : t("common.loading")}</> : t(webConsoleSyncTargets === "all" ? "webConsoleSync.allAction" : "webConsoleSync.action")}
|
||||
<AlertDialogAction disabled={webConsoleSyncMutation.isPending || webConsoleSyncTargets === null || (Array.isArray(webConsoleSyncTargets) && webConsoleSyncTargets.length === 0)} onClick={(event) => { event.preventDefault(); if (webConsoleSyncTargets === "all") webConsoleSyncMutation.mutate({ all: true, strategy: webConsoleSyncStrategy }); else if (webConsoleSyncTargets) webConsoleSyncMutation.mutate({ ids: webConsoleSyncTargets, strategy: webConsoleSyncStrategy }); }}>
|
||||
{webConsoleSyncMutation.isPending ? <><Spinner />{webConsoleSyncProgress ? <span className="tabular-nums">{webConsoleSyncProgress.completed} / {webConsoleSyncProgress.total}</span> : t("common.loading")}</> : t(webConsoleSyncStrategy === "missing" ? "webConsoleSync.syncMissing" : "webConsoleSync.syncAll")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
@@ -719,12 +740,20 @@ export function AccountsPage() {
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t(conversionTargets === "all" ? "accountBulk.convertAllToBuildTitle" : "accounts.convertToBuildTitle")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{conversionTargets === "all" ? t("accountBulk.convertAllToBuildDescription") : t("accounts.convertToBuildDescription", { count: conversionTargets?.length ?? 0 })}</AlertDialogDescription>
|
||||
<AlertDialogDescription>{t(conversionTargets === "all" ? "accountBulk.convertAllToBuildDescription" : "accountBulk.selectedDescription")}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="space-y-2">
|
||||
<p id="web-build-conversion-strategy" className="text-xs font-medium">{t("accountBulk.strategyTitle")}</p>
|
||||
<div role="radiogroup" aria-labelledby="web-build-conversion-strategy" className="grid grid-cols-2 rounded-md bg-muted p-1">
|
||||
<Button type="button" role="radio" aria-checked={conversionStrategy === "missing"} variant={conversionStrategy === "missing" ? "secondary" : "ghost"} size="sm" className="h-8 rounded-sm px-3 text-xs font-normal shadow-none" onClick={() => setConversionStrategy("missing")}>{t("accountBulk.missingStrategy")}</Button>
|
||||
<Button type="button" role="radio" aria-checked={conversionStrategy === "all"} variant={conversionStrategy === "all" ? "secondary" : "ghost"} size="sm" className="h-8 rounded-sm px-3 text-xs font-normal shadow-none" onClick={() => setConversionStrategy("all")}>{t("accountBulk.allStrategy")}</Button>
|
||||
</div>
|
||||
<p className="min-h-8 text-xs text-muted-foreground">{t(conversionStrategy === "missing" ? "accountBulk.missingStrategyDescription" : "accountBulk.allStrategyDescription")}</p>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction disabled={conversionMutation.isPending || conversionTargets === null || (Array.isArray(conversionTargets) && conversionTargets.length === 0)} onClick={(event) => { event.preventDefault(); if (conversionTargets === "all") conversionMutation.mutate({ all: true }); else if (conversionTargets) conversionMutation.mutate({ ids: conversionTargets }); }}>
|
||||
{conversionMutation.isPending ? <><Spinner />{activeConversionProgress ? <span className="whitespace-nowrap tabular-nums">{t(activeConversionProgress.phase === "syncing" ? "accounts.syncingProgress" : "accounts.convertingProgress", activeConversionProgress)}</span> : t("common.loading")}</> : t(conversionTargets === "all" ? "accountBulk.convertAllToBuild" : "accounts.convertToBuild")}
|
||||
<AlertDialogAction disabled={conversionMutation.isPending || conversionTargets === null || (Array.isArray(conversionTargets) && conversionTargets.length === 0)} onClick={(event) => { event.preventDefault(); if (conversionTargets === "all") conversionMutation.mutate({ all: true, strategy: conversionStrategy }); else if (conversionTargets) conversionMutation.mutate({ ids: conversionTargets, strategy: conversionStrategy }); }}>
|
||||
{conversionMutation.isPending ? <><Spinner />{activeConversionProgress ? <span className="whitespace-nowrap tabular-nums">{t(activeConversionProgress.phase === "syncing" ? "accounts.syncingProgress" : "accounts.convertingProgress", activeConversionProgress)}</span> : t("common.loading")}</> : t(conversionStrategy === "missing" ? "accountBulk.convertMissing" : "accountBulk.convertAll")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -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<PeriodDays>(30);
|
||||
const [trendMetric, setTrendMetric] = useState<TrendMetric>("tokens");
|
||||
const [preferences, setPreferences] = useState<DashboardPreferences>(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() {
|
||||
<h2 className="shrink-0 text-sm font-medium">{t("dashboard.usage")}</h2>
|
||||
<div className="flex min-w-0 shrink-0 items-center gap-2">
|
||||
<Button variant="ghost" size="icon" className="size-8 text-muted-foreground" onClick={refreshAll} disabled={dashboardQuery.isFetching || manualRefreshing} aria-label={t("common.refresh")}><RefreshCw className={manualRefreshing ? "animate-spin" : undefined} /></Button>
|
||||
<PeriodSelector value={periodDays} onChange={setPeriodDays} ariaLabel={t("dashboard.usage")} />
|
||||
<PeriodSelector value={periodDays} onChange={(value) => setPreferences((current) => ({ ...current, periodDays: value }))} ariaLabel={t("dashboard.usage")} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -100,13 +108,36 @@ export function DashboardPage() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<TrendPanel dashboard={dashboard} metric={trendMetric} onMetricChange={setTrendMetric} locale={i18n.language} loading={loading} />
|
||||
<TrendPanel dashboard={dashboard} metric={trendMetric} onMetricChange={(value) => setPreferences((current) => ({ ...current, trendMetric: value }))} locale={i18n.language} loading={loading} />
|
||||
|
||||
<TopModels dashboard={dashboard} locale={i18n.language} loading={loading} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<string, unknown>;
|
||||
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 (
|
||||
<div className="min-h-28 rounded-lg bg-card p-4">
|
||||
|
||||
@@ -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 账号。",
|
||||
allTitle: "将全部 Web 账号同步到 Console?",
|
||||
allDescription: "将复用完整 Web 号池的 SSO 创建或更新 Console 账号,已有账号会幂等更新。",
|
||||
completed: "同步完成:新增 {{created}},更新 {{updated}},初始同步成功 {{synced}},失败 {{syncFailed}}",
|
||||
selectedTitle: "将所选 Web 账号转换为 Console?",
|
||||
selectedDescription: "选择所选 Web 账号的转换范围。",
|
||||
allTitle: "将全部 Web 账号转换为 Console?",
|
||||
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}}",
|
||||
@@ -750,16 +765,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.",
|
||||
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",
|
||||
selectedTitle: "Convert selected Web accounts to Console?",
|
||||
selectedDescription: "Choose the conversion scope for the selected Web accounts.",
|
||||
allTitle: "Convert all Web accounts to Console?",
|
||||
allDescription: "Choose the conversion scope. All Web accounts are processed in batches.",
|
||||
strategyTitle: "Conversion scope",
|
||||
missingStrategy: "Missing only",
|
||||
missingStrategyDescription: "Create SSO accounts that are absent from Console and skip existing accounts.",
|
||||
allStrategy: "Reconvert all",
|
||||
allStrategyDescription: "Create missing accounts and rewrite existing Console accounts.",
|
||||
syncMissing: "Convert missing accounts",
|
||||
syncAll: "Reconvert all",
|
||||
completed: "Conversion complete: {{created}} created, {{updated}} updated, {{skipped}} skipped, {{synced}} initialized, {{syncFailed}} failed",
|
||||
},
|
||||
console: {
|
||||
name: "Grok Console",
|
||||
@@ -792,7 +822,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}Line truncated
|
||||
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
Line truncated
|
||||
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: {
|
||||
|
||||
Reference in new issue
Block a user