mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
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.
This commit is contained in:
1 parent
d70676756f
commit
5f12044f59
6 files changed
+361
-7
No files matched your search
@@ -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(
|
||||
|
||||
@@ -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<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 }), { 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)
|
||||
})
|
||||
})
|
||||
@@ -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('')
|
||||
})
|
||||
})
|
||||
@@ -52,6 +52,43 @@ 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 ''
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ const DataTableStub = defineComponent({
|
||||
<div>
|
||||
<template v-if="!loading"><div v-for="row in data" :key="row.id" :data-account-name="row.name">
|
||||
<slot name="cell-groups" :row="row" />
|
||||
<slot name="cell-usage" :row="row" />
|
||||
<slot name="cell-actions" :row="row" />
|
||||
</div></template>
|
||||
</div>
|
||||
@@ -78,6 +79,11 @@ 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>'
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user