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()