Merge pull request #681 from chenyme/grok_build_0.2.102

fix: correct subscription tier and quota classification
This commit is contained in:
Chenyme authored and GitHub committed 2026-07-18 08:55:18 +08:00
commit cda37eb8d7
14 files changed
+232 -35

No files matched your search

@@ -47,12 +47,22 @@ func TestNewQuotaViewUnknownWithoutBillingSnapshot(t *testing.T) {
}
func TestNewQuotaViewEstimatesFreeFromObservedZeroBillingProfile(t *testing.T) {
quota := newQuotaView(&accountdomain.Billing{IsUnifiedBillingUser: true, TopUpMethod: "TOP_UP_METHOD_SAVED_PAYMENT_METHOD"}, 100, nil, "")
quota := newQuotaView(&accountdomain.Billing{PlanName: "Free", IsUnifiedBillingUser: true, TopUpMethod: "TOP_UP_METHOD_SAVED_PAYMENT_METHOD"}, 100, nil, "")
if quota.Type != QuotaTypeFree || quota.Source != "billingProfile" || quota.Confidence != "estimated" || quota.Limit != 1_000_000 || quota.LimitKnown {
t.Fatalf("quota = %#v", quota)
}
}
func TestNewQuotaViewTreatsZeroUsageSuperGrokAsPaid(t *testing.T) {
quota := newQuotaView(&accountdomain.Billing{
PlanName: "SuperGrok", IsUnifiedBillingUser: true,
UsagePeriodType: "USAGE_PERIOD_TYPE_WEEKLY", CreditUsagePercent: 0,
}, 0, nil, "")
if quota.Type != QuotaTypePaid || quota.Unit != "percent" || quota.Limit != 100 || quota.Remaining != 100 || quota.Confidence != "observed" {
t.Fatalf("quota = %#v", quota)
}
}
func TestNewQuotaViewUsesConfirmedExhaustion(t *testing.T) {
now := time.Now().UTC()
next := now.Add(24 * time.Hour)
@@ -469,7 +469,11 @@ func newQuotaView(billing *accountdomain.Billing, observedTokens int64, recovery
}
}
if billing != nil && billing.IsPaid() {
result := QuotaView{Type: QuotaTypePaid, Source: "upstreamBilling", Confidence: "observed", Unit: "credits", UsagePercent: billing.CreditUsagePercent, Status: QuotaStatusActive, PeriodStart: billing.BillingPeriodStart, PeriodEnd: billing.BillingPeriodEnd}
periodStart, periodEnd := billing.BillingPeriodStart, billing.BillingPeriodEnd
if billing.UsagePeriodType != "" {
periodStart, periodEnd = billing.UsagePeriodStart, billing.UsagePeriodEnd
}
result := QuotaView{Type: QuotaTypePaid, Source: "upstreamBilling", Confidence: "observed", Unit: "credits", UsagePercent: billing.CreditUsagePercent, Status: QuotaStatusActive, PeriodStart: periodStart, PeriodEnd: periodEnd}
if recovery != nil && recovery.Kind == accountdomain.QuotaRecoveryKindPaid {
result.Status = QuotaStatusWaitingReset
if recovery.Status == accountdomain.QuotaRecoveryStatusProbing {
@@ -499,6 +503,12 @@ func newQuotaView(billing *accountdomain.Billing, observedTokens int64, recovery
}
case billing.PrepaidBalance > 0:
result.Remaining = billing.PrepaidBalance
case billing.UsagePeriodType != "":
result.Unit = "percent"
result.Used = billing.CreditUsagePercent
result.Limit = 100
result.Remaining = max(0, 100-billing.CreditUsagePercent)
result.LimitKnown = true
}
return result
}
@@ -430,7 +430,7 @@ func TestSelectorPreferFreeBuildHotReloadAndSaturationFallback(t *testing.T) {
t.Fatal(err)
}
now := time.Now().UTC()
if err := accounts.SaveBilling(ctx, account.Billing{AccountID: freeAccount.ID, IsUnifiedBillingUser: true, SyncedAt: now}); err != nil {
if err := accounts.SaveBilling(ctx, account.Billing{AccountID: freeAccount.ID, PlanName: "free", SyncedAt: now}); err != nil {
t.Fatal(err)
}
if err := accounts.SaveBilling(ctx, account.Billing{AccountID: superAccount.ID, MonthlyLimit: 140, SyncedAt: now}); err != nil {
+32 -4
View File
@@ -310,15 +310,43 @@ func (b Billing) Remaining() float64 {
// IsPaid 判断 Billing 快照是否呈现 Super/paid 信号。
// 语义与 SQL accountPaidBillingPredicate 及 QuotaView paid 分支一致:
// 任一 MonthlyLimit、OnDemandCap、OnDemandUsed、PrepaidBalance、CreditUsagePercent 为正即为 paid。
// 已确认的付费订阅名称,或任一付费额度字段为正,即为 paid。
// creditUsagePercent 只是当前周期使用率,Free 与 paid 都可能存在,不能参与判级。
// 无快照时应由调用方按 Unknown 处理,不得调用本方法。
func (b Billing) IsPaid() bool {
return b.MonthlyLimit > 0 || b.OnDemandCap > 0 || b.OnDemandUsed > 0 || b.PrepaidBalance > 0 || b.CreditUsagePercent > 0
return isPaidBillingPlan(b.PlanCode) || isPaidBillingPlan(b.PlanName) ||
b.MonthlyLimit > 0 || b.OnDemandCap > 0 || b.OnDemandUsed > 0 || b.PrepaidBalance > 0
}
// HasFreeProfileSignal 判断零付费额度快照是否包含已知 Free 账号特征。
// HasFreeProfileSignal 仅接受明确的 Free/Basic 套餐名称。
// currentPeriod、unified billing、top-up 等字段在零使用量的付费账号上同样存在,
// 不能作为 Free 证据,否则会把刚开通的 SuperGrok 误判为 Free。
func (b Billing) HasFreeProfileSignal() bool {
return b.IsUnifiedBillingUser || b.UsagePeriodType != "" || b.TopUpMethod != "" || b.BillingPeriodStart != "" || len(b.History) > 0
return isFreeBillingPlan(b.PlanCode) || isFreeBillingPlan(b.PlanName)
}
func normalizeBillingPlan(value string) string {
value = strings.ToLower(strings.TrimSpace(value))
return strings.NewReplacer(" ", "", "_", "", "-", "", "+", "plus").Replace(value)
}
func isPaidBillingPlan(value string) bool {
switch normalizeBillingPlan(value) {
case "super", "supergrok", "supergrokpro", "supergrokheavy", "supergroklite",
"grokpro", "xpremium", "xpremiumplus", "apikey":
return true
default:
return false
}
}
func isFreeBillingPlan(value string) bool {
switch normalizeBillingPlan(value) {
case "free", "grokfree", "freetier", "basic", "grokbasic", "xbasic":
return true
default:
return false
}
}
// IsKnownFreeBuild 判断候选是否是已确认的 Grok Build Free 账号。
@@ -14,20 +14,32 @@ func TestBillingIsPaidMatchesSQLSignals(t *testing.T) {
{OnDemandCap: 0.01},
{OnDemandUsed: 1},
{PrepaidBalance: 5},
{CreditUsagePercent: 0.1},
{PlanName: "SuperGrok"},
{PlanName: "SuperGrok Heavy"},
{PlanCode: "supergrok_lite"},
{PlanName: "X Premium+"},
} {
if !billing.IsPaid() {
t.Fatalf("expected paid for %#v", billing)
}
}
if (Billing{Used: 100, PlanName: "free"}).IsPaid() {
t.Fatal("usage/plan name alone must not mark paid")
if (Billing{Used: 100, CreditUsagePercent: 42.5, PlanName: "free"}).IsPaid() {
t.Fatal("usage percentage must not mark a Free account as paid")
}
if (Billing{CreditUsagePercent: 42.5}).IsPaid() {
t.Fatal("usage percentage without a subscription tier must remain unknown")
}
if (Billing{IsUnifiedBillingUser: true, UsagePeriodType: "USAGE_PERIOD_TYPE_WEEKLY"}).HasFreeProfileSignal() {
t.Fatal("generic weekly billing fields must not mark an account as free")
}
if !(Billing{PlanName: "Free"}).HasFreeProfileSignal() || !(Billing{PlanCode: "x_basic"}).HasFreeProfileSignal() {
t.Fatal("known restricted tiers should be recognized as free/basic")
}
}
func TestRoutingCandidateIsKnownFreeBuild(t *testing.T) {
freeBilling := Billing{IsUnifiedBillingUser: true}
paidBilling := Billing{MonthlyLimit: 100}
freeBilling := Billing{PlanName: "Free"}
paidBilling := Billing{PlanName: "SuperGrok"}
freeRecovery := QuotaRecovery{Kind: QuotaRecoveryKindFree}
tests := []struct {
name string
@@ -35,6 +47,7 @@ func TestRoutingCandidateIsKnownFreeBuild(t *testing.T) {
want bool
}{
{name: "billing profile", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild}, Billing: &freeBilling}, want: true},
{name: "ambiguous weekly profile", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild}, Billing: &Billing{IsUnifiedBillingUser: true, UsagePeriodType: "USAGE_PERIOD_TYPE_WEEKLY"}}},
{name: "observed response model", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild, ObservedModel: "grok-4.5-build-free"}}, want: true},
{name: "quota recovery", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild}, QuotaRecovery: &freeRecovery}, want: true},
{name: "paid overrides stale free signal", candidate: RoutingCandidate{Credential: Credential{Provider: ProviderBuild, ObservedModel: "grok-4.5-build-free"}, Billing: &paidBilling}},
@@ -24,9 +24,11 @@ type quotaBreakdownJSON struct {
}
const (
accountPaidBillingSignals = `(billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0 OR billing.credit_usage_percent > 0)`
accountPaidPlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey'))`
accountFreePlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic'))`
accountPaidBillingSignals = `(` + accountPaidPlanSignal + ` OR billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0)`
accountPaidBillingPredicate = `EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountPaidBillingSignals + `)`
accountFreeSignalPredicate = `(LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND (billing.is_unified_billing_user = TRUE OR billing.usage_period_type <> '' OR billing.top_up_method <> '' OR billing.billing_period_start <> '' OR (billing.history_json <> '' AND billing.history_json <> '[]' AND billing.history_json <> 'null'))))`
accountFreeSignalPredicate = `(LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountFreePlanSignal + `))`
accountRecoveryPredicate = `EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status IN ('exhausted', 'probing'))`
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`
@@ -40,7 +40,10 @@ func TestListFilters(t *testing.T) {
t.Fatal(err)
}
}
if err := database.db.WithContext(ctx).Create(&billingModel{AccountID: paid.ID, MonthlyLimit: 100, Used: 10, SyncedAt: now}).Error; err != nil {
if err := database.db.WithContext(ctx).Create(&billingModel{AccountID: paid.ID, PlanName: "SuperGrokPro", IsUnifiedBillingUser: true, UsagePeriodType: "USAGE_PERIOD_TYPE_WEEKLY", SyncedAt: now}).Error; err != nil {
t.Fatal(err)
}
if err := database.db.WithContext(ctx).Create(&billingModel{AccountID: disabled.ID, CreditUsagePercent: 42.5, IsUnifiedBillingUser: true, UsagePeriodType: "USAGE_PERIOD_TYPE_WEEKLY", SyncedAt: now}).Error; err != nil {
t.Fatal(err)
}
@@ -36,6 +36,8 @@ type Config struct {
UserAgent string
}
const subscriptionTierTimeout = 10 * time.Second
// Adapter 实现 Grok Build CLI Responses、模型、Billing 与 OAuth 协议。
type Adapter struct {
cfgMu sync.RWMutex
@@ -472,6 +474,13 @@ func (a *Adapter) GetBilling(ctx context.Context, credential account.Credential)
if err != nil {
return account.Billing{}, err
}
// 周额度在 0% 使用时无法区分 Free 与刚开通的付费套餐。官方 CLI
// 使用 /user?include=subscription 获取实时订阅等级;失败时再退回 JWT tier。
if tier, tierErr := a.getSubscriptionTier(ctx, credential, accessToken); tierErr == nil && tier != "" {
billing.PlanName = tier
} else if billing.PlanCode == "" && billing.PlanName == "" {
billing.PlanName = subscriptionTierFromJWT(accessToken)
}
billing.AccountID = credential.ID
billing.SyncedAt = time.Now().UTC()
return billing, nil
@@ -677,3 +686,32 @@ func (a *Adapter) getBilling(ctx context.Context, credential account.Credential,
}
return parseBilling(body)
}
func (a *Adapter) getSubscriptionTier(ctx context.Context, credential account.Credential, accessToken string) (string, error) {
endpoint := a.url("/user") + "?include=subscription"
requestCtx, cancel := context.WithTimeout(infraegress.WithAccount(ctx, string(account.ProviderBuild), credential.ID), subscriptionTierTimeout)
defer cancel()
req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, endpoint, nil)
if err != nil {
return "", err
}
if err := a.applyHeaders(req, credential, accessToken, "", "", false); err != nil {
return "", err
}
resp, err := a.http.Do(req)
if err != nil {
return "", err
}
if err := normalizeGzipResponse(resp); err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("上游订阅接口返回 %d", resp.StatusCode)
}
return parseSubscriptionTier(body)
}
@@ -35,7 +35,7 @@ func TestForwardResponseMatchesGrokBuildHeadersAndPreservesReasoning(t *testing.
if r.Method != http.MethodPost || r.URL.Path != "/v1/responses" {
t.Fatalf("request = %s %s", r.Method, r.URL.Path)
}
if r.Header.Get("Authorization") != "Bearer access-token" || r.Header.Get("X-XAI-Token-Auth") != "xai-grok-cli" || r.Header.Get("x-authenticateresponse") != "authenticate-response" || r.Header.Get("x-grok-client-version") != "0.2.101" || r.Header.Get("x-grok-client-identifier") != "grok-shell" || r.Header.Get("x-grok-client-mode") != "headless" || r.Header.Get("User-Agent") != "grok-shell/0.2.101 (linux; x86_64)" {
if r.Header.Get("Authorization") != "Bearer access-token" || r.Header.Get("X-XAI-Token-Auth") != "xai-grok-cli" || r.Header.Get("x-authenticateresponse") != "authenticate-response" || r.Header.Get("x-grok-client-version") != "0.2.102" || r.Header.Get("x-grok-client-identifier") != "grok-shell" || r.Header.Get("x-grok-client-mode") != "headless" || r.Header.Get("User-Agent") != "grok-shell/0.2.102 (linux; x86_64)" {
t.Fatalf("headers = %#v", r.Header)
}
requestID := r.Header.Get("x-grok-req-id")
@@ -81,7 +81,7 @@ func TestForwardResponseMatchesGrokBuildHeadersAndPreservesReasoning(t *testing.
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.101", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.101 (linux; x86_64)"}, cipher)
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.102", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.102 (linux; x86_64)"}, cipher)
adapter.http.Transport = transport
response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 7, UserID: "user-123", EncryptedAccessToken: encrypted}, Method: http.MethodPost, Path: "/responses",
@@ -188,9 +188,9 @@ func TestListModelsUsesOfficialMetadataHeaders(t *testing.T) {
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.101", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.101 (linux; x86_64)"}, cipher)
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.102", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.102 (linux; x86_64)"}, cipher)
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
if request.URL.Path != "/v1/models" || request.Header.Get("Authorization") != "Bearer access-token" || request.Header.Get("X-XAI-Token-Auth") != "xai-grok-cli" || request.Header.Get("x-grok-client-version") != "0.2.101" || request.Header.Get("x-grok-client-identifier") != "grok-shell" || request.Header.Get("x-grok-client-mode") != "headless" || request.Header.Get("User-Agent") != "grok-shell/0.2.101 (linux; x86_64)" {
if request.URL.Path != "/v1/models" || request.Header.Get("Authorization") != "Bearer access-token" || request.Header.Get("X-XAI-Token-Auth") != "xai-grok-cli" || request.Header.Get("x-grok-client-version") != "0.2.102" || request.Header.Get("x-grok-client-identifier") != "grok-shell" || request.Header.Get("x-grok-client-mode") != "headless" || request.Header.Get("User-Agent") != "grok-shell/0.2.102 (linux; x86_64)" {
t.Fatalf("headers = %#v", request.Header)
}
if request.Header.Get("x-userid") != "user-123" || request.Header.Get("x-email") != "user@example.com" || request.Header.Get("x-grok-user-id") != "" || request.Header.Get("x-authenticateresponse") != "" || request.Header.Get("x-grok-session-id") != "" {
@@ -263,7 +263,7 @@ func TestModelCatalogETagSignalsMissingOrChangedCatalogBaseline(t *testing.T) {
}
}
func TestGetBillingUsesCreditsEndpointOnce(t *testing.T) {
func TestGetBillingUsesCreditsAndLiveSubscriptionTier(t *testing.T) {
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
t.Fatal(err)
@@ -272,20 +272,32 @@ func TestGetBillingUsesCreditsEndpointOnce(t *testing.T) {
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.101", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.101 (linux; x86_64)"}, cipher)
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.102", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.102 (linux; x86_64)"}, cipher)
calls := 0
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
calls++
if request.URL.Path != "/v1/billing" || request.URL.Query().Get("format") != "credits" {
t.Fatalf("billing request = %s", request.URL.String())
var body string
switch request.URL.Path {
case "/v1/billing":
if request.URL.Query().Get("format") != "credits" {
t.Fatalf("billing request = %s", request.URL.String())
}
body = `{"config":{"creditUsagePercent":0,"currentPeriod":{"type":"USAGE_PERIOD_TYPE_WEEKLY","start":"2026-07-01T00:00:00Z","end":"2026-07-08T00:00:00Z"}}}`
case "/v1/user":
if request.URL.Query().Get("include") != "subscription" {
t.Fatalf("subscription request = %s", request.URL.String())
}
body = `{"subscriptionTier":"SuperGrokPro"}`
default:
t.Fatalf("unexpected request = %s", request.URL.String())
}
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"config":{"creditUsagePercent":25,"currentPeriod":{"type":"USAGE_PERIOD_TYPE_WEEKLY","start":"2026-07-01T00:00:00Z","end":"2026-07-08T00:00:00Z"}}}`)), Request: request}, nil
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: request}, nil
})
billing, err := adapter.GetBilling(context.Background(), account.Credential{ID: 7, EncryptedAccessToken: encrypted})
if err != nil {
t.Fatal(err)
}
if calls != 1 || billing.AccountID != 7 || billing.CreditUsagePercent != 25 || billing.UsagePeriodType != "USAGE_PERIOD_TYPE_WEEKLY" || billing.SyncedAt.IsZero() {
if calls != 2 || billing.AccountID != 7 || billing.CreditUsagePercent != 0 || billing.UsagePeriodType != "USAGE_PERIOD_TYPE_WEEKLY" || billing.PlanName != "SuperGrokPro" || !billing.IsPaid() || billing.SyncedAt.IsZero() {
t.Fatalf("calls=%d billing=%#v", calls, billing)
}
}
@@ -316,7 +328,7 @@ func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) {
t.Fatalf("unknown catalog = %#v", got)
}
// 不得依赖 BuildAPIFallback;空目录 + Super 仅补 1.5。
got = adapter.NormalizeAccountModelCapabilities(nil, &account.Billing{CreditUsagePercent: 1})
got = adapter.NormalizeAccountModelCapabilities(nil, &account.Billing{PlanName: "SuperGrok", CreditUsagePercent: 1})
if len(got) != 1 || got[0] != buildVideoModel {
t.Fatalf("super empty catalog = %#v", got)
}
@@ -350,7 +362,7 @@ func TestGrokSessionIDFollowsConversationIdentity(t *testing.T) {
}
func TestInferenceIdentityIsConversationScopedNotAccountScoped(t *testing.T) {
adapter := NewAdapter(Config{ClientVersion: "0.2.101", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.101 (linux; x86_64)"}, nil)
adapter := NewAdapter(Config{ClientVersion: "0.2.102", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.102 (linux; x86_64)"}, nil)
build := func(accountID uint64, conversation string) http.Header {
request := httptest.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil)
if err := adapter.applyHeaders(request, account.Credential{ID: accountID}, "token", "grok-4.5", conversation, true); err != nil {
@@ -381,7 +393,7 @@ func TestForwardResponseSupportsResourceMethodsAndQuery(t *testing.T) {
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.101", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.101 (linux; x86_64)"}, cipher)
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1", ClientVersion: "0.2.102", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.102 (linux; x86_64)"}, cipher)
methods := []string{http.MethodGet, http.MethodDelete}
next := 0
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
@@ -4,10 +4,71 @@ import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/chenyme/grok2api/backend/internal/domain/account"
)
func parseSubscriptionTier(data []byte) (string, error) {
var payload map[string]any
if err := json.Unmarshal(data, &payload); err != nil {
return "", fmt.Errorf("解析订阅等级: %w", err)
}
if tier := stringValue(firstValue(payload, "subscriptionTier", "subscription_tier")); strings.TrimSpace(tier) != "" {
return strings.TrimSpace(tier), nil
}
if user, ok := payload["user"].(map[string]any); ok {
if tier := stringValue(firstValue(user, "subscriptionTier", "subscription_tier")); strings.TrimSpace(tier) != "" {
return strings.TrimSpace(tier), nil
}
}
return "", nil
}
func subscriptionTierFromJWT(token string) string {
claims := decodeJWTClaims(token)
value, exists := claims["tier"]
if !exists {
return ""
}
if tier, ok := value.(string); ok {
tier = strings.TrimSpace(tier)
if tier == "" {
return ""
}
if numeric, err := strconv.Atoi(tier); err == nil {
return subscriptionTierFromNumber(numeric)
}
return tier
}
number, ok := value.(float64)
if !ok || number < 0 || number != float64(int(number)) {
return ""
}
return subscriptionTierFromNumber(int(number))
}
func subscriptionTierFromNumber(tier int) string {
switch tier {
case 0:
return "free"
case 1:
return "supergrok"
case 2:
return "x_basic"
case 3:
return "x_premium"
case 4:
return "x_premium_plus"
case 5:
return "supergrok_heavy"
case 6:
return "supergrok_lite"
default:
return ""
}
}
func parseBilling(data []byte) (account.Billing, error) {
var root map[string]any
if err := json.Unmarshal(data, &root); err != nil {
@@ -1,6 +1,7 @@
package cli
import (
"encoding/base64"
"testing"
)
@@ -49,4 +50,18 @@ func TestParseBillingMatchesObservedBuildPayloads(t *testing.T) {
if len(credits.History) != 1 || credits.History[0].PeriodType != "USAGE_PERIOD_TYPE_WEEKLY" || credits.History[0].PeriodStart != "2026-07-01T00:00:00Z" || credits.History[0].PeriodEnd != "2026-07-08T00:00:00Z" || credits.History[0].OnDemandUsed != 120 {
t.Fatalf("credits history = %#v", credits.History)
}
if !credits.IsPaid() {
t.Fatal("explicit SuperGrok tier must remain paid even when numeric limits are zero")
}
}
func TestParseSubscriptionTierAndJWTFallback(t *testing.T) {
tier, err := parseSubscriptionTier([]byte(`{"user":{"subscriptionTier":"SuperGrokPro"}}`))
if err != nil || tier != "SuperGrokPro" {
t.Fatalf("tier = %q err=%v", tier, err)
}
claims := base64.RawURLEncoding.EncodeToString([]byte(`{"tier":5}`))
if got := subscriptionTierFromJWT("header." + claims + ".signature"); got != "supergrok_heavy" {
t.Fatalf("JWT tier = %q", got)
}
}
@@ -372,6 +372,9 @@ func TestGetBillingAlwaysPrimaryEvenWhenMarked(t *testing.T) {
switch {
case strings.Contains(request.URL.Host, "primary.test"):
primaryHits.Add(1)
if strings.HasSuffix(request.URL.Path, "/user") {
return jsonResponse(http.StatusNotFound, `{"error":"subscription unavailable"}`, request), nil
}
if !strings.Contains(request.URL.Path, "/billing") {
t.Fatalf("path = %s", request.URL.Path)
}
@@ -398,7 +401,7 @@ func TestGetBillingAlwaysPrimaryEvenWhenMarked(t *testing.T) {
if billing.OnDemandCap != 10 || billing.OnDemandUsed != 1 {
t.Fatalf("billing = %+v", billing)
}
if primaryHits.Load() != 1 || fallbackHits.Load() != 0 {
if primaryHits.Load() != 2 || fallbackHits.Load() != 0 {
t.Fatalf("primary=%d fallback=%d", primaryHits.Load(), fallbackHits.Load())
}
if marker.calls.Load() != 0 {
@@ -57,12 +57,14 @@ export function AccountQuota({ quota, billing, locale }: { quota: QuotaDTO; bill
function BuildQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: BillingDTO; locale: string }) {
const { t } = useTranslation();
const hasWeekly = billing?.usagePeriodType === "USAGE_PERIOD_TYPE_WEEKLY";
const hasMonthly = quota.limit > 0;
const percentageQuota = quota.unit === "percent";
const hasWeekly = percentageQuota || billing?.usagePeriodType === "USAGE_PERIOD_TYPE_WEEKLY";
const hasMonthly = !percentageQuota && quota.limit > 0;
if (!hasWeekly && !hasMonthly) return <span className="text-xs text-muted-foreground">{t("accounts.paidQuotaUsage")}</span>;
const weeklyPercent = Math.max(0, Math.min(100, billing?.creditUsagePercent ?? 0));
const weeklyPercent = Math.max(0, Math.min(100, percentageQuota ? quota.usagePercent : (billing?.creditUsagePercent ?? 0)));
const monthlyPercent = Math.max(0, Math.min(100, quota.usagePercent));
const weeklyPeriodEnd = quota.periodEnd ?? billing?.usagePeriodEnd;
const statusDescription = quota.status === "waitingReset" && quota.nextProbeAt
? t("accounts.paidWaitingResetUntil", { time: formatDateTime(quota.nextProbeAt, locale) })
: quota.status === "probing" ? t("accounts.paidProbingQuota") : null;
@@ -80,7 +82,7 @@ function BuildQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: Bil
</TooltipTrigger>
<TooltipContent>
<div>{t("accounts.weeklyLimit", { percent: formatNumber(100 - weeklyPercent, locale, 1) })}</div>
<div className="text-muted-foreground">{billing?.usagePeriodEnd ? t("accounts.quotaResetAt", { time: formatDateTime(billing.usagePeriodEnd, locale) }) : t("accounts.quotaResetUnknown")}</div>
<div className="text-muted-foreground">{weeklyPeriodEnd ? t("accounts.quotaResetAt", { time: formatDateTime(weeklyPeriodEnd, locale) }) : t("accounts.quotaResetUnknown")}</div>
</TooltipContent>
</Tooltip>
) : null}
@@ -43,7 +43,7 @@ export type QuotaDTO = {
source: "unknown" | "upstreamBilling" | "upstreamExhaustion" | "responseModel" | "billingProfile";
confidence: "estimated" | "observed" | "confirmed" | "";
status: "active" | "waitingReset" | "probing";
unit?: "tokens" | "credits";
unit?: "tokens" | "credits" | "percent";
used: number;
limit: number;
remaining: number;
@@ -144,7 +144,7 @@ const billingValidator = hasShape({
const quotaValidator = hasShape({
type: isOneOf("free", "paid", "unknown"), source: isOneOf("unknown", "upstreamBilling", "upstreamExhaustion", "responseModel", "billingProfile"),
confidence: isOneOf("estimated", "observed", "confirmed", ""), status: isOneOf("active", "waitingReset", "probing"),
unit: isOptional(isOneOf("tokens", "credits")), used: isNumber, limit: isNumber, remaining: isNumber, usagePercent: isNumber,
unit: isOptional(isOneOf("tokens", "credits", "percent")), used: isNumber, limit: isNumber, remaining: isNumber, usagePercent: isNumber,
limitKnown: isBoolean, windowHours: isOptional(isNumber), observed: isBoolean, confirmed: isBoolean,
periodStart: isOptional(isString), periodEnd: isOptional(isString), exhaustedAt: isOptional(isString),
nextProbeAt: isOptional(isString), lastConfirmedAt: isOptional(isString),