diff --git a/internal/quotahistory/providers_test.go b/internal/quotahistory/providers_test.go index 6b887b6de43..3b58704b0bf 100644 --- a/internal/quotahistory/providers_test.go +++ b/internal/quotahistory/providers_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "reflect" + "strconv" "strings" "testing" "time" @@ -275,3 +276,24 @@ func TestParseAntigravityPlan(t *testing.T) { } } } + +func TestQuotaErrorsKeepGoogleReasonCode(t *testing.T) { + body := `{"error":{"code":403,"message":"Verify your account to continue.","status":"PERMISSION_DENIED","details":[` + + `{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED","metadata":{"validation_url":"https://accounts.google.com/secret-plt"}},` + + `{"@type":"type.googleapis.com/google.rpc.Help","links":[{"url":"https://accounts.google.com/secret-plt"}]}]}}` + r := NewRecorder(Deps{DoRequest: func(context.Context, *coreauth.Auth, string, string, map[string]string, []byte) (int, []byte, error) { + return 403, []byte(body), nil + }}) + auth := &coreauth.Auth{ID: t.Name(), Provider: "antigravity", Metadata: map[string]any{"project_id": "fixture"}} + rec := r.sample(context.Background(), auth) + if rec.Error != "HTTP 403 VALIDATION_REQUIRED" { + t.Fatalf("error = %q, want status and reason code only", rec.Error) + } + + for _, reason := range []string{"verify at https://x", "lower_case", strings.Repeat("A", 65)} { + doc := `{"error":{"details":[{"reason":` + strconv.Quote(reason) + `}]}}` + if got := errorReason([]byte(doc)); got != "" { + t.Fatalf("errorReason(%q) = %q, want empty", reason, got) + } + } +} diff --git a/internal/quotahistory/recorder.go b/internal/quotahistory/recorder.go index 8990efb2e15..20a24edd3aa 100644 --- a/internal/quotahistory/recorder.go +++ b/internal/quotahistory/recorder.go @@ -11,6 +11,7 @@ import ( "sync/atomic" "time" + "github.com/MoeForge/moego/ojson" coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" log "github.com/sirupsen/logrus" ) @@ -620,12 +621,41 @@ func (r *Recorder) request(ctx context.Context, auth *coreauth.Auth, method, url } if status < 200 || status >= 300 { // Usage responses can echo credentials or personal data. Keep errors bounded - // to the status code for both storage and logs. + // to the status code and a machine-readable reason code for both storage and logs. + if reason := errorReason(body); reason != "" { + return nil, fmt.Errorf("HTTP %d %s", status, reason) + } return nil, fmt.Errorf("HTTP %d", status) } return body, nil } +// errorReason returns the reason code of a Google RPC error +// (error.details[].reason, such as VALIDATION_REQUIRED). Only upper-case +// identifiers are kept, so no message text, URL or account data reaches the +// stored error. +func errorReason(body []byte) string { + for _, detail := range ojson.ParseBytes(body).Get("error.details").Array() { + reason := detail.Get("reason").String() + if isReasonCode(reason) { + return reason + } + } + return "" +} + +func isReasonCode(value string) bool { + if value == "" || len(value) > 64 { + return false + } + for _, r := range value { + if (r < 'A' || r > 'Z') && (r < '0' || r > '9') && r != '_' { + return false + } + } + return true +} + func (r *Recorder) setPlan(authIndex, plan string) { r.plansMu.Lock() r.plans[authIndex] = plan diff --git a/web/src/features/quota/QuotaPage.tsx b/web/src/features/quota/QuotaPage.tsx index 6c69c736b45..989ec9972c8 100644 --- a/web/src/features/quota/QuotaPage.tsx +++ b/web/src/features/quota/QuotaPage.tsx @@ -56,6 +56,7 @@ import { historyFromLiveSnapshots, isLivePoolProvider, mergeLiveHistory, + orderingWindowKey, poolChartWindows, poolProvidersFromHistory, providerWindowLabels, @@ -615,7 +616,7 @@ export function QuotaPage() { out[provider] = buildPoolAccountRows(poolHistory, provider, inputs, now, { // Columns read shortest first, like 5-hour before weekly. windowKeys: [...windows].reverse().map((window) => window.key), - primary: windows[0]?.key ?? null, + primary: orderingWindowKey(poolHistory, provider, windows), weights: effectiveWeightsFor(provider), }); }); @@ -1001,6 +1002,7 @@ export function QuotaPage() { const windows = isLivePoolProvider(provider) ? [] : providerWindows(poolHistory, provider); + const orderingKey = orderingWindowKey(poolHistory, provider, windows); const providerLabel = getTypeLabel(t, provider); const windowLabels = providerWindowLabels(windows); const columns = isLivePoolProvider(provider) @@ -1057,7 +1059,7 @@ export function QuotaPage() { rows={rows} windowColumns={columns} primaryLabel={ - windows[0] ? windowLabel(t, windows[0].key, windowLabels) : undefined + orderingKey ? windowLabel(t, orderingKey, windowLabels) : undefined } now={now} locale={locale} diff --git a/web/src/features/quota/components/PoolAccountsTable.tsx b/web/src/features/quota/components/PoolAccountsTable.tsx index 3dae2125000..92731400eff 100644 --- a/web/src/features/quota/components/PoolAccountsTable.tsx +++ b/web/src/features/quota/components/PoolAccountsTable.tsx @@ -66,6 +66,9 @@ export interface PoolAccountsTableProps { renderDetail?: (row: PoolAccountRow) => ReactNode; } +/** The provider (Google) wants the account owner to verify the account before it can be used. */ +const needsVerification = (error: string) => /\bVALIDATION_REQUIRED\b/.test(error); + const meterLevel = (remaining: number) => remaining <= 0 ? 'empty' : remaining < 20 ? 'low' : 'ok'; @@ -304,11 +307,16 @@ export function PoolAccountsTable({ ) : row.exhausted ? ( {t('quota_accounts.badge_exhausted')} ) : null} - {row.error && ( - - {t('quota_accounts.badge_read_failed')} - - )} + {row.error && + (needsVerification(row.error) ? ( + + {t('quota_accounts.badge_verify')} + + ) : ( + + {t('quota_accounts.badge_read_failed')} + + ))} {formatPlanName(row.plan)} diff --git a/web/src/features/quota/poolModel.ts b/web/src/features/quota/poolModel.ts index 0ef5b15cbca..eb39ca993ad 100644 --- a/web/src/features/quota/poolModel.ts +++ b/web/src/features/quota/poolModel.ts @@ -304,6 +304,35 @@ export function providerWindows(history: QuotaHistory, provider: PoolProvider): }); } +/** + * The window accounts are ordered by and whose reset the table shows: the + * longest window, preferring one that has reported a reset. A window that has + * not been used yet (Antigravity's "Claude and GPT models" before the first + * request) reports no reset, so ordering by it would leave every reset blank. + */ +export function orderingWindowKey( + history: QuotaHistory, + provider: PoolProvider, + windows: readonly ProviderWindow[] +): string | null { + const longest = windows[0]?.periodHours ?? null; + const candidates = windows.filter((window) => window.periodHours === longest); + const accounts = new Set( + history.accounts + .filter((account) => account.provider === provider && !account.disabled) + .map((account) => account.authIndex) + ); + const withReset = candidates.find((window) => + history.samples.some( + (sample) => + !sample.error && + accounts.has(sample.authIndex) && + sample.windows[window.key]?.resetsAt != null + ) + ); + return (withReset ?? windows[0])?.key ?? null; +} + /** * Providers that get a pool card from recorded history: any with an enabled * account reporting a renewing window. Claude and Codex lead, the rest follow diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 4520ff648a0..91a7aad2aa7 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -1847,6 +1847,8 @@ "badge_disabled": "Disabled", "badge_exhausted": "Exhausted", "badge_read_failed": "Read failed", + "badge_verify": "Verify account", + "verify_hint": "Google asks this account to verify itself before it can be used (HTTP 403 VALIDATION_REQUIRED). Sign in to Antigravity with this account and complete the check.", "credits_loading": "Loading…", "credits_unavailable": "Unavailable", "credit_expires": "next expires {{date}}", diff --git a/web/tests/quotaPoolModel.test.ts b/web/tests/quotaPoolModel.test.ts index 432a58add42..311925286ea 100644 --- a/web/tests/quotaPoolModel.test.ts +++ b/web/tests/quotaPoolModel.test.ts @@ -23,6 +23,7 @@ import { historyFromLiveSnapshots, jumpThreshold, nextResetAfter, + orderingWindowKey, parseWindowKey, defaultPoolWindow, poolProvidersFromHistory, @@ -778,6 +779,50 @@ describe('pools for every provider', () => { expect([...resets].sort((a, b) => a - b)).toEqual(resets); expect(rows.filter((row) => row.isNext)).toHaveLength(1); }); + + test('accounts order by a weekly window that reports resets, not an unused one listed first', () => { + const claudeGpt = 'group_claude_and_gpt_models_3p_weekly'; + const gemini = 'group_gemini_models_gemini_weekly'; + const h = history( + [ + { id: 'g1', provider: 'antigravity', plan: 'pro' }, + { id: 'g2', provider: 'antigravity', plan: 'pro' }, + ], + [ + sample(NOW - H, 'g1', { + [claudeGpt]: { used: 0 }, + [gemini]: { used: 72, resetsAt: NOW + 50 * H }, + }), + sample(NOW - H, 'g2', { + [claudeGpt]: { used: 0 }, + [gemini]: { used: 10, resetsAt: NOW + 20 * H }, + }), + ] + ); + const windows = providerWindows(h, 'antigravity'); + expect(windows[0].key).toBe(claudeGpt); + const primary = orderingWindowKey(h, 'antigravity', windows); + expect(primary).toBe(gemini); + const rows = buildPoolAccountRows( + h, + 'antigravity', + ['g1', 'g2'].map((id) => ({ authIndex: id, label: id, plan: 'pro', disabled: false })), + NOW, + { windowKeys: windows.map((window) => window.key), primary } + ); + expect(rows.map((row) => [row.authIndex, row.weekly?.resetsAt])).toEqual([ + ['g2', NOW + 20 * H], + ['g1', NOW + 50 * H], + ]); + // With no window reporting a reset, the longest window listed first stays the default. + const unused = history( + [{ id: 'g1', provider: 'antigravity' }], + [sample(NOW - H, 'g1', { [claudeGpt]: { used: 0 }, [gemini]: { used: 0 } })] + ); + expect(orderingWindowKey(unused, 'antigravity', providerWindows(unused, 'antigravity'))).toBe( + claudeGpt + ); + }); }); describe('window labels', () => {