Revert "feat: combine usage quota and pool stats updates"

This reverts commit 1f5b294bd0.
This commit is contained in:
fawney19
2026-05-07 01:33:40 +08:00
parent 1f5b294bd0
commit df9d30340d
35 changed files with 123 additions and 3473 deletions

View File

@@ -39,7 +39,6 @@ describe('poolManagementState', () => {
pageSize: 20,
sortBy: 'last_used_at',
sortOrder: 'asc',
statsMode: 'account_total',
},
storage,
)
@@ -53,7 +52,6 @@ describe('poolManagementState', () => {
pageSize: '100',
sortBy: 'imported_at',
sortOrder: 'desc',
statsMode: 'current_cycle',
},
storage,
)
@@ -66,7 +64,6 @@ describe('poolManagementState', () => {
pageSize: 100,
sortBy: 'imported_at',
sortOrder: 'desc',
statsMode: 'current_cycle',
})
})
@@ -80,7 +77,6 @@ describe('poolManagementState', () => {
pageSize: 50,
sortBy: 'last_used_at',
sortOrder: 'asc',
statsMode: 'account_total',
},
storage,
)
@@ -95,7 +91,6 @@ describe('poolManagementState', () => {
pageSize: 50,
sortBy: 'last_used_at',
sortOrder: 'asc',
statsMode: 'account_total',
})
})
@@ -109,7 +104,6 @@ describe('poolManagementState', () => {
pageSize: 50,
sortBy: null,
sortOrder: 'desc',
statsMode: 'current_cycle',
}),
).toEqual({
providerId: 'provider-d',
@@ -119,7 +113,6 @@ describe('poolManagementState', () => {
pageSize: undefined,
sortBy: undefined,
sortOrder: undefined,
statsMode: undefined,
})
})
@@ -133,36 +126,13 @@ describe('poolManagementState', () => {
pageSize: 50,
sortBy: 'last_used_at',
sortOrder: 'asc',
statsMode: 'account_total',
}),
).toMatchObject({
sortBy: 'last_used_at',
sortOrder: 'asc',
statsMode: 'account_total',
})
})
it('restores stats mode from storage and lets query override it', () => {
writePoolManagementViewState(
{
providerId: 'provider-f',
search: '',
status: 'all',
page: 1,
pageSize: 50,
sortBy: null,
sortOrder: 'desc',
statsMode: 'account_total',
},
storage,
)
expect(readPoolManagementViewState({}, storage).statsMode).toBe('account_total')
expect(
readPoolManagementViewState({ statsMode: 'current_cycle' }, storage).statsMode,
).toBe('current_cycle')
})
it('clamps a restored page to the last available page after load', () => {
expect(
resolvePoolManagementPageAfterLoad({

View File

@@ -1,115 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
buildPoolStatsDisplay,
type PoolStatsKeyInput,
} from '@/features/pool/utils/poolStatsDisplay'
function metricValues(metrics: Array<{ key: string, value: string }>) {
return Object.fromEntries(metrics.map(metric => [metric.key, metric.value]))
}
function createCodexKey(overrides: Partial<PoolStatsKeyInput> = {}): PoolStatsKeyInput {
return {
request_count: 1234,
total_tokens: 5678000,
total_cost_usd: '12.3456',
status_snapshot: {
quota: {
windows: [
{
code: '5h',
usage: {
request_count: 5,
total_tokens: 2500,
total_cost_usd: '0.0045',
},
},
{
code: 'weekly',
usage: {
request_count: 0,
total_tokens: 0,
total_cost_usd: '0.00000000',
},
},
],
},
},
...overrides,
}
}
describe('poolStatsDisplay', () => {
it('builds Codex current-cycle groups in 5H and weekly order', () => {
const display = buildPoolStatsDisplay(createCodexKey(), 'codex', 'current_cycle')
expect(display.kind).toBe('codex_cycle')
if (display.kind !== 'codex_cycle') throw new Error('expected codex cycle display')
expect(display.groups.map(group => group.label)).toEqual(['5H', '周'])
expect(metricValues(display.groups[0].metrics)).toEqual({
request_count: '5',
total_tokens: '2.5K',
total_cost_usd: '$0.0045',
})
expect(metricValues(display.groups[1].metrics)).toEqual({
request_count: '0',
total_tokens: '0',
total_cost_usd: '0',
})
})
it('renders missing cycle usage as dashes instead of account-total fallback', () => {
const display = buildPoolStatsDisplay(
createCodexKey({
status_snapshot: {
quota: {
windows: [{ code: '5h', usage: null }],
},
},
}),
'codex',
'current_cycle',
)
expect(display.kind).toBe('codex_cycle')
if (display.kind !== 'codex_cycle') throw new Error('expected codex cycle display')
expect(metricValues(display.groups[0].metrics)).toEqual({
request_count: '—',
total_tokens: '—',
total_cost_usd: '—',
})
expect(metricValues(display.groups[1].metrics)).toEqual({
request_count: '—',
total_tokens: '—',
total_cost_usd: '—',
})
})
it('preserves account-total formatting when toggled away from current cycle', () => {
const display = buildPoolStatsDisplay(createCodexKey(), 'codex', 'account_total')
expect(display.kind).toBe('account_total')
if (display.kind !== 'account_total') throw new Error('expected account total display')
expect(metricValues(display.metrics)).toEqual({
request_count: '1,234',
total_tokens: '5.7M',
total_cost_usd: '$12.35',
})
})
it('keeps non-Codex providers on account totals even in current-cycle mode', () => {
const display = buildPoolStatsDisplay(createCodexKey(), 'openai', 'current_cycle')
expect(display.kind).toBe('account_total')
if (display.kind !== 'account_total') throw new Error('expected account total display')
expect(metricValues(display.metrics)).toMatchObject({
request_count: '1,234',
total_tokens: '5.7M',
total_cost_usd: '$12.35',
})
})
})

View File

@@ -1,7 +1,6 @@
export type PoolManagementStatus = 'all' | 'active' | 'cooldown' | 'inactive'
export type PoolManagementSortBy = 'imported_at' | 'last_used_at'
export type PoolManagementSortOrder = 'asc' | 'desc'
export type PoolManagementStatsMode = 'current_cycle' | 'account_total'
export interface PoolManagementViewState {
providerId: string | null
@@ -11,7 +10,6 @@ export interface PoolManagementViewState {
pageSize: number
sortBy: PoolManagementSortBy | null
sortOrder: PoolManagementSortOrder
statsMode: PoolManagementStatsMode
}
export interface PoolManagementStateSource {
@@ -22,7 +20,6 @@ export interface PoolManagementStateSource {
pageSize?: string
sortBy?: string
sortOrder?: string
statsMode?: string
}
export interface StorageLike {
@@ -31,10 +28,6 @@ export interface StorageLike {
removeItem(key: string): void
}
type PoolManagementViewStateInput = Partial<{
[Key in keyof PoolManagementViewState]: unknown
}>
export const POOL_MANAGEMENT_VIEW_STORAGE_KEY = 'aether:pool-management:view-state'
export const DEFAULT_POOL_MANAGEMENT_VIEW_STATE: PoolManagementViewState = {
@@ -45,7 +38,6 @@ export const DEFAULT_POOL_MANAGEMENT_VIEW_STATE: PoolManagementViewState = {
pageSize: 50,
sortBy: null,
sortOrder: 'desc',
statsMode: 'current_cycle',
}
function normalizeProviderId(value: unknown): string | null {
@@ -83,11 +75,7 @@ function normalizeSortOrder(value: unknown): PoolManagementSortOrder {
return value === 'asc' ? 'asc' : 'desc'
}
function normalizeStatsMode(value: unknown): PoolManagementStatsMode {
return value === 'account_total' ? 'account_total' : 'current_cycle'
}
function normalizeViewState(input: PoolManagementViewStateInput): PoolManagementViewState {
function normalizeViewState(input: Partial<PoolManagementViewState>): PoolManagementViewState {
return {
providerId: normalizeProviderId(input.providerId),
search: normalizeSearch(input.search),
@@ -96,7 +84,6 @@ function normalizeViewState(input: PoolManagementViewStateInput): PoolManagement
pageSize: normalizePositiveInteger(input.pageSize, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.pageSize),
sortBy: normalizeSortBy(input.sortBy),
sortOrder: normalizeSortOrder(input.sortOrder),
statsMode: normalizeStatsMode(input.statsMode),
}
}
@@ -119,20 +106,15 @@ export function readPoolManagementViewState(
): PoolManagementViewState {
const stored = normalizeViewState(readStoredState(storage))
return {
providerId: source.providerId !== undefined ? normalizeProviderId(source.providerId) : stored.providerId,
search: source.search !== undefined ? normalizeSearch(source.search) : stored.search,
status: source.status !== undefined ? normalizeStatus(source.status) : stored.status,
page: source.page !== undefined
? normalizePositiveInteger(source.page, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.page)
: stored.page,
pageSize: source.pageSize !== undefined
? normalizePositiveInteger(source.pageSize, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.pageSize)
: stored.pageSize,
sortBy: source.sortBy !== undefined ? normalizeSortBy(source.sortBy) : stored.sortBy,
sortOrder: source.sortOrder !== undefined ? normalizeSortOrder(source.sortOrder) : stored.sortOrder,
statsMode: source.statsMode !== undefined ? normalizeStatsMode(source.statsMode) : stored.statsMode,
}
return normalizeViewState({
providerId: source.providerId ?? stored.providerId,
search: source.search ?? stored.search,
status: source.status ?? stored.status,
page: source.page ?? stored.page,
pageSize: source.pageSize ?? stored.pageSize,
sortBy: source.sortBy ?? stored.sortBy,
sortOrder: source.sortOrder ?? stored.sortOrder,
})
}
export function writePoolManagementViewState(
@@ -168,7 +150,6 @@ export function buildPoolManagementQueryPatch(
: String(normalized.pageSize),
sortBy: normalized.sortBy || undefined,
sortOrder: normalized.sortBy ? normalized.sortOrder : undefined,
statsMode: normalized.statsMode === 'account_total' ? 'account_total' : undefined,
}
}

View File

@@ -1,178 +0,0 @@
import type { QuotaWindowUsageSnapshot } from '@/api/endpoints/types/statusSnapshot'
import type { PoolManagementStatsMode } from '@/features/pool/utils/poolManagementState'
export type PoolStatsMetricKey = 'request_count' | 'total_tokens' | 'total_cost_usd'
export type PoolStatsDisplayKind = 'account_total' | 'codex_cycle'
export type PoolCodexCycleWindowCode = '5h' | 'weekly'
export interface PoolStatsKeyInput {
request_count?: number | null
total_tokens?: number | null
total_cost_usd?: number | string | null
status_snapshot?: {
quota?: {
windows?: Array<{
code?: string | null
usage?: QuotaWindowUsageSnapshot | null
} | null> | null
} | null
} | null
}
export interface PoolStatsMetric {
key: PoolStatsMetricKey
label: string
value: string
missing: boolean
}
export interface PoolAccountTotalStatsDisplay {
kind: 'account_total'
metrics: PoolStatsMetric[]
}
export interface PoolCodexCycleStatsGroup {
code: PoolCodexCycleWindowCode
label: string
metrics: PoolStatsMetric[]
}
export interface PoolCodexCycleStatsDisplay {
kind: 'codex_cycle'
groups: PoolCodexCycleStatsGroup[]
}
export type PoolStatsDisplay = PoolAccountTotalStatsDisplay | PoolCodexCycleStatsDisplay
const MISSING_STAT_VALUE = '—'
const CODEX_CYCLE_WINDOWS: Array<{ code: PoolCodexCycleWindowCode, label: string }> = [
{ code: '5h', label: '5H' },
{ code: 'weekly', label: '周' },
]
export function isCodexProviderType(providerType: string | null | undefined): boolean {
return String(providerType || '').trim().toLowerCase() === 'codex'
}
export function formatPoolStatInteger(value: number | null | undefined): string {
const n = Number(value ?? 0)
if (!Number.isFinite(n) || n <= 0) return '0'
return Math.round(n).toLocaleString('en-US')
}
export function formatPoolTokenCount(value: number | null | undefined): string {
const n = Number(value ?? 0)
if (!Number.isFinite(n) || n <= 0) return '0'
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
return String(Math.round(n))
}
export function formatPoolStatUsd(value: number | string | null | undefined): string {
const n = Number(value ?? 0)
if (!Number.isFinite(n) || n <= 0) return '$0.00'
if (n < 0.01) return `$${n.toFixed(4)}`
if (n < 1) return `$${n.toFixed(3)}`
if (n < 1000) return `$${n.toFixed(2)}`
return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}
function formatCycleInteger(value: number | null | undefined): string | null {
if (value == null) return null
const n = Number(value)
if (!Number.isFinite(n)) return null
if (n <= 0) return '0'
return Math.round(n).toLocaleString('en-US')
}
function formatCycleTokenCount(value: number | null | undefined): string | null {
if (value == null) return null
const n = Number(value)
if (!Number.isFinite(n)) return null
return formatPoolTokenCount(n)
}
function formatCycleUsd(value: number | string | null | undefined): string | null {
if (value == null) return null
const n = Number(value)
if (!Number.isFinite(n)) return null
if (n <= 0) return '0'
return formatPoolStatUsd(value)
}
function createMetric(
key: PoolStatsMetricKey,
label: string,
value: string | null,
): PoolStatsMetric {
return {
key,
label,
value: value ?? MISSING_STAT_VALUE,
missing: value == null,
}
}
function normalizeWindowCode(value: unknown): string {
return String(value || '').trim().toLowerCase()
}
function getQuotaWindowUsage(
key: PoolStatsKeyInput,
code: PoolCodexCycleWindowCode,
): QuotaWindowUsageSnapshot | null {
const windows = key.status_snapshot?.quota?.windows
if (!Array.isArray(windows)) return null
const window = windows.find(item => normalizeWindowCode(item?.code) === code)
return window?.usage ?? null
}
function buildAccountTotalMetrics(key: PoolStatsKeyInput): PoolStatsMetric[] {
return [
createMetric('request_count', '请求', formatPoolStatInteger(key.request_count)),
createMetric('total_tokens', 'Token', formatPoolTokenCount(key.total_tokens)),
createMetric('total_cost_usd', '费用', formatPoolStatUsd(key.total_cost_usd)),
]
}
function buildCycleMetrics(usage: QuotaWindowUsageSnapshot | null): PoolStatsMetric[] {
return [
createMetric('request_count', '请求', formatCycleInteger(usage?.request_count)),
createMetric('total_tokens', 'Token', formatCycleTokenCount(usage?.total_tokens)),
createMetric('total_cost_usd', '费用', formatCycleUsd(usage?.total_cost_usd)),
]
}
export function buildAccountTotalStatsDisplay(
key: PoolStatsKeyInput,
): PoolAccountTotalStatsDisplay {
return {
kind: 'account_total',
metrics: buildAccountTotalMetrics(key),
}
}
export function buildCodexCycleStatsDisplay(
key: PoolStatsKeyInput,
): PoolCodexCycleStatsDisplay {
return {
kind: 'codex_cycle',
groups: CODEX_CYCLE_WINDOWS.map(window => ({
...window,
metrics: buildCycleMetrics(getQuotaWindowUsage(key, window.code)),
})),
}
}
export function buildPoolStatsDisplay(
key: PoolStatsKeyInput,
providerType: string | null | undefined,
mode: PoolManagementStatsMode,
): PoolStatsDisplay {
if (isCodexProviderType(providerType) && mode === 'current_cycle') {
return buildCodexCycleStatsDisplay(key)
}
return buildAccountTotalStatsDisplay(key)
}

View File

@@ -818,51 +818,6 @@
</div>
</template>
</div>
<!-- ChatGPT Web 上游额度信息(生图配额) -->
<div
v-if="provider.provider_type === 'chatgpt_web' && hasChatGPTWebQuotaDisplayData(key)"
class="mt-2 p-2 rounded-md bg-muted/30"
>
<div class="flex items-center justify-between mb-1">
<span class="text-[10px] text-muted-foreground">账号配额</span>
<div class="flex items-center gap-1">
<RefreshCw
v-if="refreshingQuota"
class="w-3 h-3 text-muted-foreground/70 animate-spin"
/>
<span
v-if="getChatGPTWebQuotaDisplay(key)?.updated_at"
class="text-[9px] text-muted-foreground/70"
>
{{ formatKiroUpdatedAt(getChatGPTWebQuotaDisplay(key)?.updated_at || 0) }}
</span>
</div>
</div>
<div>
<div class="flex items-center justify-between text-[10px] mb-0.5">
<span class="text-muted-foreground">使用额度</span>
<span :class="getQuotaRemainingClass(getChatGPTWebQuotaUsedPercent(key))">
{{ getChatGPTWebQuotaRemainingPercent(key).toFixed(1) }}%
</span>
</div>
<div class="relative w-full h-1.5 bg-border rounded-full overflow-hidden">
<div
class="absolute left-0 top-0 h-full transition-all duration-300"
:class="getQuotaRemainingBarColor(getChatGPTWebQuotaUsedPercent(key))"
:style="{ width: `${Math.max(getChatGPTWebQuotaRemainingPercent(key), 0)}%` }"
/>
</div>
<div class="flex items-center justify-between text-[9px] text-muted-foreground/70 mt-0.5">
<span>
{{ formatChatGPTWebUsage(getChatGPTWebQuotaDisplay(key)?.image_quota_used) }} /
{{ formatChatGPTWebUsage(getChatGPTWebQuotaDisplay(key)?.image_quota_total) }}
</span>
<span v-if="getChatGPTWebQuotaDisplay(key)?.image_quota_reset_at">
{{ formatKiroResetTime(getChatGPTWebQuotaDisplay(key)?.image_quota_reset_at) }}重置
</span>
</div>
</div>
</div>
<!-- 第二行:优先级 + API 格式(展开显示) + 统计信息 -->
<div class="flex items-center gap-1.5 mt-1 text-[11px] text-muted-foreground">
<!-- 优先级放最前面,支持点击编辑 -->
@@ -1210,7 +1165,6 @@ import type {
AntigravityModelQuota,
AntigravityUpstreamMetadata,
CodexUpstreamMetadata,
ChatGPTWebUpstreamMetadata,
KiroUpstreamMetadata,
QuotaStatusSnapshot,
QuotaWindowSnapshot,
@@ -1861,7 +1815,7 @@ async function handleClearOAuthInvalid(key: EndpointAPIKey) {
}
}
// Codex / Antigravity / Kiro / ChatGPT Web:打开抽屉后自动后台刷新(配额缓存缺失/过期,或 Token 即将过期时触发)
// Codex / Antigravity / Kiro打开抽屉后自动后台刷新配额缓存缺失/过期,或 Token 即将过期时触发)
const AUTO_QUOTA_REFRESH_STALE_SECONDS = 5 * 60
// 与后端 OAuth 懒刷新阈值对齐:到期前 2 分钟内视为需要刷新
const AUTO_TOKEN_REFRESH_SKEW_SECONDS = 2 * 60
@@ -1880,7 +1834,7 @@ function quotaSnapshotHasDisplayData(quota: QuotaStatusSnapshot | null | undefin
function getQuotaSnapshotForProvider(
key: EndpointAPIKey,
providerType: 'codex' | 'kiro' | 'antigravity' | 'chatgpt_web' | 'gemini_cli',
providerType: 'codex' | 'kiro' | 'antigravity' | 'gemini_cli',
): QuotaStatusSnapshot | null {
const quota = key.status_snapshot?.quota
if (!quota) return null
@@ -2052,86 +2006,6 @@ function hasKiroQuotaDisplayData(key: EndpointAPIKey): boolean {
return !!kiro && (kiro.usage_percentage !== undefined || kiro.usage_limit !== undefined)
}
type ChatGPTWebQuotaDisplay = ChatGPTWebUpstreamMetadata & {
image_quota_remaining_percent?: number
image_quota_used_percent?: number
}
function getChatGPTWebQuotaDisplay(key: EndpointAPIKey): ChatGPTWebQuotaDisplay | null {
const quota = getQuotaSnapshotForProvider(key, 'chatgpt_web')
if (!quota) return null
const display: ChatGPTWebQuotaDisplay = {}
const updatedAt = getQuotaSnapshotUpdatedAt(quota)
if (updatedAt !== undefined) display.updated_at = updatedAt
if (quota.plan_type) display.plan_type = quota.plan_type
if (quota.code === 'exhausted' || quota.code === 'banned') display.image_quota_blocked = true
const imageWindow =
getQuotaWindow(quota, 'image_gen')
?? getQuotaWindowByScope(quota, 'account')[0]
?? null
if (imageWindow) {
const remainingValue = typeof imageWindow.remaining_value === 'number' ? imageWindow.remaining_value : undefined
const limitValue = typeof imageWindow.limit_value === 'number' ? imageWindow.limit_value : undefined
const usedValue = typeof imageWindow.used_value === 'number' ? imageWindow.used_value : undefined
const remainingPercent = getQuotaWindowRemainingPercent(imageWindow)
const usedPercent = getQuotaWindowUsedPercent(imageWindow)
if (remainingValue !== undefined) display.image_quota_remaining = remainingValue
if (limitValue !== undefined) display.image_quota_total = limitValue
if (usedValue !== undefined) display.image_quota_used = usedValue
if (remainingPercent !== undefined) display.image_quota_remaining_percent = remainingPercent
if (usedPercent !== undefined) display.image_quota_used_percent = usedPercent
if (typeof imageWindow.reset_at === 'number') display.image_quota_reset_at = imageWindow.reset_at
if (typeof imageWindow.reset_seconds === 'number') {
const resetAt = updatedAt === undefined ? undefined : updatedAt + imageWindow.reset_seconds
if (resetAt !== undefined && display.image_quota_reset_at === undefined) {
display.image_quota_reset_at = resetAt
}
}
}
return Object.keys(display).length > 0 ? display : null
}
function hasChatGPTWebQuotaDisplayData(key: EndpointAPIKey): boolean {
const display = getChatGPTWebQuotaDisplay(key)
return !!display && (
display.image_quota_remaining_percent !== undefined
|| display.image_quota_total !== undefined
|| display.image_quota_used !== undefined
)
}
function getChatGPTWebQuotaUsedPercent(key: EndpointAPIKey): number {
const display = getChatGPTWebQuotaDisplay(key)
if (!display) return 0
if (typeof display.image_quota_used_percent === 'number') return display.image_quota_used_percent
if (typeof display.image_quota_remaining_percent === 'number') {
return Math.max(100 - display.image_quota_remaining_percent, 0)
}
return 0
}
function getChatGPTWebQuotaRemainingPercent(key: EndpointAPIKey): number {
const display = getChatGPTWebQuotaDisplay(key)
if (!display) return 0
if (typeof display.image_quota_remaining_percent === 'number') return display.image_quota_remaining_percent
if (typeof display.image_quota_used_percent === 'number') {
return Math.max(100 - display.image_quota_used_percent, 0)
}
return 0
}
function formatChatGPTWebUsage(value: number | null | undefined): string {
if (value === undefined || value === null) return '-'
if (Math.abs(value - Math.round(value)) < 1e-6) {
return String(Math.round(value))
}
return value.toFixed(1)
}
function isKiroBannedKey(key: EndpointAPIKey): boolean {
const quota = getQuotaSnapshotForProvider(key, 'kiro')
return String(quota?.code || '').trim().toLowerCase() === 'banned'
@@ -2264,7 +2138,7 @@ function shouldAutoRefreshCodexQuota(): boolean {
return false
}
// 检查 OAuth Token 是否即将过期Codex / Antigravity / Kiro / ChatGPT Web
// 检查 OAuth Token 是否即将过期Codex / Antigravity / Kiro
function isTokenExpiringSoon(key: EndpointAPIKey, now: number): boolean {
const oauthCode = String(key.status_snapshot?.oauth?.code || '').trim().toLowerCase()
if (oauthCode && oauthCode !== 'valid' && oauthCode !== 'expiring') {
@@ -2319,28 +2193,6 @@ function shouldAutoRefreshKiroQuota(): boolean {
return false
}
function shouldAutoRefreshChatGPTWebQuota(): boolean {
if (provider.value?.provider_type !== 'chatgpt_web') return false
const now = Math.floor(Date.now() / 1000)
for (const { key } of allKeys.value) {
if (!key.is_active) continue
if (isTokenExpiringSoon(key, now)) return true
if (!hasChatGPTWebQuotaDisplayData(key)) {
return true
}
const updatedAt = getChatGPTWebQuotaDisplay(key)?.updated_at
if (typeof updatedAt !== 'number' || (now - updatedAt) > AUTO_QUOTA_REFRESH_STALE_SECONDS) {
return true
}
}
return false
}
function defaultQuotaSnapshot(): QuotaStatusSnapshot {
return {
code: 'unknown',
@@ -2418,14 +2270,14 @@ function applyQuotaResults(
return applied
}
// 通用的自动刷新配额函数(支持 Codex、AntigravityKiro 和 ChatGPT Web
// 通用的自动刷新配额函数(支持 Codex、AntigravityKiro
async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean } = {}) {
const providerId = props.providerId
if (!providerId) return
if (refreshingQuota.value) return
const providerType = provider.value?.provider_type
if (providerType !== 'codex' && providerType !== 'antigravity' && providerType !== 'kiro' && providerType !== 'chatgpt_web') return
if (providerType !== 'codex' && providerType !== 'antigravity' && providerType !== 'kiro') return
// 检查是否需要刷新
let shouldRefresh = false
@@ -2435,8 +2287,6 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
shouldRefresh = shouldAutoRefreshAntigravityQuota()
} else if (providerType === 'kiro') {
shouldRefresh = shouldAutoRefreshKiroQuota()
} else if (providerType === 'chatgpt_web') {
shouldRefresh = shouldAutoRefreshChatGPTWebQuota()
}
if (!shouldRefresh) return
if (!options.ignoreCooldown && isProviderQuotaAutoRefreshCoolingDown(providerId)) return
@@ -2448,8 +2298,6 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasAntigravityQuotaDisplayData(key))
} else if (providerType === 'kiro') {
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasKiroQuotaDisplayData(key))
} else if (providerType === 'chatgpt_web') {
hadCachedQuota = allKeys.value.some(({ key }) => key.is_active && hasChatGPTWebQuotaDisplayData(key))
}
refreshingQuota.value = true

View File

@@ -272,28 +272,16 @@
<!-- 耗时 -->
<span
v-if="getDisplayStatus(record) === 'pending' || getDisplayStatus(record) === 'streaming'"
class="tabular-nums whitespace-nowrap"
>
<span>{{ formatRecordDurationSeconds(record.first_byte_time_ms) }}</span>
<span class="text-muted-foreground"> / </span>
<ElapsedTimeText
class="text-primary"
:created-at="record.created_at"
:status="getDisplayStatus(record)"
:response-time-ms="record.response_time_ms ?? null"
/>
</span>
class="text-primary tabular-nums"
><ElapsedTimeText
:created-at="record.created_at"
:status="getDisplayStatus(record)"
:response-time-ms="record.response_time_ms ?? null"
/></span>
<span
v-else-if="record.response_time_ms != null || record.first_byte_time_ms != null"
class="flex flex-col items-end tabular-nums leading-3 shrink-0"
:title="getRecordPerformanceTitle(record)"
>
<span class="whitespace-nowrap">{{ formatRecordLatencyPair(record) }}</span>
<span
v-if="getRecordDisplayOutputRate(record) != null"
class="text-muted-foreground tabular-nums whitespace-nowrap"
>{{ formatOutputRate(getRecordDisplayOutputRate(record)) }}</span>
</span>
class="tabular-nums"
>{{ record.first_byte_time_ms != null ? (record.first_byte_time_ms / 1000).toFixed(1) + '/' : '' }}{{ record.response_time_ms != null ? (record.response_time_ms / 1000).toFixed(1) : '-' }}{{ record.response_time_ms != null ? 's' : '' }}</span>
<span
v-else
class="tabular-nums"
@@ -322,12 +310,12 @@
<colgroup v-else>
<col class="w-[9%]">
<col class="w-[17%]">
<col class="w-[24%]">
<col class="w-[26%]">
<col class="w-[15%]">
<col class="w-[7%]">
<col class="w-[11%]">
<col class="w-[7%]">
<col class="w-[10%]">
<col class="w-[8%]">
</colgroup>
<TableHeader>
<TableRow class="border-b border-border/60 hover:bg-transparent">
@@ -441,8 +429,8 @@
</TableHead>
<TableHead class="h-12 font-semibold w-[9%] text-right">
<div class="flex flex-col items-end text-xs gap-0.5">
<span class="whitespace-nowrap">首字/总耗时</span>
<span class="text-muted-foreground font-normal">输出速度</span>
<span>首字</span>
<span class="text-muted-foreground font-normal">总耗时</span>
</div>
</TableHead>
</TableRow>
@@ -728,33 +716,58 @@
</div>
</TableCell>
<TableCell class="text-right py-4 w-[9%]">
<!-- pending/streaming 状态首字与动态总耗时保留在同一行 -->
<!-- pending 状态只显示增长的总时间 -->
<div
v-if="getDisplayStatus(record) === 'pending' || getDisplayStatus(record) === 'streaming'"
v-if="getDisplayStatus(record) === 'pending'"
class="flex flex-col items-end text-xs gap-0.5"
>
<span class="tabular-nums whitespace-nowrap">
<span>{{ formatRecordDurationSeconds(record.first_byte_time_ms) }}</span>
<span class="text-muted-foreground"> / </span>
<ElapsedTimeText
class="text-primary"
:created-at="record.created_at"
:status="getDisplayStatus(record)"
:response-time-ms="record.response_time_ms ?? null"
/>
</span>
<span class="text-muted-foreground">-</span>
<span class="text-primary tabular-nums"><ElapsedTimeText
:created-at="record.created_at"
:status="getDisplayStatus(record)"
:response-time-ms="record.response_time_ms ?? null"
/></span>
</div>
<!-- streaming 状态首字固定 + 总时间增长 -->
<div
v-else-if="getDisplayStatus(record) === 'streaming'"
class="flex flex-col items-end text-xs gap-0.5"
>
<span
v-if="record.first_byte_time_ms != null"
class="tabular-nums"
>{{ (record.first_byte_time_ms / 1000).toFixed(2) }}s</span>
<span
v-else
class="text-muted-foreground"
>-</span>
<span class="text-primary tabular-nums"><ElapsedTimeText
:created-at="record.created_at"
:status="getDisplayStatus(record)"
:response-time-ms="record.response_time_ms ?? null"
/></span>
</div>
<!-- 已完成状态首字 + 总耗时 -->
<div
v-else-if="record.response_time_ms != null || record.first_byte_time_ms != null"
class="flex flex-col items-end text-xs gap-0.5"
:title="getRecordPerformanceTitle(record)"
>
<span class="tabular-nums whitespace-nowrap">{{ formatRecordLatencyPair(record) }}</span>
<span
v-if="getRecordDisplayOutputRate(record) != null"
class="text-muted-foreground tabular-nums whitespace-nowrap"
>{{ formatOutputRate(getRecordDisplayOutputRate(record)) }}</span>
v-if="record.first_byte_time_ms != null"
class="tabular-nums"
>{{ (record.first_byte_time_ms / 1000).toFixed(2) }}s</span>
<span
v-else
class="text-muted-foreground"
>-</span>
<span
v-if="record.response_time_ms != null"
class="text-muted-foreground tabular-nums"
>{{ (record.response_time_ms / 1000).toFixed(2) }}s</span>
<span
v-else
class="text-muted-foreground"
>-</span>
</div>
<span
v-else
@@ -807,12 +820,6 @@ import {
import { RefreshCcw, Search } from 'lucide-vue-next'
import { formatTokens, formatCurrency } from '@/utils/format'
import { getCacheCreationTokens, getCacheReadTokens, getEffectiveInputTokens } from '../token-normalization'
import {
formatOutputRate,
formatOutputRateValue,
getDisplayOutputRate,
getGenerationTimeMs,
} from '../performance'
import {
formatUsageStreamLabel,
isUsageRecordFailed,
@@ -1033,43 +1040,6 @@ function formatOptionalTokens(value: number | null | undefined): string {
return hasPositiveTokens(value) ? formatTokens(value) : '-'
}
function formatRecordLatencyPair(record: UsageRecord): string {
const firstByte = formatRecordDurationSeconds(record.first_byte_time_ms)
const total = formatRecordDurationSeconds(record.response_time_ms)
return `${firstByte} / ${total}`
}
function formatRecordDurationSeconds(ms: number | null | undefined): string {
if (ms == null || !Number.isFinite(ms)) return '-'
return `${(ms / 1000).toFixed(2)}s`
}
function getRecordDisplayOutputRate(record: UsageRecord): number | null {
return getDisplayOutputRate({
output_tokens: record.output_tokens,
response_time_ms: record.response_time_ms,
first_byte_time_ms: record.first_byte_time_ms,
is_stream: record.is_stream,
upstream_is_stream: record.upstream_is_stream,
})
}
function getRecordPerformanceTitle(record: UsageRecord): string {
const outputRate = getRecordDisplayOutputRate(record)
return [
`首字: ${formatRecordDurationSeconds(record.first_byte_time_ms)}`,
`总耗时: ${formatRecordDurationSeconds(record.response_time_ms)}`,
`生成耗时: ${formatRecordDurationSeconds(getGenerationTimeMs(record))}`,
`输出速度: ${formatOutputRateTokensPerSecond(outputRate)}`,
].join('\n')
}
function formatOutputRateTokensPerSecond(outputRate: number | null | undefined): string {
const value = formatOutputRateValue(outputRate)
if (value === '-') return value
return `${value} tokens/s`
}
// useDebounceFn 自动处理清理,无需 onUnmounted
// 判断是否应该显示格式转换信息

View File

@@ -1,211 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createApp, defineComponent, h, type App } from 'vue'
import UsageRecordsTable from '../UsageRecordsTable.vue'
import type { UsageRecord } from '../../types'
vi.mock('@/components/ui', async () => {
const { defineComponent, h } = await import('vue')
const passthrough = (name: string, tag = 'div') => defineComponent({
name,
setup(_, { slots }) {
return () => h(tag, [
slots.default?.(),
slots.actions?.(),
slots.pagination?.(),
slots.filter?.({ close: () => undefined }),
])
},
})
return {
TableCard: passthrough('TableCardStub', 'section'),
Badge: passthrough('BadgeStub', 'span'),
Button: passthrough('ButtonStub', 'button'),
Input: defineComponent({
name: 'InputStub',
props: { modelValue: String },
emits: ['update:modelValue'],
setup(props, { attrs, emit }) {
return () => h('input', {
...attrs,
value: props.modelValue ?? '',
onInput: (event: Event) => emit('update:modelValue', (event.target as HTMLInputElement).value),
})
},
}),
Select: passthrough('SelectStub'),
SelectTrigger: passthrough('SelectTriggerStub'),
SelectValue: passthrough('SelectValueStub', 'span'),
SelectContent: passthrough('SelectContentStub'),
SelectItem: passthrough('SelectItemStub'),
Table: passthrough('TableStub', 'table'),
TableHeader: passthrough('TableHeaderStub', 'thead'),
TableBody: passthrough('TableBodyStub', 'tbody'),
TableRow: passthrough('TableRowStub', 'tr'),
TableHead: passthrough('TableHeadStub', 'th'),
TableCell: passthrough('TableCellStub', 'td'),
Pagination: passthrough('PaginationStub'),
SortableTableHead: passthrough('SortableTableHeadStub', 'th'),
TableFilterMenu: passthrough('TableFilterMenuStub'),
}
})
vi.mock('@/components/common', async () => {
const { defineComponent, h } = await import('vue')
return {
TimeRangePicker: defineComponent({
name: 'TimeRangePickerStub',
setup() {
return () => h('div')
},
}),
}
})
vi.mock('lucide-vue-next', async () => {
const { defineComponent, h } = await import('vue')
const Icon = defineComponent({
name: 'IconStub',
setup() {
return () => h('span')
},
})
return {
RefreshCcw: Icon,
Search: Icon,
}
})
vi.mock('../ElapsedTimeText.vue', () => ({
default: defineComponent({
name: 'ElapsedTimeTextStub',
setup() {
return () => h('span', 'elapsed')
},
}),
}))
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
function buildRecord(overrides: Partial<UsageRecord> = {}): UsageRecord {
return {
id: 'usage-1',
model: 'gpt-5',
input_tokens: 100,
output_tokens: 50,
total_tokens: 150,
cost: 0.01,
response_time_ms: 1000,
first_byte_time_ms: 500,
is_stream: true,
upstream_is_stream: true,
status: 'completed',
created_at: '2026-05-06T12:00:00Z',
...overrides,
}
}
function mountUsageRecordsTable(records: UsageRecord[], overrides: Record<string, unknown> = {}) {
const root = document.createElement('div')
document.body.appendChild(root)
const app = createApp(UsageRecordsTable, {
records,
isAdmin: true,
showActualCost: false,
loading: false,
timeRange: { preset: 'today', tz_offset_minutes: 0 },
filterSearch: '',
filterUser: '__all__',
filterModel: '__all__',
filterProvider: '__all__',
filterApiFormat: '__all__',
filterStatus: '__all__',
availableUsers: [],
availableModels: [],
availableProviders: [],
currentPage: 1,
pageSize: 20,
totalRecords: records.length,
pageSizeOptions: [20, 50],
autoRefresh: false,
...overrides,
})
app.mount(root)
mountedApps.push({ app, root })
return root
}
afterEach(() => {
for (const { app, root } of mountedApps.splice(0)) {
app.unmount()
root.remove()
}
})
describe('UsageRecordsTable', () => {
it('shows output TPS after the request completes', () => {
const root = mountUsageRecordsTable([buildRecord()])
expect(root.textContent).toContain('输出速度')
expect(root.textContent).toContain('0.50s / 1.00s')
expect(root.textContent).not.toContain('500ms')
expect(root.textContent).toContain('100 tps')
expect([...root.querySelectorAll<HTMLElement>('.text-muted-foreground')]
.some((element) => element.textContent?.includes('100 tps'))).toBe(true)
const tpsElements = [...root.querySelectorAll<HTMLElement>('.text-muted-foreground')]
.filter((element) => element.textContent?.trim() === '100 tps')
expect(tpsElements.some((element) => element.classList.contains('text-[11px]'))).toBe(false)
const titles = [...root.querySelectorAll<HTMLElement>('[title]')].map((element) => element.title)
expect(titles).toContain([
'首字: 0.50s',
'总耗时: 1.00s',
'生成耗时: 0.50s',
'输出速度: 100 tokens/s',
].join('\n'))
expect(titles.join('\n')).not.toContain('500ms')
expect(titles.join('\n')).not.toContain('首字后生成耗时')
})
it('keeps active request latency in one first-byte / live-total line without TPS', () => {
const root = mountUsageRecordsTable([buildRecord({
status: 'streaming',
response_time_ms: null,
first_byte_time_ms: 500,
})])
expect(root.textContent).toContain('0.50s')
expect(root.textContent).toContain('elapsed')
expect(root.textContent).toContain('0.50s / elapsed')
expect(root.textContent).not.toContain('100 tps')
expect(root.textContent).not.toContain('生成中')
expect(root.textContent).not.toContain('等待首字')
expect(root.querySelector('[data-active-latency-state="streaming"]')).toBeNull()
})
it('uses a first-byte placeholder and live total before the first byte arrives', () => {
const root = mountUsageRecordsTable([buildRecord({
status: 'pending',
response_time_ms: null,
first_byte_time_ms: null,
})])
expect(root.textContent).toContain('- / elapsed')
expect(root.textContent).toContain('elapsed')
expect(root.textContent).not.toContain('等待首字')
expect(root.querySelector('[data-active-latency-state="waiting-first-byte"]')).toBeNull()
})
it('renders output TPS in the non-admin usage table', () => {
const root = mountUsageRecordsTable([buildRecord()], { isAdmin: false })
expect(root.textContent).toContain('100 tps')
expect(root.textContent).toContain('0.50s / 1.00s')
expect(root.textContent).toContain('gpt-5')
})
})