fix(accounts): refetch Gemini usage when the account's quota tier changes

The usage refresh key has no Gemini quota input. When a Gemini account's
tier changes, as when the token refresher re-detects the Google One tier,
auto refresh replaces the row but the key is unchanged: the tier badge
shows the new tier, the quota bars keep the old limits until the account
is used, Refresh is clicked or the page is reloaded. An API key account
moved from a third-party base URL to the official one gets no bars for
the same reason.

The Gemini key now carries credentials.oauth_type, project_id, tier_id and
base_url, the credentials geminiQuotaTierKeyForAccount depends on. Gemini
usage is read from local usage logs, so the refetch sends nothing
upstream, and a token refresh that leaves these four fields alone keeps
the key.
This commit is contained in:
Anankke committed 2026-11-20 16:28:16 -08:00
1 parent 53fa92d0a6
commit cc2a2616d8
6 files changed
+101 -358

No files matched your search

@@ -947,7 +947,6 @@ const openAISevenDayEstimatedTotalCost = computed(() =>
estimateWindowTotalCost(usageInfo.value?.seven_day)
)
// Covers OpenAI, Claude and Gemini; '' for other platforms.
const usageRefreshKey = computed(() => buildAccountUsageRefreshKey(props.account))
const shouldAutoLoadUsageOnMount = computed(() => {
@@ -130,7 +130,62 @@ describe('AccountUsageCell', () => {
expect(wrapper.text()).toContain('54')
await wrapper.setProps({ account: { ...next, updated_at: 'unrelated', current_concurrency: 3 } })
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(platform === 'gemini' ? 3 : 2)
expect(getUsage).toHaveBeenCalledTimes(2)
wrapper.unmount()
})
it('refetches Gemini usage when the account quota tier changes', async () => {
const account = makeAccount({ id: 98210, platform: 'gemini', type: 'oauth', credentials: { oauth_type: 'google_one', tier_id: 'google_ai_pro' } })
getUsage.mockResolvedValue({ gemini_shared_daily: { utilization: 31 } })
const wrapper = mount(AccountUsageCell, { props: { account } })
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(1)
expect(getUsage).toHaveBeenLastCalledWith(account.id)
await wrapper.setProps({ account: { ...account, credentials: { ...account.credentials, tier_id: 'google_ai_ultra' } } })
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(2)
expect(getUsage).toHaveBeenLastCalledWith(account.id)
wrapper.unmount()
})
it.each([false, true])('sends one usage request when a relay Gemini base_url becomes the official one (batch %s)', async (batch) => {
const requestBatchedUsage = vi.fn()
const relayAccount = (baseUrl: string) => makeAccount({
id: 98220,
platform: 'gemini',
type: 'apikey',
credentials: { base_url: baseUrl, tier_id: 'aistudio_free' }
})
const wrapper = mount(AccountUsageCell, {
props: { account: relayAccount('https://relay.example'), ...(batch ? { requestBatchedUsage } : {}) }
})
const calls = () => (batch ? requestBatchedUsage.mock.calls.length : getUsage.mock.calls.length)
await flushPromises()
const before = calls()
await wrapper.setProps({ account: relayAccount('https://generativelanguage.googleapis.com') })
await flushPromises()
expect(calls() - before).toBe(1)
if (!batch) expect(getUsage).toHaveBeenLastCalledWith(98220)
wrapper.unmount()
})
it.each([false, true])('sends no usage request when one relay Gemini base_url becomes another (batch %s)', async (batch) => {
const requestBatchedUsage = vi.fn()
const relayAccount = (baseUrl: string) => makeAccount({
id: 98230,
platform: 'gemini',
type: 'apikey',
credentials: { base_url: baseUrl, tier_id: 'aistudio_free' }
})
const wrapper = mount(AccountUsageCell, {
props: { account: relayAccount('https://relay.example'), ...(batch ? { requestBatchedUsage } : {}) }
})
const calls = () => (batch ? requestBatchedUsage.mock.calls.length : getUsage.mock.calls.length)
await flushPromises()
const before = calls()
await wrapper.setProps({ account: relayAccount('https://relay2.example') })
await flushPromises()
expect(calls()).toBe(before)
wrapper.unmount()
})
@@ -1,174 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import AccountUsageCell from '../AccountUsageCell.vue'
import type { Account } from '@/types'
const { getUsage } = vi.hoisted(() => ({
getUsage: vi.fn()
}))
vi.mock('@/api/admin', () => ({
adminAPI: {
accounts: {
getUsage
}
}
}))
vi.mock('vue-i18n', async () => {
const actual = await vi.importActual<typeof import('vue-i18n')>('vue-i18n')
return {
...actual,
useI18n: () => ({
t: (key: string) => key
})
}
})
function makeAccount(overrides: Partial<Account>): Account {
return {
id: 1,
name: 'account',
platform: 'anthropic',
type: 'oauth',
proxy_id: null,
concurrency: 1,
priority: 1,
status: 'active',
error_message: null,
last_used_at: null,
expires_at: null,
auto_pause_on_expired: true,
created_at: '2026-10-25T00:00:00Z',
updated_at: '2026-10-25T00:00:00Z',
schedulable: true,
rate_limited_at: null,
rate_limit_reset_at: null,
overload_until: null,
temp_unschedulable_until: null,
temp_unschedulable_reason: null,
session_window_start: null,
session_window_end: null,
session_window_status: null,
...overrides,
}
}
const passiveUsage = (fiveHour: number, sevenDay: number) => ({
source: 'passive',
five_hour: { utilization: fiveHour, resets_at: null, remaining_seconds: 0 },
seven_day: { utilization: sevenDay, resets_at: null, remaining_seconds: 0 }
})
const stubs = {
UsageProgressBar: {
props: ['label', 'utilization'],
template: '<div class="usage-bar">{{ label }}|{{ utilization }}</div>'
},
ClaudeResetCreditsCell: { template: '<div><slot name="pre-actions" /></div>' },
AccountQuotaInfo: true
}
const sampledClaudeAccount = (id: number, sampledAt: string, fiveHour: number) => makeAccount({
id,
extra: {
passive_usage_sampled_at: sampledAt,
session_window_utilization: fiveHour,
passive_usage_7d_utilization: 0.2
}
})
describe('AccountUsageCell usage refresh on row updates', () => {
beforeEach(() => {
getUsage.mockReset()
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation(() => ({
matches: true,
media: '(min-width: 768px)',
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
})
})
it('refetches passive usage past its cache when the Claude row carries a new sample', async () => {
getUsage
.mockResolvedValueOnce(passiveUsage(10, 20))
.mockResolvedValueOnce(passiveUsage(55, 20))
const wrapper = mount(AccountUsageCell, {
props: { account: sampledClaudeAccount(4101, '2026-10-25T10:00:00Z', 0.1) },
global: { stubs }
})
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(1)
expect(getUsage).toHaveBeenLastCalledWith(4101, 'passive', false)
expect(wrapper.text()).toContain('5h|10')
// A replaced row whose usage inputs are unchanged keeps the cached usage.
await wrapper.setProps({
account: { ...sampledClaudeAccount(4101, '2026-10-25T10:00:00Z', 0.1), current_concurrency: 3 }
})
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(1)
await wrapper.setProps({ account: sampledClaudeAccount(4101, '2026-10-25T10:01:00Z', 0.55) })
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(2)
expect(getUsage).toHaveBeenLastCalledWith(4101, 'passive', false)
expect(wrapper.text()).toContain('5h|55')
})
it('asks the batch loader to bypass its cache when a batch-managed Claude row carries a new sample', async () => {
const requestBatchedUsage = vi.fn()
const wrapper = mount(AccountUsageCell, {
props: {
account: sampledClaudeAccount(4102, '2026-10-25T10:00:00Z', 0.1),
requestBatchedUsage
},
global: { stubs }
})
await flushPromises()
expect(requestBatchedUsage).toHaveBeenCalledTimes(1)
await wrapper.setProps({
account: { ...sampledClaudeAccount(4102, '2026-10-25T10:00:00Z', 0.1), current_concurrency: 3 }
})
await flushPromises()
expect(requestBatchedUsage).toHaveBeenCalledTimes(1)
await wrapper.setProps({ account: sampledClaudeAccount(4102, '2026-10-25T10:01:00Z', 0.55) })
await flushPromises()
expect(requestBatchedUsage).toHaveBeenCalledTimes(2)
expect(requestBatchedUsage).toHaveBeenLastCalledWith(expect.objectContaining({ id: 4102 }), undefined)
expect(getUsage).not.toHaveBeenCalled()
})
it('refetches Gemini usage when the row reports new use', async () => {
getUsage.mockResolvedValue({})
const account = makeAccount({
id: 4103,
platform: 'gemini',
type: 'oauth',
last_used_at: '2026-10-25T10:00:00Z',
credentials: { oauth_type: 'google_one' }
})
const wrapper = mount(AccountUsageCell, {
props: { account },
global: { stubs }
})
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(1)
expect(getUsage).toHaveBeenLastCalledWith(4103)
await wrapper.setProps({ account: { ...account, last_used_at: '2026-10-25T10:01:00Z' } })
await flushPromises()
expect(getUsage).toHaveBeenCalledTimes(2)
expect(getUsage).toHaveBeenLastCalledWith(4103)
})
})
@@ -1,11 +1,5 @@
import { describe, expect, it } from 'vitest'
import {
buildAccountUsageRefreshKey,
buildAnthropicUsageRefreshKey,
buildGeminiUsageRefreshKey,
buildGrokUsageRefreshKey,
buildOpenAIUsageRefreshKey
} from '../accountUsageRefresh'
import { buildAccountUsageRefreshKey, buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh'
describe('buildAccountUsageRefreshKey', () => {
it.each(['oauth', 'setup-token'])('tracks every Claude %s passive snapshot input', (type) => {
@@ -20,15 +14,19 @@ describe('buildAccountUsageRefreshKey', () => {
it.each(['anthropic', 'gemini'])('ignores unrelated %s changes and extra key ordering', (platform) => {
const base = { id: 1, platform, type: 'oauth', extra: { session_window_utilization: 0, other: 1 } } as any
expect(buildAccountUsageRefreshKey({ ...base, current_concurrency: 5, extra: { other: 2, session_window_utilization: 0 } } as any)).toBe(buildAccountUsageRefreshKey(base))
expect(buildAccountUsageRefreshKey({ ...base, updated_at: 'new', current_concurrency: 5, extra: { other: 2, session_window_utilization: 0 } } as any)).toBe(buildAccountUsageRefreshKey(base))
expect(buildAccountUsageRefreshKey({ ...base, last_used_at: 'new' })).not.toBe(buildAccountUsageRefreshKey(base))
})
it('tracks an account edit for Gemini but not for Claude', () => {
const claude = { id: 1, platform: 'anthropic', type: 'oauth', extra: {} } as any
expect(buildAccountUsageRefreshKey({ ...claude, updated_at: 'new' })).toBe(buildAccountUsageRefreshKey(claude))
const gemini = { id: 1, platform: 'gemini', type: 'oauth', extra: {} } as any
expect(buildAccountUsageRefreshKey({ ...gemini, updated_at: 'new' })).not.toBe(buildAccountUsageRefreshKey(gemini))
it('tracks the Gemini quota tier and ignores other credential keys', () => {
const base = { id: 1, platform: 'gemini', type: 'oauth', credentials: { oauth_type: 'google_one', tier_id: 'google_ai_pro' } } as any
expect(buildAccountUsageRefreshKey({ ...base, credentials: { ...base.credentials, tier_id: 'google_ai_ultra' } })).not.toBe(buildAccountUsageRefreshKey(base))
expect(buildAccountUsageRefreshKey({ ...base, credentials: { ...base.credentials, oauth_type: 'ai_studio' } })).not.toBe(buildAccountUsageRefreshKey(base))
const legacy = { id: 1, platform: 'gemini', type: 'oauth', credentials: {} } as any
expect(buildAccountUsageRefreshKey({ ...legacy, credentials: { project_id: 'p-1' } })).not.toBe(buildAccountUsageRefreshKey(legacy))
expect(buildAccountUsageRefreshKey({ ...base, credentials: { ...base.credentials, client_id: 'other', expires_at: '999' } })).toBe(buildAccountUsageRefreshKey(base))
const apiKey = { id: 1, platform: 'gemini', type: 'apikey', credentials: { base_url: 'https://relay.example' } } as any
expect(buildAccountUsageRefreshKey({ ...apiKey, credentials: { ...apiKey.credentials, base_url: 'https://generativelanguage.googleapis.com' } })).not.toBe(buildAccountUsageRefreshKey(apiKey))
})
it('retains OpenAI keys and excludes unsupported platforms/types', () => {
@@ -197,76 +195,3 @@ describe('buildGrokUsageRefreshKey', () => {
} as any)).toBe('')
})
})
describe('buildAnthropicUsageRefreshKey', () => {
const base = {
id: 7,
platform: 'anthropic',
type: 'oauth',
updated_at: '2026-10-25T10:00:00Z',
last_used_at: '2026-10-25T09:59:00Z',
rate_limit_reset_at: null,
session_window_start: '2026-10-25T08:00:00Z',
session_window_end: '2026-10-25T13:00:00Z',
session_window_status: 'allowed',
extra: {
passive_usage_sampled_at: '2026-10-25T09:59:00Z',
session_window_utilization: 0.1,
passive_usage_7d_utilization: 0.2,
passive_usage_7d_reset: 1761900000,
passive_usage_7d_oi_utilization: 0.3,
passive_usage_7d_oi_reset: 1761900000
}
} as any
it('changes when any input of the passive /usage response changes', () => {
const variants = [
{ last_used_at: '2026-10-25T10:01:00Z' },
{ session_window_start: '2026-10-25T13:00:00Z' },
{ session_window_end: '2026-10-25T18:00:00Z' },
{ session_window_status: 'rejected' },
{ extra: { ...base.extra, passive_usage_sampled_at: '2026-10-25T10:01:00Z' } },
{ extra: { ...base.extra, session_window_utilization: 0.5 } },
{ extra: { ...base.extra, passive_usage_7d_utilization: 0.6 } },
{ extra: { ...base.extra, passive_usage_7d_reset: 1762500000 } },
{ extra: { ...base.extra, passive_usage_7d_oi_utilization: 0.7 } },
{ extra: { ...base.extra, passive_usage_7d_oi_reset: 1762500000 } }
]
for (const variant of variants) {
expect(buildAnthropicUsageRefreshKey({ ...base, ...variant })).not.toBe(buildAnthropicUsageRefreshKey(base))
}
})
it('covers setup-token accounts', () => {
const setupToken = { ...base, type: 'setup-token' }
expect(buildAnthropicUsageRefreshKey(setupToken)).not.toBe('')
expect(buildAnthropicUsageRefreshKey({
...setupToken,
extra: { ...base.extra, session_window_utilization: 0.9 }
})).not.toBe(buildAnthropicUsageRefreshKey(setupToken))
})
it('returns an empty key for other Anthropic types and other platforms', () => {
expect(buildAnthropicUsageRefreshKey({ ...base, type: 'apikey' })).toBe('')
expect(buildAnthropicUsageRefreshKey({ ...base, platform: 'openai' })).toBe('')
})
})
describe('buildGeminiUsageRefreshKey', () => {
const base = {
id: 8,
platform: 'gemini',
type: 'oauth',
updated_at: '2026-10-25T10:00:00Z',
last_used_at: '2026-10-25T09:59:00Z'
} as any
it('changes when the account is used or updated', () => {
expect(buildGeminiUsageRefreshKey({ ...base, last_used_at: '2026-10-25T10:01:00Z' })).not.toBe(buildGeminiUsageRefreshKey(base))
expect(buildGeminiUsageRefreshKey({ ...base, updated_at: '2026-10-25T10:01:00Z' })).not.toBe(buildGeminiUsageRefreshKey(base))
})
it('returns an empty key for non-Gemini accounts', () => {
expect(buildGeminiUsageRefreshKey({ ...base, platform: 'anthropic' })).toBe('')
})
})
+32 -41
View File
@@ -52,43 +52,6 @@ export const buildOpenAIUsageRefreshKey = (account: Pick<Account, 'id' | 'platfo
].map(normalizeUsageRefreshValue).join('|')
}
// Inputs of the passive /usage response: session window columns, header samples
// in extra, and window stats from usage logs (signalled by last_used_at).
export const buildAnthropicUsageRefreshKey = (account: Pick<Account, 'id' | 'platform' | 'type' | 'last_used_at' | 'session_window_start' | 'session_window_end' | 'session_window_status' | 'extra'>): string => {
if (account.platform !== 'anthropic' || (account.type !== 'oauth' && account.type !== 'setup-token')) {
return ''
}
const extra = account.extra ?? {}
return [
account.id,
account.last_used_at,
account.session_window_start,
account.session_window_end,
account.session_window_status,
extra.passive_usage_sampled_at,
extra.session_window_utilization,
extra.passive_usage_7d_utilization,
extra.passive_usage_7d_reset,
extra.passive_usage_7d_oi_utilization,
extra.passive_usage_7d_oi_reset
].map(normalizeUsageRefreshValue).join('|')
}
// Gemini /usage counts usage logs against a tier derived from the account, so
// new use (last_used_at) or an account edit (updated_at) changes it.
export const buildGeminiUsageRefreshKey = (account: Pick<Account, 'id' | 'platform' | 'updated_at' | 'last_used_at'>): string => {
if (account.platform !== 'gemini') {
return ''
}
return [
account.id,
account.updated_at,
account.last_used_at
].map(normalizeUsageRefreshValue).join('|')
}
export const buildGrokUsageRefreshKey = (account: Pick<Account, 'platform' | 'extra'>): string => {
if (account.platform !== 'grok') {
return ''
@@ -107,9 +70,37 @@ export const buildGrokUsageRefreshKey = (account: Pick<Account, 'platform' | 'ex
].join('|')
}
export const buildAccountUsageRefreshKey = (account: Pick<Account, 'id' | 'platform' | 'type' | 'updated_at' | 'last_used_at' | 'rate_limit_reset_at' | 'session_window_start' | 'session_window_end' | 'session_window_status' | 'extra'>): string => {
export const buildAccountUsageRefreshKey = (account: Pick<Account, 'id' | 'platform' | 'type' | 'updated_at' | 'last_used_at' | 'rate_limit_reset_at' | 'session_window_start' | 'session_window_end' | 'session_window_status' | 'credentials' | 'extra'>): string => {
if (account.platform === 'openai') return buildOpenAIUsageRefreshKey(account)
if (account.platform === 'anthropic') return buildAnthropicUsageRefreshKey(account)
if (account.platform === 'gemini') return buildGeminiUsageRefreshKey(account)
return ''
const isClaude = account.platform === 'anthropic' && (account.type === 'oauth' || account.type === 'setup-token')
if (!isClaude && account.platform !== 'gemini') return ''
const credentials = account.credentials ?? {}
const extra = account.extra ?? {}
return serializeSnapshotRefreshValue([
account.id,
account.platform,
account.type,
account.last_used_at ?? null,
account.session_window_start ?? null,
account.session_window_end ?? null,
...(isClaude ? [
account.session_window_status ?? null,
extra.session_window_utilization ?? null,
extra.passive_usage_sampled_at ?? null,
extra.passive_usage_7d_utilization ?? null,
extra.passive_usage_7d_reset ?? null,
extra.passive_usage_7d_oi_utilization ?? null,
extra.passive_usage_7d_oi_reset ?? null
] : [
// Gemini quota comes from the canonical tier of (oauth_type, tier_id); a
// legacy project_id alone makes the backend treat the account as code_assist.
// An API key on a third-party base_url has no tier, the official one does.
credentials.oauth_type ?? null,
credentials.project_id ?? null,
credentials.tier_id ?? null,
credentials.base_url ?? null
])
])
}
@@ -82,11 +82,6 @@ const AccountGroupsCellStub = defineComponent({
template: '<span data-test="account-groups">{{ groups.map(group => group.name).join(",") }}</span>'
})
const AccountUsageCellStub = defineComponent({
props: { account: { type: Object, required: true } },
template: '<span data-test="usage-row">{{ account.extra?.session_window_utilization }}|{{ account.last_used_at }}</span>'
})
const EditAccountModalStub = defineComponent({
props: { show: Boolean, account: { type: Object, default: null } },
template: '<div data-test="edit-account">{{ show ? account?.name : "" }}</div>'
@@ -133,7 +128,7 @@ function mountView(stubActionMenu = true, realUsageCell = false) {
AccountStatusIndicator: true,
AccountTodayStatsCell: true,
AccountGroupsCell: AccountGroupsCellStub,
AccountUsageCell: realUsageCell ? false : AccountUsageCellStub,
AccountUsageCell: !realUsageCell,
UpstreamBillingRateCell: true,
HelpTooltip: true,
Icon: true,
@@ -221,7 +216,7 @@ describe('admin AccountsView lite account list', () => {
listWithEtag.mockResolvedValue({ notModified: false, etag: 'unrelated', data: { items: [{ ...next, updated_at: 'new', current_concurrency: 2, extra: { ...next.extra, unrelated: true } }], total: 1, pages: 1 } })
await vi.advanceTimersByTimeAsync(6000)
await flushPromises()
expect(getBatchUsage).toHaveBeenCalledTimes(platform === 'gemini' ? 3 : 2)
expect(getBatchUsage).toHaveBeenCalledTimes(2)
wrapper.unmount()
})
@@ -315,54 +310,6 @@ describe('admin AccountsView lite account list', () => {
wrapper.unmount()
})
it.each([
{
name: 'a Claude passive usage sample',
row: {
...listRow,
platform: 'anthropic',
updated_at: '2026-10-25T10:00:00Z',
last_used_at: '2026-10-25T10:00:00Z',
extra: { passive_usage_sampled_at: '2026-10-25T10:00:00Z', session_window_utilization: 0.1 }
},
change: { extra: { passive_usage_sampled_at: '2026-10-25T10:01:00Z', session_window_utilization: 0.55 } },
before: '0.1|2026-10-25T10:00:00Z',
after: '0.55|2026-10-25T10:00:00Z'
},
{
name: 'new Gemini use',
row: {
...listRow,
platform: 'gemini',
updated_at: '2026-10-25T10:00:00Z',
last_used_at: '2026-10-25T10:00:00Z'
},
change: { last_used_at: '2026-10-25T10:01:00Z' },
before: '|2026-10-25T10:00:00Z',
after: '|2026-10-25T10:01:00Z'
}
])('replaces a row on automatic refresh when only $name changed', async ({ row, change, before, after }) => {
vi.useFakeTimers()
vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
localStorage.setItem('account-auto-refresh', JSON.stringify({ enabled: true, interval_seconds: 5 }))
listAccounts.mockResolvedValue({ items: [row], total: 1, page: 1, page_size: 20, pages: 1 })
listWithEtag.mockResolvedValueOnce({
notModified: false,
etag: 'next-etag',
data: { items: [{ ...row, ...change }], total: 1, page: 1, page_size: 20, pages: 1 }
})
const wrapper = mountView()
await flushPromises()
expect(wrapper.get('[data-test="usage-row"]').text()).toBe(before)
await vi.advanceTimersByTimeAsync(6000)
await flushPromises()
expect(listWithEtag).toHaveBeenCalled()
expect(wrapper.get('[data-test="usage-row"]').text()).toBe(after)
wrapper.unmount()
})
it('loads the full account by id before opening edit, test, and stats actions', async () => {
const wrapper = mountView()
await flushPromises()