From 5f12044f59d6cc317f9bf64861fc023c02620434 Mon Sep 17 00:00:00 2001 From: Anankke Date: Mon, 16 Nov 2026 01:29:16 -0800 Subject: [PATCH 1/2] fix(accounts): refetch Claude and Gemini usage cells when auto-refresh updates a row With auto-refresh on, the accounts page replaces a row only when OpenAI or Grok usage inputs change, and AccountUsageCell watches only the OpenAI usage key, so Claude OAuth, setup-token and Gemini bars stay at what they loaded until the refresh button is clicked. Add usage refresh keys for Claude (session window columns, passive samples in extra, last_used_at) and Gemini (updated_at, last_used_at), replace a row when either changes, and have the cell watch one key across the three platforms. A change asks the batch loader for a forced refetch, or outside batch mode drops the cached entry and reloads, passive for Claude. Both backend paths read local data only, so a refetch per changed row sends no upstream request. --- .../components/account/AccountUsageCell.vue | 18 +- .../AccountUsageCell.usageRefresh.spec.ts | 174 ++++++++++++++++++ .../__tests__/accountUsageRefresh.spec.ts | 80 +++++++- frontend/src/utils/accountUsageRefresh.ts | 37 ++++ frontend/src/views/admin/AccountsView.vue | 3 + .../admin/__tests__/AccountsView.lite.spec.ts | 56 +++++- 6 files changed, 361 insertions(+), 7 deletions(-) create mode 100644 frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 8ccc433706..e243f4b060 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -751,7 +751,11 @@ import { ref, computed, onMounted, onBeforeUnmount, onUnmounted, watch } from 'v import { useI18n } from 'vue-i18n' import { adminAPI } from '@/api/admin' import type { Account, AccountUsageInfo, GeminiCredentials, WindowStats } from '@/types' -import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' +import { + buildAnthropicUsageRefreshKey, + buildGeminiUsageRefreshKey, + buildOpenAIUsageRefreshKey +} from '@/utils/accountUsageRefresh' import { enqueueUsageRequest } from '@/utils/usageLoadQueue' import { formatCompactNumber } from '@/utils/format' import { isOfficialGeminiBaseUrl } from '@/utils/geminiExplicitCache' @@ -917,7 +921,12 @@ const openAISevenDayEstimatedTotalCost = computed(() => { return Number.isFinite(estimate) && estimate > 0 ? estimate : null }) -const openAIUsageRefreshKey = computed(() => buildOpenAIUsageRefreshKey(props.account)) +// Each builder returns '' for other platforms, so at most one contributes. +const usageRefreshKey = computed(() => ( + buildOpenAIUsageRefreshKey(props.account) || + buildAnthropicUsageRefreshKey(props.account) || + buildGeminiUsageRefreshKey(props.account) +)) const shouldAutoLoadUsageOnMount = computed(() => { return shouldFetchUsage.value @@ -1797,9 +1806,8 @@ watch( { flush: 'post' } ) -watch(openAIUsageRefreshKey, (nextKey, prevKey) => { +watch(usageRefreshKey, (nextKey, prevKey) => { if (!prevKey || nextKey === prevKey) return - if (props.account.platform !== 'openai' || props.account.type !== 'oauth') return if (isBatchManaged.value) { requestParentBatchUsage({ force: true }) @@ -1807,7 +1815,7 @@ watch(openAIUsageRefreshKey, (nextKey, prevKey) => { } _usageCache.delete(props.account.id) - requestAutoLoad() + requestAutoLoad(isAnthropicOAuthOrSetupToken.value ? 'passive' : undefined) }) watch( diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts new file mode 100644 index 0000000000..34dae1ae81 --- /dev/null +++ b/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts @@ -0,0 +1,174 @@ +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('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string) => key + }) + } +}) + +function makeAccount(overrides: Partial): 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: '
{{ label }}|{{ utilization }}
' + }, + ClaudeResetCreditsCell: { template: '
' }, + 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 }), { force: true }) + 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) + }) +}) diff --git a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts index f9559697e1..d54606b88d 100644 --- a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts +++ b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest' -import { buildGrokUsageRefreshKey, buildOpenAIUsageRefreshKey } from '../accountUsageRefresh' +import { + buildAnthropicUsageRefreshKey, + buildGeminiUsageRefreshKey, + buildGrokUsageRefreshKey, + buildOpenAIUsageRefreshKey +} from '../accountUsageRefresh' describe('buildOpenAIUsageRefreshKey', () => { it('会在 codex 快照变化时生成不同 key', () => { @@ -159,3 +164,76 @@ 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('') + }) +}) diff --git a/frontend/src/utils/accountUsageRefresh.ts b/frontend/src/utils/accountUsageRefresh.ts index 121dae253a..ff89d8edde 100644 --- a/frontend/src/utils/accountUsageRefresh.ts +++ b/frontend/src/utils/accountUsageRefresh.ts @@ -52,6 +52,43 @@ export const buildOpenAIUsageRefreshKey = (account: Pick): 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): string => { + if (account.platform !== 'gemini') { + return '' + } + + return [ + account.id, + account.updated_at, + account.last_used_at + ].map(normalizeUsageRefreshValue).join('|') +} + export const buildGrokUsageRefreshKey = (account: Pick): string => { if (account.platform !== 'grok') { return '' diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index 7384e4858b..8cc2a32688 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -539,6 +539,7 @@ import { sanitizeUrl } from '@/utils/url' import { getFloatingPanelPosition } from '@/utils/floatingPanel' import { formatMultiplier } from '@/utils/formatters' import type { Account, AccountListItem, AccountPlatform, AccountSchedulerGroupScore, AccountType, AccountUsageInfo, Proxy as AccountProxy, AdminGroup, WindowStats, ClaudeModel, UpstreamBillingProbeSnapshot } from '@/types' +import { buildAnthropicUsageRefreshKey, buildGeminiUsageRefreshKey } from '@/utils/accountUsageRefresh' const { t } = useI18n() const appStore = useAppStore() @@ -1436,6 +1437,8 @@ const shouldReplaceAutoRefreshRow = (current: Account, next: Account) => { current.overload_until !== next.overload_until || current.temp_unschedulable_until !== next.temp_unschedulable_until || buildOpenAIUsageRefreshKey(current) !== buildOpenAIUsageRefreshKey(next) || + buildAnthropicUsageRefreshKey(current) !== buildAnthropicUsageRefreshKey(next) || + buildGeminiUsageRefreshKey(current) !== buildGeminiUsageRefreshKey(next) || buildGrokUsageRefreshKey(current) !== buildGrokUsageRefreshKey(next) ) } diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index 9d8d7266e5..fb44a917d9 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -67,6 +67,7 @@ const DataTableStub = defineComponent({
@@ -78,6 +79,11 @@ const AccountGroupsCellStub = defineComponent({ template: '{{ groups.map(group => group.name).join(",") }}' }) +const AccountUsageCellStub = defineComponent({ + props: { account: { type: Object, required: true } }, + template: '{{ account.extra?.session_window_utilization }}|{{ account.last_used_at }}' +}) + const EditAccountModalStub = defineComponent({ props: { show: Boolean, account: { type: Object, default: null } }, template: '
{{ show ? account?.name : "" }}
' @@ -124,7 +130,7 @@ function mountView(stubActionMenu = true) { AccountStatusIndicator: true, AccountTodayStatsCell: true, AccountGroupsCell: AccountGroupsCellStub, - AccountUsageCell: true, + AccountUsageCell: AccountUsageCellStub, UpstreamBillingRateCell: true, HelpTooltip: true, Icon: true, @@ -266,6 +272,54 @@ 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() From cc2a2616d84d2d685818a37e784a381474f2e5dc Mon Sep 17 00:00:00 2001 From: Anankke Date: Fri, 20 Nov 2026 15:04:42 -0800 Subject: [PATCH 2/2] 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. --- .../components/account/AccountUsageCell.vue | 1 - .../__tests__/AccountUsageCell.spec.ts | 57 +++++- .../AccountUsageCell.usageRefresh.spec.ts | 174 ------------------ .../__tests__/accountUsageRefresh.spec.ts | 97 ++-------- frontend/src/utils/accountUsageRefresh.ts | 73 ++++---- .../admin/__tests__/AccountsView.lite.spec.ts | 57 +----- 6 files changed, 101 insertions(+), 358 deletions(-) delete mode 100644 frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 2a16ab98ce..8a5a8bd0fe 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -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(() => { diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index b7b0ced41b..7181f63c91 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -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() }) diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts deleted file mode 100644 index 33f2fcd953..0000000000 --- a/frontend/src/components/account/__tests__/AccountUsageCell.usageRefresh.spec.ts +++ /dev/null @@ -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('vue-i18n') - return { - ...actual, - useI18n: () => ({ - t: (key: string) => key - }) - } -}) - -function makeAccount(overrides: Partial): 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: '
{{ label }}|{{ utilization }}
' - }, - ClaudeResetCreditsCell: { template: '
' }, - 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) - }) -}) diff --git a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts index 4c9fcc0885..1bba33e58e 100644 --- a/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts +++ b/frontend/src/utils/__tests__/accountUsageRefresh.spec.ts @@ -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('') - }) -}) diff --git a/frontend/src/utils/accountUsageRefresh.ts b/frontend/src/utils/accountUsageRefresh.ts index ea5642fd6b..be01b6b415 100644 --- a/frontend/src/utils/accountUsageRefresh.ts +++ b/frontend/src/utils/accountUsageRefresh.ts @@ -52,43 +52,6 @@ export const buildOpenAIUsageRefreshKey = (account: Pick): 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): string => { - if (account.platform !== 'gemini') { - return '' - } - - return [ - account.id, - account.updated_at, - account.last_used_at - ].map(normalizeUsageRefreshValue).join('|') -} - export const buildGrokUsageRefreshKey = (account: Pick): string => { if (account.platform !== 'grok') { return '' @@ -107,9 +70,37 @@ export const buildGrokUsageRefreshKey = (account: Pick): string => { +export const buildAccountUsageRefreshKey = (account: Pick): 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 + ]) + ]) } diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index a7c8ee6aae..64115c43f5 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -82,11 +82,6 @@ const AccountGroupsCellStub = defineComponent({ template: '{{ groups.map(group => group.name).join(",") }}' }) -const AccountUsageCellStub = defineComponent({ - props: { account: { type: Object, required: true } }, - template: '{{ account.extra?.session_window_utilization }}|{{ account.last_used_at }}' -}) - const EditAccountModalStub = defineComponent({ props: { show: Boolean, account: { type: Object, default: null } }, template: '
{{ show ? account?.name : "" }}
' @@ -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()