mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge pull request #797 from AmPlace/agent/selective-account-export
feat(accounts): support selective and paginated credential exports
This commit is contained in:
10 files changed
+444
-36
No files matched your search
@@ -40,12 +40,13 @@ func TestExportCredentialsRoundTripsImportFormat(t *testing.T) {
|
||||
}
|
||||
expiresAt := time.Date(2026, 7, 12, 12, 0, 0, 0, time.UTC)
|
||||
repository := relational.NewAccountRepository(database)
|
||||
if _, _, err := repository.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
created, _, err := repository.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderBuild, Name: "primary", Email: "user@example.com", UserID: "user-1",
|
||||
SourceKey: "export-test", OIDCClientID: "client-1", EncryptedAccessToken: accessToken,
|
||||
EncryptedRefreshToken: refreshToken, ExpiresAt: expiresAt, Enabled: false,
|
||||
AuthStatus: accountdomain.AuthStatusActive, Priority: 1, MaxConcurrent: 8,
|
||||
}); err != nil {
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter := cliprovider.NewAdapter(cliprovider.Config{}, cipher)
|
||||
@@ -55,6 +56,16 @@ func TestExportCredentialsRoundTripsImportFormat(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
selectedResult, err := service.ExportProviderCredentialsByIDs(ctx, accountdomain.ProviderBuild, []uint64{created.ID})
|
||||
if err != nil || selectedResult.Count != 1 {
|
||||
t.Fatalf("selected export result = %#v, error = %v", selectedResult, err)
|
||||
}
|
||||
if _, err := service.ExportProviderCredentialsByIDs(ctx, accountdomain.ProviderWeb, []uint64{created.ID}); err == nil {
|
||||
t.Fatal("expected cross-provider selected export to fail")
|
||||
}
|
||||
if _, err := service.ExportProviderCredentialsCursor(ctx, accountdomain.ProviderBuild, 0, 0, maxCredentialExportAccounts+1); err == nil {
|
||||
t.Fatal("expected oversized export page to fail")
|
||||
}
|
||||
values, err := adapter.ParseImportedCredentials(result.Data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -97,6 +108,91 @@ func TestExportCredentialsRoundTripsImportFormat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportProviderCredentialsCursorKeepsStableSnapshot(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "cursor-export.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)
|
||||
}
|
||||
accessToken, err := cipher.Encrypt("access-token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := relational.NewAccountRepository(database)
|
||||
createAccount := func(name string) accountdomain.Credential {
|
||||
t.Helper()
|
||||
value, _, createErr := repository.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderBuild, Name: name, SourceKey: "cursor-" + name,
|
||||
UserID: name, EncryptedAccessToken: accessToken, Enabled: true,
|
||||
AuthStatus: accountdomain.AuthStatusActive, Priority: 1, MaxConcurrent: 8,
|
||||
})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
return value
|
||||
}
|
||||
first := createAccount("first")
|
||||
second := createAccount("second")
|
||||
third := createAccount("third")
|
||||
adapter := cliprovider.NewAdapter(cliprovider.Config{}, cipher)
|
||||
service := NewService(repository, nil, nil, nil, provider.NewRegistry(adapter), cipher, nil)
|
||||
|
||||
pageOne, err := service.ExportProviderCredentialsCursor(ctx, accountdomain.ProviderBuild, 0, 0, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pageOne.Count != 2 || !pageOne.HasMore || pageOne.NextID != second.ID || pageOne.SnapshotMaxID != third.ID {
|
||||
t.Fatalf("first cursor page = %#v", pageOne)
|
||||
}
|
||||
createAccount("new-after-snapshot")
|
||||
pageTwo, err := service.ExportProviderCredentialsCursor(ctx, accountdomain.ProviderBuild, pageOne.NextID, pageOne.SnapshotMaxID, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
values, err := adapter.ParseImportedCredentials(pageTwo.Data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pageTwo.Count != 1 || pageTwo.HasMore || pageTwo.NextID != third.ID || len(values) != 1 || values[0].Name != "third" {
|
||||
t.Fatalf("second cursor page = %#v, values = %#v", pageTwo, values)
|
||||
}
|
||||
if first.ID >= second.ID || second.ID >= third.ID {
|
||||
t.Fatalf("test account IDs are not monotonic: %d, %d, %d", first.ID, second.ID, third.ID)
|
||||
}
|
||||
if _, err := service.ExportProviderCredentialsCursor(ctx, accountdomain.ProviderBuild, second.ID, 0, 2); err == nil {
|
||||
t.Fatal("expected continuation without snapshot boundary to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCredentialExportCountRejectsPartialReads(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
expected int
|
||||
total int64
|
||||
actual int
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "exact", expected: 2, total: 2, actual: 2},
|
||||
{name: "missing at count", expected: 2, total: 1, actual: 1, wantErr: true},
|
||||
{name: "deleted after count", expected: 2, total: 2, actual: 1, wantErr: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := validateCredentialExportCount(test.expected, test.total, test.actual)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("validateCredentialExportCount() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportProviderCredentialsRoundTripsSSOProviders(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
|
||||
@@ -208,6 +208,13 @@ type ExportResult struct {
|
||||
Count int
|
||||
}
|
||||
|
||||
type ExportPageResult struct {
|
||||
ExportResult
|
||||
NextID uint64
|
||||
SnapshotMaxID uint64
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
type BuildConversionResult struct {
|
||||
Created int
|
||||
Linked int
|
||||
@@ -1670,6 +1677,102 @@ func (s *Service) ExportCredentials(ctx context.Context) (ExportResult, error) {
|
||||
|
||||
// ExportProviderCredentials 导出可由对应 Provider 导入接口重新读取的凭据文档。
|
||||
func (s *Service) ExportProviderCredentials(ctx context.Context, providerValue accountdomain.Provider) (ExportResult, error) {
|
||||
return s.exportProviderCredentials(ctx, providerValue, repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Limit: maxCredentialExportAccounts + 1},
|
||||
Filter: repository.AccountListFilter{Provider: string(providerValue), Now: s.now()},
|
||||
}, true, 0)
|
||||
}
|
||||
|
||||
// ExportProviderCredentialsCursor exports a stable provider batch bounded by
|
||||
// the maximum account ID captured by the first request.
|
||||
func (s *Service) ExportProviderCredentialsCursor(ctx context.Context, providerValue accountdomain.Provider, afterID, snapshotMaxID uint64, limit int) (ExportPageResult, error) {
|
||||
if limit < 1 || limit > maxCredentialExportAccounts {
|
||||
return ExportPageResult{}, invalidInput("单批导出数量必须在 1 到 10000 之间")
|
||||
}
|
||||
if afterID > 0 && snapshotMaxID == 0 {
|
||||
return ExportPageResult{}, invalidInput("继续导出时必须提供快照上界")
|
||||
}
|
||||
if snapshotMaxID > 0 && afterID > snapshotMaxID {
|
||||
return ExportPageResult{}, invalidInput("导出游标不能超过快照上界")
|
||||
}
|
||||
if !providerValue.IsValid() {
|
||||
return ExportPageResult{}, invalidInput("账号来源无效")
|
||||
}
|
||||
if snapshotMaxID == 0 {
|
||||
values, _, err := s.accounts.List(ctx, repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Limit: 1, Sort: repository.SortQuery{Field: "id", Direction: repository.SortDescending}},
|
||||
Filter: repository.AccountListFilter{Provider: string(providerValue), Now: s.now()},
|
||||
})
|
||||
if err != nil {
|
||||
return ExportPageResult{}, err
|
||||
}
|
||||
if len(values) == 0 {
|
||||
result, exportErr := s.marshalProviderCredentials(providerValue, nil)
|
||||
return ExportPageResult{ExportResult: result}, exportErr
|
||||
}
|
||||
snapshotMaxID = values[0].ID
|
||||
}
|
||||
values, total, err := s.accounts.List(ctx, repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Limit: limit, Sort: repository.SortQuery{Field: "id", Direction: repository.SortAscending}},
|
||||
Filter: repository.AccountListFilter{
|
||||
Provider: string(providerValue), AfterID: afterID, ThroughID: snapshotMaxID, Now: s.now(),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return ExportPageResult{}, err
|
||||
}
|
||||
result, err := s.marshalProviderCredentials(providerValue, values)
|
||||
if err != nil {
|
||||
return ExportPageResult{}, err
|
||||
}
|
||||
nextID := afterID
|
||||
if len(values) > 0 {
|
||||
nextID = values[len(values)-1].ID
|
||||
}
|
||||
return ExportPageResult{
|
||||
ExportResult: result, NextID: nextID, SnapshotMaxID: snapshotMaxID, HasMore: total > int64(len(values)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ExportProviderCredentialsByIDs 只导出管理端明确选择且属于指定 Provider 的账号。
|
||||
func (s *Service) ExportProviderCredentialsByIDs(ctx context.Context, providerValue accountdomain.Provider, ids []uint64) (ExportResult, error) {
|
||||
values, err := normalizeIDs(ids, maxCredentialExportAccounts)
|
||||
if err != nil {
|
||||
return ExportResult{}, err
|
||||
}
|
||||
return s.exportProviderCredentials(ctx, providerValue, repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Limit: len(values)},
|
||||
Filter: repository.AccountListFilter{
|
||||
Provider: string(providerValue), AccountIDs: values, RestrictIDs: true, Now: s.now(),
|
||||
},
|
||||
}, false, len(values))
|
||||
}
|
||||
|
||||
func (s *Service) exportProviderCredentials(ctx context.Context, providerValue accountdomain.Provider, query repository.AccountListQuery, enforceTotalLimit bool, expectedCount int) (ExportResult, error) {
|
||||
if !providerValue.IsValid() {
|
||||
return ExportResult{}, invalidInput("账号来源无效")
|
||||
}
|
||||
values, total, err := s.accounts.List(ctx, query)
|
||||
if err != nil {
|
||||
return ExportResult{}, err
|
||||
}
|
||||
if enforceTotalLimit && total > maxCredentialExportAccounts {
|
||||
return ExportResult{}, fmt.Errorf("%w: 单次最多导出 10000 个账号", ErrExportLimit)
|
||||
}
|
||||
if err := validateCredentialExportCount(expectedCount, total, len(values)); err != nil {
|
||||
return ExportResult{}, err
|
||||
}
|
||||
return s.marshalProviderCredentials(providerValue, values)
|
||||
}
|
||||
|
||||
func validateCredentialExportCount(expected int, total int64, actual int) error {
|
||||
if expected > 0 && (total != int64(expected) || actual != expected) {
|
||||
return invalidInput("所选账号包含不存在或不属于当前号池的账号")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) marshalProviderCredentials(providerValue accountdomain.Provider, values []accountdomain.Credential) (ExportResult, error) {
|
||||
if !providerValue.IsValid() {
|
||||
return ExportResult{}, invalidInput("账号来源无效")
|
||||
}
|
||||
@@ -1680,16 +1783,7 @@ func (s *Service) ExportProviderCredentials(ctx context.Context, providerValue a
|
||||
if !ok {
|
||||
return ExportResult{}, fmt.Errorf("Provider %s 不支持凭据导出", providerValue)
|
||||
}
|
||||
values, total, err := s.accounts.List(ctx, repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Limit: maxCredentialExportAccounts + 1},
|
||||
Filter: repository.AccountListFilter{Provider: string(providerValue), Now: s.now()},
|
||||
})
|
||||
if err != nil {
|
||||
return ExportResult{}, err
|
||||
}
|
||||
if total > maxCredentialExportAccounts {
|
||||
return ExportResult{}, fmt.Errorf("%w: 单次最多导出 10000 个账号", ErrExportLimit)
|
||||
}
|
||||
var err error
|
||||
seeds := make([]provider.CredentialSeed, 0, len(values))
|
||||
for _, value := range values {
|
||||
if value.Provider != providerValue {
|
||||
|
||||
@@ -102,11 +102,18 @@ func (r *AccountRepository) List(ctx context.Context, input repository.AccountLi
|
||||
if len(input.Filter.ExcludeIDs) > 0 {
|
||||
query = query.Where("provider_accounts.id NOT IN ?", input.Filter.ExcludeIDs)
|
||||
}
|
||||
if input.Filter.AfterID > 0 {
|
||||
query = query.Where("provider_accounts.id > ?", input.Filter.AfterID)
|
||||
}
|
||||
if input.Filter.ThroughID > 0 {
|
||||
query = query.Where("provider_accounts.id <= ?", input.Filter.ThroughID)
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var rows []accountModel
|
||||
query = applyStableSort(query, input.Page.Sort, map[string]sortSpec{
|
||||
"id": {expression: "provider_accounts.id"},
|
||||
"name": {expression: "LOWER(provider_accounts.name)"},
|
||||
"type": {expression: accountTypeSortExpression},
|
||||
"status": {expression: accountStatusSortExpression},
|
||||
|
||||
@@ -81,6 +81,8 @@ type AccountListFilter struct {
|
||||
AccountIDs []uint64
|
||||
RestrictIDs bool
|
||||
ExcludeIDs []uint64
|
||||
AfterID uint64
|
||||
ThroughID uint64
|
||||
Now time.Time
|
||||
}
|
||||
|
||||
|
||||
@@ -135,6 +135,7 @@ func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
router.GET("/accounts", h.list)
|
||||
router.GET("/accounts/summary", h.summary)
|
||||
router.GET("/accounts/export", h.exportCredentials)
|
||||
router.POST("/accounts/export", h.exportSelectedCredentials)
|
||||
router.GET("/accounts/:id", h.get)
|
||||
router.POST("/accounts/device/start", h.startDevice)
|
||||
router.POST("/accounts/device/:sessionId/poll", h.pollDevice)
|
||||
@@ -195,6 +196,11 @@ type batchDeleteRequest struct {
|
||||
LinkedDeleteTargets []string `json:"linkedDeleteTargets"`
|
||||
}
|
||||
|
||||
type credentialExportRequest struct {
|
||||
IDs []string `json:"ids" binding:"required"`
|
||||
Provider string `json:"provider" binding:"required"`
|
||||
}
|
||||
|
||||
type deletionPreviewRequest struct {
|
||||
IDs []string `json:"ids" binding:"required"`
|
||||
Provider string `json:"provider" binding:"required"`
|
||||
@@ -1082,14 +1088,70 @@ func (h *Handler) refreshWebQuota(c *gin.Context) {
|
||||
|
||||
func (h *Handler) exportCredentials(c *gin.Context) {
|
||||
providerValue := accountdomain.Provider(c.DefaultQuery("provider", string(accountdomain.ProviderBuild)))
|
||||
if limitText, pagedExport := c.GetQuery("limit"); pagedExport {
|
||||
if _, usesOffset := c.GetQuery("offset"); usesOffset {
|
||||
response.Error(c, http.StatusBadRequest, "accountExportFailed", "分批导出不支持 offset,请使用服务端返回的 afterId")
|
||||
return
|
||||
}
|
||||
limit, err := strconv.Atoi(strings.TrimSpace(limitText))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "accountExportFailed", "导出数量必须为整数")
|
||||
return
|
||||
}
|
||||
afterID, err := strconv.ParseUint(strings.TrimSpace(c.DefaultQuery("afterId", "0")), 10, 64)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "accountExportFailed", "导出游标必须为非负整数")
|
||||
return
|
||||
}
|
||||
snapshotMaxID, err := strconv.ParseUint(strings.TrimSpace(c.DefaultQuery("snapshotMaxId", "0")), 10, 64)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "accountExportFailed", "导出快照上界必须为非负整数")
|
||||
return
|
||||
}
|
||||
result, exportErr := h.service.ExportProviderCredentialsCursor(c.Request.Context(), providerValue, afterID, snapshotMaxID, limit)
|
||||
if exportErr != nil {
|
||||
h.writeServiceError(c, "accountExportFailed", exportErr, http.StatusInternalServerError, "导出账号失败")
|
||||
return
|
||||
}
|
||||
c.Header("X-Export-Next-ID", strconv.FormatUint(result.NextID, 10))
|
||||
c.Header("X-Export-Snapshot-Max-ID", strconv.FormatUint(result.SnapshotMaxID, 10))
|
||||
c.Header("X-Export-Has-More", strconv.FormatBool(result.HasMore))
|
||||
h.writeCredentialExport(c, providerValue, result.ExportResult)
|
||||
return
|
||||
}
|
||||
result, err := h.service.ExportProviderCredentials(c.Request.Context(), providerValue)
|
||||
if err != nil {
|
||||
h.writeServiceError(c, "accountExportFailed", err, http.StatusInternalServerError, "导出账号失败")
|
||||
return
|
||||
}
|
||||
h.writeCredentialExport(c, providerValue, result)
|
||||
}
|
||||
|
||||
func (h *Handler) exportSelectedCredentials(c *gin.Context) {
|
||||
var request credentialExportRequest
|
||||
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)
|
||||
result, err := h.service.ExportProviderCredentialsByIDs(c.Request.Context(), providerValue, ids)
|
||||
if err != nil {
|
||||
h.writeServiceError(c, "accountExportFailed", err, http.StatusInternalServerError, "导出账号失败")
|
||||
return
|
||||
}
|
||||
h.writeCredentialExport(c, providerValue, result)
|
||||
}
|
||||
|
||||
func (h *Handler) writeCredentialExport(c *gin.Context, providerValue accountdomain.Provider, result accountapp.ExportResult) {
|
||||
filename := "grok2api-" + string(providerValue) + "-accounts-" + time.Now().UTC().Format("20060102T150405Z") + ".json"
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.Header("Pragma", "no-cache")
|
||||
c.Header("Access-Control-Expose-Headers", "Content-Disposition, X-Exported-Accounts, X-Export-Next-ID, X-Export-Snapshot-Max-ID, X-Export-Has-More")
|
||||
c.Header("Content-Disposition", `attachment; filename="`+filename+`"`)
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
c.Header("X-Exported-Accounts", strconv.Itoa(result.Count))
|
||||
|
||||
@@ -87,6 +87,31 @@ func TestWriteServiceErrorUsesCredentialLimitCodes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialExportRejectsOffsetPagination(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest("GET", "/api/admin/v1/accounts/export?provider=grok_build&limit=1000&offset=1000", nil)
|
||||
new(Handler).exportCredentials(ctx)
|
||||
if recorder.Code != 400 || !strings.Contains(recorder.Body.String(), "afterId") {
|
||||
t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialExportExposesBatchMetadataHeaders(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
new(Handler).writeCredentialExport(ctx, accountdomain.ProviderBuild, accountapp.ExportResult{Data: []byte(`[]`)})
|
||||
|
||||
exposed := recorder.Header().Get("Access-Control-Expose-Headers")
|
||||
for _, header := range []string{"X-Exported-Accounts", "X-Export-Next-ID", "X-Export-Snapshot-Max-ID", "X-Export-Has-More"} {
|
||||
if !strings.Contains(exposed, header) {
|
||||
t.Fatalf("exposed headers %q do not include %s", exposed, header)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLinkedDeleteTargets(t *testing.T) {
|
||||
targets, err := parseLinkedDeleteTargets([]string{"grok_build", "grok_console", "grok_build"})
|
||||
if err != nil || len(targets) != 2 || targets[0] != accountdomain.ProviderBuild || targets[1] != accountdomain.ProviderConsole {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApiError, apiDownload, apiEventStream, apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import { ApiError, apiDownload, apiDownloadResponse, apiEventStream, apiRequest, type PaginatedDTO } from "@/shared/api/client";
|
||||
import { createObjectDecoder, createPaginatedDecoder, createValidatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder";
|
||||
import { i18n } from "@/shared/i18n";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
@@ -493,8 +493,48 @@ export function refreshAccountQuota(id: string): Promise<AccountDTO> {
|
||||
return apiRequest(`/api/admin/v1/accounts/${id}/refresh-quota`, { method: "POST" }, decodeAccount);
|
||||
}
|
||||
|
||||
export function exportAccounts(provider: AccountProvider): Promise<Blob> {
|
||||
return apiDownload(`/api/admin/v1/accounts/export?provider=${encodeURIComponent(provider)}`);
|
||||
export type AccountExportBatch = {
|
||||
blob: Blob;
|
||||
count: number;
|
||||
nextId: string;
|
||||
snapshotMaxId: string;
|
||||
hasMore: boolean;
|
||||
};
|
||||
|
||||
function requiredExportHeader(headers: Headers, name: string): string {
|
||||
const value = headers.get(name);
|
||||
if (value === null) {
|
||||
throw new ApiError(502, "invalidResponse", i18n.t("apiErrors.invalidResponse"));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function exportAccountBatch(provider: AccountProvider, limit: number, afterId: string, snapshotMaxId: string): Promise<AccountExportBatch> {
|
||||
const query = new URLSearchParams({ provider, limit: String(limit), afterId, snapshotMaxId });
|
||||
const result = await apiDownloadResponse(`/api/admin/v1/accounts/export?${query}`);
|
||||
const count = Number(requiredExportHeader(result.headers, "X-Exported-Accounts"));
|
||||
const nextId = requiredExportHeader(result.headers, "X-Export-Next-ID");
|
||||
const nextSnapshotMaxId = requiredExportHeader(result.headers, "X-Export-Snapshot-Max-ID");
|
||||
const hasMoreText = requiredExportHeader(result.headers, "X-Export-Has-More");
|
||||
const validCursor = /^\d+$/.test(nextId) && /^\d+$/.test(nextSnapshotMaxId);
|
||||
if (!Number.isSafeInteger(count) || count < 0 || !validCursor || (hasMoreText !== "true" && hasMoreText !== "false")) {
|
||||
throw new ApiError(502, "invalidResponse", i18n.t("apiErrors.invalidResponse"));
|
||||
}
|
||||
const hasMore = hasMoreText === "true";
|
||||
if (hasMore && (count === 0 || BigInt(nextId) <= BigInt(afterId) || BigInt(nextId) > BigInt(nextSnapshotMaxId))) {
|
||||
throw new ApiError(502, "invalidResponse", i18n.t("apiErrors.invalidResponse"));
|
||||
}
|
||||
return {
|
||||
blob: result.blob,
|
||||
count,
|
||||
nextId,
|
||||
snapshotMaxId: nextSnapshotMaxId,
|
||||
hasMore,
|
||||
};
|
||||
}
|
||||
|
||||
export function exportSelectedAccounts(provider: AccountProvider, ids: string[]): Promise<Blob> {
|
||||
return apiDownload("/api/admin/v1/accounts/export", { method: "POST", body: { provider, ids } });
|
||||
}
|
||||
|
||||
export function updateAccountsEnabled(ids: string[], enabled: boolean, provider: AccountProvider): Promise<{ updated: number }> {
|
||||
|
||||
@@ -43,7 +43,8 @@ import {
|
||||
previewCleanup,
|
||||
enableWebAccountNSFW,
|
||||
convertWebAccountsToBuild,
|
||||
exportAccounts,
|
||||
exportAccountBatch,
|
||||
exportSelectedAccounts,
|
||||
getAccountSummary,
|
||||
importAccounts,
|
||||
importConsoleAccounts,
|
||||
@@ -146,6 +147,11 @@ export function AccountsPage() {
|
||||
const [cleanupPreview, setCleanupPreview] = useState<{ key: string; data: CleanupPreviewDTO } | null>(null);
|
||||
const [cleanupPreviewError, setCleanupPreviewError] = useState(false);
|
||||
const [exportOpen, setExportOpen] = useState(false);
|
||||
const [exportLimit, setExportLimit] = useState("1000");
|
||||
const [exportCursor, setExportCursor] = useState("0");
|
||||
const [exportSnapshotMaxId, setExportSnapshotMaxId] = useState("0");
|
||||
const [exportBatchNumber, setExportBatchNumber] = useState(1);
|
||||
const [exportCompletedCount, setExportCompletedCount] = useState(0);
|
||||
const [syncAllOpen, setSyncAllOpen] = useState(false);
|
||||
const [allQuotaTask, setAllQuotaTask] = useState<BuildQuotaTask>("sync");
|
||||
const [quotaSyncProgress, setQuotaSyncProgress] = useState<AccountTaskProgressDTO | null>(null);
|
||||
@@ -600,11 +606,31 @@ export function AccountsPage() {
|
||||
});
|
||||
|
||||
const exportMutation = useMutation({
|
||||
mutationFn: () => exportAccounts(provider),
|
||||
onSuccess: (blob) => {
|
||||
downloadAccountExport(blob, provider);
|
||||
mutationFn: async (input: { kind: "selected"; ids: string[] } | { kind: "batch"; limit: number; afterId: string; snapshotMaxId: string; batchNumber: number }) => {
|
||||
if (input.kind === "selected") {
|
||||
return { kind: input.kind, blob: await exportSelectedAccounts(provider, input.ids) } as const;
|
||||
}
|
||||
return { kind: input.kind, batchNumber: input.batchNumber, batch: await exportAccountBatch(provider, input.limit, input.afterId, input.snapshotMaxId) } as const;
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
if (result.kind === "selected") {
|
||||
downloadAccountExport(result.blob, provider, "selected");
|
||||
setExportOpen(false);
|
||||
toast.success(t("accounts.exported"));
|
||||
return;
|
||||
}
|
||||
downloadAccountExport(result.batch.blob, provider, `batch-${String(result.batchNumber).padStart(4, "0")}`);
|
||||
const completed = exportCompletedCount + result.batch.count;
|
||||
if (result.batch.hasMore) {
|
||||
setExportCursor(result.batch.nextId);
|
||||
setExportSnapshotMaxId(result.batch.snapshotMaxId);
|
||||
setExportBatchNumber(result.batchNumber + 1);
|
||||
setExportCompletedCount(completed);
|
||||
toast.success(t("accountExport.batchCompleted", { count: result.batch.count }));
|
||||
return;
|
||||
}
|
||||
setExportOpen(false);
|
||||
toast.success(t("accounts.exported"));
|
||||
toast.success(t("accountExport.completed", { count: completed }));
|
||||
},
|
||||
onError: showError,
|
||||
});
|
||||
@@ -934,6 +960,24 @@ export function AccountsPage() {
|
||||
setSelection((current) => ({ provider: current.provider, ids: new Set() }));
|
||||
}
|
||||
|
||||
function resetExportProgress(): void {
|
||||
setExportCursor("0");
|
||||
setExportSnapshotMaxId("0");
|
||||
setExportBatchNumber(1);
|
||||
setExportCompletedCount(0);
|
||||
}
|
||||
|
||||
function openProviderExport(): void {
|
||||
clearSelection();
|
||||
resetExportProgress();
|
||||
setExportOpen(true);
|
||||
}
|
||||
|
||||
function openSelectedExport(): void {
|
||||
resetExportProgress();
|
||||
setExportOpen(true);
|
||||
}
|
||||
|
||||
function togglePage(checked: boolean): void {
|
||||
setSelection((current) => {
|
||||
const next = new Set(current.provider === provider ? current.ids : []);
|
||||
@@ -1041,7 +1085,7 @@ export function AccountsPage() {
|
||||
{hasProviderAccounts ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setExportOpen(true)}><Download />{t("accounts.exportAuth")}</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={openProviderExport}><Download />{t("accounts.exportAuth")}</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
@@ -1125,6 +1169,7 @@ export function AccountsPage() {
|
||||
{selected.size > 0 ? (
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className="mr-1 text-xs text-muted-foreground">{t("common.selectedCount", { count: selected.size })}</span>
|
||||
<Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={openSelectedExport}><Download />{t("accounts.exportAuth")}</Button>
|
||||
<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>
|
||||
<Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => {
|
||||
@@ -1333,10 +1378,32 @@ export function AccountsPage() {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<AlertDialog open={exportOpen} onOpenChange={setExportOpen}>
|
||||
<AlertDialog open={exportOpen} onOpenChange={(open) => { if (!open && !exportMutation.isPending) setExportOpen(false); }}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader><AlertDialogTitle>{t("accounts.exportTitle", { provider: provider === "grok_build" ? "Grok Build" : provider === "grok_web" ? "Grok Web" : "Grok Console" })}</AlertDialogTitle><AlertDialogDescription>{t("accounts.exportDescription")}</AlertDialogDescription></AlertDialogHeader>
|
||||
<AlertDialogFooter><AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel><AlertDialogAction disabled={exportMutation.isPending} onClick={() => exportMutation.mutate()}>{t("accounts.exportAuth")}</AlertDialogAction></AlertDialogFooter>
|
||||
{selected.size > 0 ? <p className="text-sm text-muted-foreground">{t("common.selectedCount", { count: selected.size })}</p> : <div className="grid gap-2">
|
||||
<Label htmlFor="account-export-limit">{t("accounts.exportCount")}</Label>
|
||||
<Input id="account-export-limit" type="number" min={1} max={10000} value={exportLimit} disabled={exportSnapshotMaxId !== "0"} onChange={(event) => setExportLimit(event.target.value)} />
|
||||
<p className="text-xs text-muted-foreground">{t("accountExport.countDescription")}</p>
|
||||
{exportCompletedCount > 0 ? <p className="text-sm text-muted-foreground">{t("accountExport.batchProgress", { count: exportCompletedCount, batch: exportBatchNumber })}</p> : null}
|
||||
</div>}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={exportMutation.isPending}>{t("common.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
disabled={exportMutation.isPending || (selected.size === 0 && (!Number.isInteger(Number(exportLimit)) || Number(exportLimit) < 1 || Number(exportLimit) > 10000))}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
if (selected.size > 0) {
|
||||
exportMutation.mutate({ kind: "selected", ids: [...selected] });
|
||||
return;
|
||||
}
|
||||
exportMutation.mutate({ kind: "batch", limit: Number(exportLimit), afterId: exportCursor, snapshotMaxId: exportSnapshotMaxId, batchNumber: exportBatchNumber });
|
||||
}}
|
||||
>
|
||||
{exportMutation.isPending ? <Spinner /> : null}
|
||||
{selected.size === 0 && exportCompletedCount > 0 ? t("accountExport.nextBatch") : t("accounts.exportAuth")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
@@ -1823,11 +1890,11 @@ export function AccountsPage() {
|
||||
);
|
||||
}
|
||||
|
||||
function downloadAccountExport(blob: Blob, provider: AccountProvider): void {
|
||||
function downloadAccountExport(blob: Blob, provider: AccountProvider, suffix: string): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = `grok2api-${provider.replaceAll("_", "-")}-accounts-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
anchor.download = `grok2api-${provider.replaceAll("_", "-")}-accounts-${suffix}-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
anchor.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||
}
|
||||
|
||||
@@ -255,16 +255,17 @@ async function readEventStreamChunk(reader: ReadableStreamDefaultReader<Uint8Arr
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiDownload(path: string, retryAuth = true): Promise<Blob> {
|
||||
const headers = new Headers();
|
||||
if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);
|
||||
const response = await fetch(`${runtimeConfig.apiBaseUrl}${path}`, {
|
||||
credentials: "include",
|
||||
headers,
|
||||
});
|
||||
if (response.status === 401 && retryAuth) {
|
||||
export type ApiDownloadResult = {
|
||||
blob: Blob;
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export async function apiDownloadResponse(path: string, options: RequestOptions = {}): Promise<ApiDownloadResult> {
|
||||
const { authenticated = true, retryAuth = true } = options;
|
||||
const response = await sendApiRequest(path, options);
|
||||
if (response.status === 401 && authenticated && retryAuth) {
|
||||
const refreshResult = await refreshAccessToken();
|
||||
if (refreshResult === "refreshed") return apiDownload(path, false);
|
||||
if (refreshResult === "refreshed") return apiDownloadResponse(path, { ...options, retryAuth: false });
|
||||
if (refreshResult === "unavailable") {
|
||||
throw new ApiError(503, "sessionRefreshUnavailable", localizedErrorMessage("sessionRefreshUnavailable", "Unable to refresh the session. Please retry."));
|
||||
}
|
||||
@@ -273,7 +274,11 @@ export async function apiDownload(path: string, retryAuth = true): Promise<Blob>
|
||||
await parseResponse(response, decodeNever);
|
||||
throw new ApiError(response.status, "requestFailed", localizedErrorMessage("requestFailed", "The request failed"));
|
||||
}
|
||||
return response.blob();
|
||||
return { blob: await response.blob(), headers: response.headers };
|
||||
}
|
||||
|
||||
export async function apiDownload(path: string, options: RequestOptions = {}): Promise<Blob> {
|
||||
return (await apiDownloadResponse(path, options)).blob;
|
||||
}
|
||||
|
||||
export type AdminDTO = {
|
||||
|
||||
@@ -421,6 +421,13 @@ const resources = {
|
||||
learnMore: "查看模型",
|
||||
unknown: "未知",
|
||||
},
|
||||
accountExport: {
|
||||
countDescription: "按稳定顺序分批导出,单批最多 10000 个。",
|
||||
batchProgress: "已导出 {{count}} 个账号;下一批为第 {{batch}} 批。",
|
||||
nextBatch: "导出下一批",
|
||||
batchCompleted: "本批已导出 {{count}} 个账号",
|
||||
completed: "导出完成,共 {{count}} 个账号",
|
||||
},
|
||||
accounts: {
|
||||
title: "上游账号",
|
||||
description: "分别管理 Grok Build OAuth、Grok Web SSO 与 Grok Console SSO 号池、健康状态和额度。",
|
||||
@@ -456,6 +463,8 @@ const resources = {
|
||||
exported: "账号凭据已导出",
|
||||
exportTitle: "导出 {{provider}} 账号?",
|
||||
exportDescription: "导出的 JSON 包含当前渠道的登录凭据和已配置的 Cloudflare Cookie,可由本项目重新导入。请仅保存到可信位置。",
|
||||
exportCount: "导出数量",
|
||||
exportCountDescription: "按创建时间从新到旧导出,单批最多 10000 个。",
|
||||
refreshAllBilling: "同步全部额度",
|
||||
account: "账号",
|
||||
status: "状态",
|
||||
@@ -1260,8 +1269,9 @@ const resources = {
|
||||
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
|
||||
accountQuotaReset: { action: "Reset quota", description: "This clears only local waiting-reset and model quota blocks. It does not change upstream Billing or audit history. Accounts that remain exhausted will be marked again by real traffic.", completed: "Reset local quota state for {{reset}} accounts" },
|
||||
accountQuotaTask: { title: "Process quota for {{count}} selected accounts", description: "Choose the quota task to run for the selected Grok Build accounts.", allTitle: "Process quota for all accounts", allDescription: "Choose the quota task to run for all enabled Grok Build accounts.", syncDescription: "Request upstream Billing and update local quota snapshots, account tiers, and recovery state.", resetAllDescription: "Clear local waiting-reset and exhausted-quota blocks for all enabled Grok Build accounts without changing upstream Billing or audit history.", execute: "Run task" },
|
||||
accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" },
|
||||
dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" },
|
||||
accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control. This may affect video generation and other permissions.", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnliLine 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 or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control. This may affect video generation and other permissions.", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web
Line truncated
|
||||
models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
|
||||
keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning supports low / medium / high; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" },
|
||||
audits: {
|
||||
|
||||
Reference in new issue
Block a user