Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions internal/quotahistory/providers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"reflect"
"strconv"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -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)
}
}
}
32 changes: 31 additions & 1 deletion internal/quotahistory/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions web/src/features/quota/QuotaPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
historyFromLiveSnapshots,
isLivePoolProvider,
mergeLiveHistory,
orderingWindowKey,
poolChartWindows,
poolProvidersFromHistory,
providerWindowLabels,
Expand Down Expand Up @@ -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),
});
});
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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}
Expand Down
18 changes: 13 additions & 5 deletions web/src/features/quota/components/PoolAccountsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -304,11 +307,16 @@ export function PoolAccountsTable({
) : row.exhausted ? (
<Badge tone="warning">{t('quota_accounts.badge_exhausted')}</Badge>
) : null}
{row.error && (
<Badge tone="destructive" title={row.error}>
{t('quota_accounts.badge_read_failed')}
</Badge>
)}
{row.error &&
(needsVerification(row.error) ? (
<Badge tone="destructive" title={t('quota_accounts.verify_hint')}>
{t('quota_accounts.badge_verify')}
</Badge>
) : (
<Badge tone="destructive" title={row.error}>
{t('quota_accounts.badge_read_failed')}
</Badge>
))}
</div>
</TableCell>
<TableCell className={styles.plan}>{formatPlanName(row.plan)}</TableCell>
Expand Down
29 changes: 29 additions & 0 deletions web/src/features/quota/poolModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions web/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}}",
Expand Down
45 changes: 45 additions & 0 deletions web/tests/quotaPoolModel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
historyFromLiveSnapshots,
jumpThreshold,
nextResetAfter,
orderingWindowKey,
parseWindowKey,
defaultPoolWindow,
poolProvidersFromHistory,
Expand Down Expand Up @@ -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', () => {
Expand Down