mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 01:10:23 +08:00
Merge branch 'pr-390' into aether-rust-pioneer
This commit is contained in:
@@ -18,6 +18,12 @@ export interface AccountStatusSnapshot {
|
||||
recoverable?: boolean
|
||||
}
|
||||
|
||||
export interface QuotaWindowUsageSnapshot {
|
||||
request_count?: number | null
|
||||
total_tokens?: number | null
|
||||
total_cost_usd?: number | string | null
|
||||
}
|
||||
|
||||
export interface QuotaWindowSnapshot {
|
||||
code: string
|
||||
label?: string | null
|
||||
@@ -33,6 +39,7 @@ export interface QuotaWindowSnapshot {
|
||||
reset_seconds?: number | null
|
||||
window_minutes?: number | null
|
||||
is_exhausted?: boolean | null
|
||||
usage?: QuotaWindowUsageSnapshot | null
|
||||
}
|
||||
|
||||
export interface QuotaCreditsSnapshot {
|
||||
|
||||
@@ -39,6 +39,7 @@ describe('poolManagementState', () => {
|
||||
pageSize: 20,
|
||||
sortBy: 'last_used_at',
|
||||
sortOrder: 'asc',
|
||||
statsMode: 'account_total',
|
||||
},
|
||||
storage,
|
||||
)
|
||||
@@ -52,6 +53,7 @@ describe('poolManagementState', () => {
|
||||
pageSize: '100',
|
||||
sortBy: 'imported_at',
|
||||
sortOrder: 'desc',
|
||||
statsMode: 'current_cycle',
|
||||
},
|
||||
storage,
|
||||
)
|
||||
@@ -64,6 +66,7 @@ describe('poolManagementState', () => {
|
||||
pageSize: 100,
|
||||
sortBy: 'imported_at',
|
||||
sortOrder: 'desc',
|
||||
statsMode: 'current_cycle',
|
||||
})
|
||||
})
|
||||
|
||||
@@ -77,6 +80,7 @@ describe('poolManagementState', () => {
|
||||
pageSize: 50,
|
||||
sortBy: 'last_used_at',
|
||||
sortOrder: 'asc',
|
||||
statsMode: 'account_total',
|
||||
},
|
||||
storage,
|
||||
)
|
||||
@@ -91,6 +95,7 @@ describe('poolManagementState', () => {
|
||||
pageSize: 50,
|
||||
sortBy: 'last_used_at',
|
||||
sortOrder: 'asc',
|
||||
statsMode: 'account_total',
|
||||
})
|
||||
})
|
||||
|
||||
@@ -104,6 +109,7 @@ describe('poolManagementState', () => {
|
||||
pageSize: 50,
|
||||
sortBy: null,
|
||||
sortOrder: 'desc',
|
||||
statsMode: 'current_cycle',
|
||||
}),
|
||||
).toEqual({
|
||||
providerId: 'provider-d',
|
||||
@@ -113,6 +119,7 @@ describe('poolManagementState', () => {
|
||||
pageSize: undefined,
|
||||
sortBy: undefined,
|
||||
sortOrder: undefined,
|
||||
statsMode: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -126,13 +133,36 @@ 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({
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
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',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
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
|
||||
@@ -10,6 +11,7 @@ export interface PoolManagementViewState {
|
||||
pageSize: number
|
||||
sortBy: PoolManagementSortBy | null
|
||||
sortOrder: PoolManagementSortOrder
|
||||
statsMode: PoolManagementStatsMode
|
||||
}
|
||||
|
||||
export interface PoolManagementStateSource {
|
||||
@@ -20,6 +22,7 @@ export interface PoolManagementStateSource {
|
||||
pageSize?: string
|
||||
sortBy?: string
|
||||
sortOrder?: string
|
||||
statsMode?: string
|
||||
}
|
||||
|
||||
export interface StorageLike {
|
||||
@@ -28,6 +31,10 @@ 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 = {
|
||||
@@ -38,6 +45,7 @@ export const DEFAULT_POOL_MANAGEMENT_VIEW_STATE: PoolManagementViewState = {
|
||||
pageSize: 50,
|
||||
sortBy: null,
|
||||
sortOrder: 'desc',
|
||||
statsMode: 'current_cycle',
|
||||
}
|
||||
|
||||
function normalizeProviderId(value: unknown): string | null {
|
||||
@@ -75,7 +83,11 @@ function normalizeSortOrder(value: unknown): PoolManagementSortOrder {
|
||||
return value === 'asc' ? 'asc' : 'desc'
|
||||
}
|
||||
|
||||
function normalizeViewState(input: Partial<PoolManagementViewState>): PoolManagementViewState {
|
||||
function normalizeStatsMode(value: unknown): PoolManagementStatsMode {
|
||||
return value === 'account_total' ? 'account_total' : 'current_cycle'
|
||||
}
|
||||
|
||||
function normalizeViewState(input: PoolManagementViewStateInput): PoolManagementViewState {
|
||||
return {
|
||||
providerId: normalizeProviderId(input.providerId),
|
||||
search: normalizeSearch(input.search),
|
||||
@@ -84,6 +96,7 @@ function normalizeViewState(input: Partial<PoolManagementViewState>): PoolManage
|
||||
pageSize: normalizePositiveInteger(input.pageSize, DEFAULT_POOL_MANAGEMENT_VIEW_STATE.pageSize),
|
||||
sortBy: normalizeSortBy(input.sortBy),
|
||||
sortOrder: normalizeSortOrder(input.sortOrder),
|
||||
statsMode: normalizeStatsMode(input.statsMode),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,15 +119,20 @@ export function readPoolManagementViewState(
|
||||
): PoolManagementViewState {
|
||||
const stored = normalizeViewState(readStoredState(storage))
|
||||
|
||||
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,
|
||||
})
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
export function writePoolManagementViewState(
|
||||
@@ -150,6 +168,7 @@ export function buildPoolManagementQueryPatch(
|
||||
: String(normalized.pageSize),
|
||||
sortBy: normalized.sortBy || undefined,
|
||||
sortOrder: normalized.sortBy ? normalized.sortOrder : undefined,
|
||||
statsMode: normalized.statsMode === 'account_total' ? 'account_total' : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
178
frontend/src/features/pool/utils/poolStatsDisplay.ts
Normal file
178
frontend/src/features/pool/utils/poolStatsDisplay.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
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)
|
||||
}
|
||||
@@ -76,6 +76,34 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="showCodexStatsModeSwitch"
|
||||
class="flex items-center"
|
||||
data-testid="pool-mobile-header-actions"
|
||||
>
|
||||
<div
|
||||
class="group inline-flex min-h-12 flex-col items-center justify-center gap-1 rounded-md border border-border/50 bg-muted/20 px-2.5 py-1.5 text-xs transition-all duration-200 hover:border-primary/40 hover:bg-muted/40"
|
||||
data-testid="pool-stats-mode-control"
|
||||
>
|
||||
<div class="flex items-center gap-1 leading-none">
|
||||
<span
|
||||
class="font-medium transition-colors"
|
||||
:class="!codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||
>累计</span>
|
||||
<span class="text-muted-foreground/50 transition-colors group-hover:text-muted-foreground/80">/</span>
|
||||
<span
|
||||
class="font-medium transition-colors"
|
||||
:class="codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||
>周期</span>
|
||||
</div>
|
||||
<Switch
|
||||
v-model="codexCurrentCycleStatsEnabled"
|
||||
class="shrink-0"
|
||||
aria-label="Codex 统计模式"
|
||||
data-testid="pool-stats-mode-switch"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="selectedProviderId"
|
||||
class="flex items-center gap-1"
|
||||
@@ -171,7 +199,10 @@
|
||||
</span>
|
||||
</h3>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<div
|
||||
class="flex items-center gap-2"
|
||||
data-testid="pool-header-actions"
|
||||
>
|
||||
<Select
|
||||
v-model="selectedProviderIdProxy"
|
||||
:disabled="providerSelectDisabled"
|
||||
@@ -228,6 +259,33 @@
|
||||
v-if="selectedProviderId"
|
||||
class="h-4 w-px bg-border"
|
||||
/>
|
||||
<div
|
||||
v-if="showCodexStatsModeSwitch"
|
||||
class="group inline-flex min-h-12 flex-col items-center justify-center gap-1 rounded-md border border-border/50 bg-muted/20 px-2.5 py-1.5 text-xs transition-all duration-200 hover:border-primary/40 hover:bg-muted/40"
|
||||
data-testid="pool-stats-mode-control"
|
||||
>
|
||||
<div class="flex items-center gap-1 leading-none">
|
||||
<span
|
||||
class="font-medium transition-colors"
|
||||
:class="!codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||
>累计</span>
|
||||
<span class="text-muted-foreground/50 transition-colors group-hover:text-muted-foreground/80">/</span>
|
||||
<span
|
||||
class="font-medium transition-colors"
|
||||
:class="codexCurrentCycleStatsEnabled ? 'text-foreground/90' : 'text-muted-foreground/80'"
|
||||
>周期</span>
|
||||
</div>
|
||||
<Switch
|
||||
v-model="codexCurrentCycleStatsEnabled"
|
||||
class="shrink-0"
|
||||
aria-label="Codex 统计模式"
|
||||
data-testid="pool-stats-mode-switch"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="showCodexStatsModeSwitch"
|
||||
class="h-4 w-px bg-border"
|
||||
/>
|
||||
<Button
|
||||
v-if="selectedProviderId"
|
||||
variant="ghost"
|
||||
@@ -571,23 +629,44 @@
|
||||
>-</span>
|
||||
</TableCell>
|
||||
<TableCell class="py-3 px-2 align-middle">
|
||||
<div class="grid grid-rows-3 gap-0.5 w-[136px] mx-auto text-[10px] leading-4">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground">请求</span>
|
||||
<span class="tabular-nums text-foreground/90">
|
||||
{{ formatStatInteger(key.request_count) }}
|
||||
</span>
|
||||
<div
|
||||
v-if="isPoolKeyCycleStatsDisplay(key)"
|
||||
class="mx-auto w-[136px] space-y-1.5 text-[10px] leading-4"
|
||||
data-testid="pool-stats-cycle-groups"
|
||||
>
|
||||
<div
|
||||
v-for="group in getPoolKeyCycleStatsGroups(key)"
|
||||
:key="`${key.key_id}-${group.code}-desktop-stats`"
|
||||
:data-testid="`pool-stats-cycle-group-${group.code}`"
|
||||
>
|
||||
<div class="text-[9px] text-muted-foreground/70 font-medium mb-0.5">{{ group.label }}</div>
|
||||
<div
|
||||
v-for="metric in group.metrics"
|
||||
:key="`${group.code}-${metric.key}`"
|
||||
class="flex items-center justify-between gap-2"
|
||||
>
|
||||
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||
<span
|
||||
class="tabular-nums text-foreground/90"
|
||||
:class="metric.missing ? 'text-muted-foreground/80' : ''"
|
||||
:data-testid="`pool-stats-${group.code}-${metric.key}`"
|
||||
>{{ metric.value }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground">Token</span>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="grid grid-rows-3 gap-0.5 w-[136px] mx-auto text-[10px] leading-4"
|
||||
data-testid="pool-stats-account-total"
|
||||
>
|
||||
<div
|
||||
v-for="metric in getPoolKeyAccountStatsMetrics(key)"
|
||||
:key="`${key.key_id}-${metric.key}-account-total`"
|
||||
class="flex items-center justify-between gap-2"
|
||||
>
|
||||
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||
<span class="tabular-nums text-foreground/90">
|
||||
{{ formatTokenCount(key.total_tokens) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground">费用</span>
|
||||
<span class="tabular-nums text-foreground/90">
|
||||
{{ formatStatUsd(key.total_cost_usd) }}
|
||||
{{ metric.value }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -787,16 +866,48 @@
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto rounded-xl border border-border/50 bg-muted/30 px-3 py-2 text-[11px] text-muted-foreground">
|
||||
<div class="flex min-w-max items-center justify-center whitespace-nowrap text-center">
|
||||
<span class="font-medium text-foreground/90">请求:{{ formatStatInteger(key.request_count) }}</span>
|
||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
||||
<span class="font-medium text-foreground/90">Token:{{ formatTokenCount(key.total_tokens) }}</span>
|
||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
||||
<span class="font-medium text-foreground/90">费用:{{ formatStatUsd(key.total_cost_usd) }}</span>
|
||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
||||
<span class="font-medium text-foreground/90">导入:{{ keyUiStateMap[key.key_id]?.importedAtRelative || '-' }}</span>
|
||||
<span class="mx-1.5 text-muted-foreground/40">|</span>
|
||||
<span class="font-medium text-foreground/90">最后使用:{{ keyUiStateMap[key.key_id]?.lastUsedRelative || '-' }}</span>
|
||||
<div class="space-y-1 text-center">
|
||||
<template v-if="isPoolKeyCycleStatsDisplay(key)">
|
||||
<div
|
||||
v-for="group in getPoolKeyCycleStatsGroups(key)"
|
||||
:key="`${key.key_id}-${group.code}-mobile-stats`"
|
||||
class="flex items-start gap-3 text-left"
|
||||
:data-testid="`pool-mobile-stats-cycle-group-${group.code}`"
|
||||
>
|
||||
<span class="w-10 shrink-0 pt-0.5 text-[10px] font-semibold text-foreground">{{ group.label }}</span>
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<div
|
||||
v-for="metric in group.metrics"
|
||||
:key="`${group.code}-${metric.key}-mobile`"
|
||||
class="flex items-center justify-between gap-2"
|
||||
>
|
||||
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||
<span
|
||||
class="font-medium text-foreground/90 tabular-nums"
|
||||
:class="metric.missing ? 'text-muted-foreground/80' : ''"
|
||||
>{{ metric.value }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="metric in getPoolKeyAccountStatsMetrics(key)"
|
||||
:key="`${key.key_id}-${metric.key}-mobile-account-total`"
|
||||
class="flex items-center justify-between gap-2"
|
||||
>
|
||||
<span class="text-muted-foreground">{{ metric.label }}</span>
|
||||
<span class="font-medium text-foreground/90">{{ metric.value }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<div class="flex items-center justify-between gap-2 border-t border-border/40 pt-1 mt-1">
|
||||
<span class="text-muted-foreground">导入</span>
|
||||
<span class="font-medium text-foreground/90">{{ keyUiStateMap[key.key_id]?.importedAtRelative || '-' }}</span>
|
||||
</div>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground">最后使用</span>
|
||||
<span class="font-medium text-foreground/90">{{ keyUiStateMap[key.key_id]?.lastUsedRelative || '-' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1146,6 +1257,7 @@ import {
|
||||
SortableTableHead,
|
||||
TableFilterMenu,
|
||||
TableCell,
|
||||
Switch,
|
||||
Pagination,
|
||||
Popover,
|
||||
PopoverTrigger,
|
||||
@@ -1209,9 +1321,16 @@ import {
|
||||
resolvePoolManagementPageAfterLoad,
|
||||
type PoolManagementSortBy,
|
||||
type PoolManagementSortOrder,
|
||||
type PoolManagementStatsMode,
|
||||
type PoolManagementViewState,
|
||||
writePoolManagementViewState,
|
||||
} from '@/features/pool/utils/poolManagementState'
|
||||
import {
|
||||
buildPoolStatsDisplay,
|
||||
type PoolCodexCycleStatsGroup,
|
||||
type PoolStatsDisplay,
|
||||
type PoolStatsMetric,
|
||||
} from '@/features/pool/utils/poolStatsDisplay'
|
||||
import { getOAuthOrgBadge } from '@/utils/oauthIdentity'
|
||||
import { getOAuthRefreshFeedback } from '@/utils/oauthRefreshFeedback'
|
||||
import {
|
||||
@@ -1253,6 +1372,7 @@ const restoredViewState = readPoolManagementViewState(
|
||||
pageSize: getQueryValue('pageSize'),
|
||||
sortBy: getQueryValue('sortBy'),
|
||||
sortOrder: getQueryValue('sortOrder'),
|
||||
statsMode: getQueryValue('statsMode'),
|
||||
},
|
||||
poolManagementViewStorage,
|
||||
)
|
||||
@@ -1476,6 +1596,14 @@ const selectedProviderType = computed(() => {
|
||||
return String(fromOverview || '').trim().toLowerCase()
|
||||
})
|
||||
|
||||
const showCodexStatsModeSwitch = computed(() => selectedProviderType.value === 'codex')
|
||||
const codexCurrentCycleStatsEnabled = computed({
|
||||
get: () => poolStatsMode.value === 'current_cycle',
|
||||
set: (enabled: boolean) => {
|
||||
poolStatsMode.value = enabled ? 'current_cycle' : 'account_total'
|
||||
},
|
||||
})
|
||||
|
||||
const selectedProviderStatusText = computed(() => {
|
||||
if (!selectedProviderId.value) return ''
|
||||
const providerActive = selectedProviderData.value?.is_active
|
||||
@@ -1600,6 +1728,7 @@ const currentPage = ref(restoredViewState.page)
|
||||
const pageSize = ref(restoredViewState.pageSize)
|
||||
const sortBy = ref<PoolManagementSortBy | null>(restoredViewState.sortBy)
|
||||
const sortOrder = ref<PoolManagementSortOrder>(restoredViewState.sortOrder)
|
||||
const poolStatsMode = ref<PoolManagementStatsMode>(restoredViewState.statsMode)
|
||||
const hasPoolKeyFilters = computed(() => searchQuery.value.trim().length > 0 || statusFilter.value !== 'all')
|
||||
const MANUAL_QUOTA_REFRESH_COOLDOWN_SECONDS = 5 * 60
|
||||
const refreshingOAuthKeyId = ref<string | null>(null)
|
||||
@@ -1681,6 +1810,18 @@ watch(
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(
|
||||
() => readPoolManagementViewState(
|
||||
{ statsMode: getQueryValue('statsMode') },
|
||||
poolManagementViewStorage,
|
||||
).statsMode,
|
||||
(value) => {
|
||||
if (poolStatsMode.value === value) return
|
||||
poolStatsMode.value = value
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(
|
||||
() => getQueryValue('providerId'),
|
||||
(value) => {
|
||||
@@ -1697,8 +1838,8 @@ watch(
|
||||
)
|
||||
|
||||
watch(
|
||||
[selectedProviderId, searchQuery, statusFilter, currentPage, pageSize, sortBy, sortOrder],
|
||||
([providerId, search, status, page, pageSizeValue, sortByValue, sortOrderValue]) => {
|
||||
[selectedProviderId, searchQuery, statusFilter, currentPage, pageSize, sortBy, sortOrder, poolStatsMode],
|
||||
([providerId, search, status, page, pageSizeValue, sortByValue, sortOrderValue, statsMode]) => {
|
||||
const nextState: PoolManagementViewState = {
|
||||
providerId,
|
||||
search,
|
||||
@@ -1707,6 +1848,7 @@ watch(
|
||||
pageSize: pageSizeValue,
|
||||
sortBy: sortByValue,
|
||||
sortOrder: sortOrderValue,
|
||||
statsMode: statsMode as PoolManagementStatsMode,
|
||||
}
|
||||
patchQuery(buildPoolManagementQueryPatch(nextState))
|
||||
writePoolManagementViewState(nextState, poolManagementViewStorage)
|
||||
@@ -1739,6 +1881,7 @@ type PoolKeyUiState = {
|
||||
quotaTextClass: string
|
||||
importedAtRelative: string
|
||||
lastUsedRelative: string
|
||||
statsDisplay: PoolStatsDisplay
|
||||
mobileTagItems: PoolMobileTagItem[]
|
||||
mobileActionIds: PoolMobileActionId[]
|
||||
}
|
||||
@@ -1778,6 +1921,7 @@ const keyUiStateMap = computed<Record<string, PoolKeyUiState>>(() => {
|
||||
quotaTextClass: quotaFallbackText ? getQuotaTextClass(quotaFallbackText) : '',
|
||||
importedAtRelative: formatPoolKeyImportedAt(key),
|
||||
lastUsedRelative: key.last_used_at ? formatRelativeTime(key.last_used_at) : '-',
|
||||
statsDisplay: buildPoolStatsDisplay(key, selectedProviderType.value, poolStatsMode.value),
|
||||
mobileTagItems: getMobileTagItems(key),
|
||||
mobileActionIds: splitPoolMobileActions({
|
||||
canDownloadOrCopy: true,
|
||||
@@ -1791,6 +1935,27 @@ const keyUiStateMap = computed<Record<string, PoolKeyUiState>>(() => {
|
||||
return map
|
||||
})
|
||||
|
||||
function getPoolKeyStatsDisplay(key: PoolKeyDetail): PoolStatsDisplay {
|
||||
return keyUiStateMap.value[key.key_id]?.statsDisplay
|
||||
?? buildPoolStatsDisplay(key, selectedProviderType.value, poolStatsMode.value)
|
||||
}
|
||||
|
||||
function isPoolKeyCycleStatsDisplay(key: PoolKeyDetail): boolean {
|
||||
return getPoolKeyStatsDisplay(key).kind === 'codex_cycle'
|
||||
}
|
||||
|
||||
function getPoolKeyCycleStatsGroups(key: PoolKeyDetail): PoolCodexCycleStatsGroup[] {
|
||||
const display = getPoolKeyStatsDisplay(key)
|
||||
return display.kind === 'codex_cycle' ? display.groups : []
|
||||
}
|
||||
|
||||
function getPoolKeyAccountStatsMetrics(key: PoolKeyDetail): PoolStatsMetric[] {
|
||||
const display = getPoolKeyStatsDisplay(key)
|
||||
return display.kind === 'account_total'
|
||||
? display.metrics
|
||||
: buildPoolStatsDisplay(key, selectedProviderType.value, 'account_total').metrics
|
||||
}
|
||||
|
||||
const quotaRefreshSupported = computed(() => {
|
||||
return selectedProviderType.value === 'codex'
|
||||
|| selectedProviderType.value === 'kiro'
|
||||
|
||||
@@ -0,0 +1,599 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createApp, nextTick, type App } from 'vue'
|
||||
|
||||
import PoolManagement from '@/views/admin/PoolManagement.vue'
|
||||
import type { PoolKeyDetail, PoolOverviewItem, PoolKeysPageResponse } from '@/api/endpoints/pool'
|
||||
import { POOL_MANAGEMENT_VIEW_STORAGE_KEY } from '@/features/pool/utils/poolManagementState'
|
||||
|
||||
const endpointMocks = vi.hoisted(() => ({
|
||||
getPoolOverview: vi.fn(),
|
||||
getPoolSchedulingPresets: vi.fn(),
|
||||
listPoolKeys: vi.fn(),
|
||||
clearPoolCooldown: vi.fn(),
|
||||
getProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
revealEndpointKey: vi.fn(),
|
||||
exportKey: vi.fn(),
|
||||
deleteEndpointKey: vi.fn(),
|
||||
updateProviderKey: vi.fn(),
|
||||
refreshProviderQuota: vi.fn(),
|
||||
refreshProviderOAuth: vi.fn(),
|
||||
}))
|
||||
|
||||
const routeMocks = vi.hoisted(() => ({
|
||||
query: {} as Record<string, string>,
|
||||
patchQuery: vi.fn((patch: Record<string, string | undefined | null>) => {
|
||||
for (const [key, value] of Object.entries(patch)) {
|
||||
if (value == null || String(value).trim() === '') {
|
||||
delete routeMocks.query[key]
|
||||
} else {
|
||||
routeMocks.query[key] = String(value)
|
||||
}
|
||||
}
|
||||
}),
|
||||
}))
|
||||
|
||||
const proxyStoreMocks = vi.hoisted(() => ({
|
||||
ensureLoaded: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/endpoints/pool', () => ({
|
||||
getPoolOverview: endpointMocks.getPoolOverview,
|
||||
getPoolSchedulingPresets: endpointMocks.getPoolSchedulingPresets,
|
||||
listPoolKeys: endpointMocks.listPoolKeys,
|
||||
clearPoolCooldown: endpointMocks.clearPoolCooldown,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/endpoints/keys', () => ({
|
||||
revealEndpointKey: endpointMocks.revealEndpointKey,
|
||||
exportKey: endpointMocks.exportKey,
|
||||
deleteEndpointKey: endpointMocks.deleteEndpointKey,
|
||||
updateProviderKey: endpointMocks.updateProviderKey,
|
||||
refreshProviderQuota: endpointMocks.refreshProviderQuota,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/endpoints/provider_oauth', () => ({
|
||||
refreshProviderOAuth: endpointMocks.refreshProviderOAuth,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/endpoints', () => ({
|
||||
getProvider: endpointMocks.getProvider,
|
||||
updateProvider: endpointMocks.updateProvider,
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/useRouteQuery', () => ({
|
||||
useRouteQuery: () => ({
|
||||
getQueryValue: (key: string) => routeMocks.query[key],
|
||||
patchQuery: routeMocks.patchQuery,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/proxy-nodes', () => ({
|
||||
useProxyNodesStore: () => ({
|
||||
nodes: [],
|
||||
ensureLoaded: proxyStoreMocks.ensureLoaded,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/useToast', () => ({
|
||||
useToast: () => ({
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/useConfirm', () => ({
|
||||
useConfirm: () => ({
|
||||
confirm: vi.fn().mockResolvedValue(true),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/useClipboard', () => ({
|
||||
useClipboard: () => ({
|
||||
copyToClipboard: vi.fn().mockResolvedValue(undefined),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/useCountdownTimer', async () => {
|
||||
const { ref } = await import('vue')
|
||||
return {
|
||||
useCountdownTimer: () => ({
|
||||
tick: ref(0),
|
||||
start: vi.fn(),
|
||||
}),
|
||||
getCodexResetCountdown: () => ({
|
||||
isExpired: false,
|
||||
text: '1h',
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('lucide-vue-next', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
const Icon = defineComponent({
|
||||
name: 'IconStub',
|
||||
setup() {
|
||||
return () => h('span')
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
Search: Icon,
|
||||
Upload: Icon,
|
||||
ChevronDown: Icon,
|
||||
RefreshCw: Icon,
|
||||
Power: Icon,
|
||||
Database: Icon,
|
||||
KeyRound: Icon,
|
||||
Download: Icon,
|
||||
Copy: Icon,
|
||||
Shield: Icon,
|
||||
Globe: Icon,
|
||||
SquarePen: Icon,
|
||||
Trash2: Icon,
|
||||
Users: Icon,
|
||||
Settings2: Icon,
|
||||
SlidersHorizontal: Icon,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/components/ui', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
const passthrough = (name: string, tag = 'div') => defineComponent({
|
||||
name,
|
||||
inheritAttrs: false,
|
||||
setup(_, { attrs, slots }) {
|
||||
return () => h(tag, attrs, slots.default?.())
|
||||
},
|
||||
})
|
||||
|
||||
const Button = defineComponent({
|
||||
name: 'ButtonStub',
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
disabled: Boolean,
|
||||
},
|
||||
setup(props, { attrs, slots }) {
|
||||
return () => h('button', { ...attrs, disabled: props.disabled, type: attrs.type ?? 'button' }, slots.default?.())
|
||||
},
|
||||
})
|
||||
|
||||
const Input = defineComponent({
|
||||
name: 'InputStub',
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
modelValue: { type: [String, Number], default: '' },
|
||||
},
|
||||
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),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const Switch = defineComponent({
|
||||
name: 'SwitchStub',
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
modelValue: Boolean,
|
||||
},
|
||||
emits: ['update:modelValue'],
|
||||
setup(props, { attrs, emit }) {
|
||||
return () => h('input', {
|
||||
...attrs,
|
||||
type: 'checkbox',
|
||||
role: 'switch',
|
||||
checked: props.modelValue,
|
||||
onChange: (event: Event) => emit('update:modelValue', (event.target as HTMLInputElement).checked),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const Pagination = defineComponent({
|
||||
name: 'PaginationStub',
|
||||
setup() {
|
||||
return () => h('nav')
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
Card: passthrough('CardStub'),
|
||||
Badge: passthrough('BadgeStub', 'span'),
|
||||
Button,
|
||||
Input,
|
||||
Select: passthrough('SelectStub'),
|
||||
SelectTrigger: passthrough('SelectTriggerStub', 'button'),
|
||||
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'),
|
||||
SortableTableHead: passthrough('SortableTableHeadStub', 'th'),
|
||||
TableFilterMenu: passthrough('TableFilterMenuStub'),
|
||||
TableCell: passthrough('TableCellStub', 'td'),
|
||||
Switch,
|
||||
Pagination,
|
||||
Popover: passthrough('PopoverStub'),
|
||||
PopoverTrigger: passthrough('PopoverTriggerStub'),
|
||||
PopoverContent: passthrough('PopoverContentStub'),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/components/ui/refresh-button.vue', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'RefreshButtonStub',
|
||||
setup(_, { attrs }) {
|
||||
return () => h('button', attrs, '刷新')
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/features/pool/components/PoolSchedulingDialog.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'PoolSchedulingDialogStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/pool/components/PoolAdvancedDialog.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'PoolAdvancedDialogStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/pool/components/PoolAccountBatchDialog.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'PoolAccountBatchDialogStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/pool/components/ProviderProxyPopover.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'ProviderProxyPopoverStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/providers/components/KeyAllowedModelsEditDialog.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'KeyAllowedModelsEditDialogStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/providers/components/KeyFormDialog.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'KeyFormDialogStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/providers/components/OAuthKeyEditDialog.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'OAuthKeyEditDialogStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/providers/components/OAuthAccountDialog.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'OAuthAccountDialogStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
vi.mock('@/features/providers/components/ProxyNodeSelect.vue', async () => {
|
||||
const { defineComponent } = await import('vue')
|
||||
return {
|
||||
default: defineComponent({
|
||||
name: 'ProxyNodeSelectStub',
|
||||
setup() {
|
||||
return () => null
|
||||
},
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
|
||||
|
||||
function createOverview(providerType: string): PoolOverviewItem {
|
||||
return {
|
||||
provider_id: `${providerType}-provider`,
|
||||
provider_name: `${providerType} Provider`,
|
||||
provider_type: providerType,
|
||||
total_keys: 1,
|
||||
active_keys: 1,
|
||||
cooldown_count: 0,
|
||||
pool_enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
function createProvider(providerType: string) {
|
||||
return {
|
||||
id: `${providerType}-provider`,
|
||||
name: `${providerType} Provider`,
|
||||
provider_type: providerType,
|
||||
is_active: true,
|
||||
api_formats: ['openai:chat'],
|
||||
proxy: null,
|
||||
pool_advanced: null,
|
||||
claude_code_advanced: null,
|
||||
}
|
||||
}
|
||||
|
||||
function createPoolKey(providerType = 'codex', overrides: Partial<PoolKeyDetail> = {}): PoolKeyDetail {
|
||||
return {
|
||||
key_id: `${providerType}-key-1`,
|
||||
key_name: `${providerType} key`,
|
||||
is_active: true,
|
||||
auth_type: 'api_key',
|
||||
api_formats: ['openai:chat'],
|
||||
internal_priority: 50,
|
||||
account_quota: null,
|
||||
cooldown_reason: null,
|
||||
cooldown_ttl_seconds: null,
|
||||
cost_window_usage: 0,
|
||||
cost_limit: null,
|
||||
request_count: 9876,
|
||||
total_tokens: 4321000,
|
||||
total_cost_usd: '8.7654',
|
||||
sticky_sessions: 0,
|
||||
lru_score: null,
|
||||
created_at: '2026-05-05T00:00:00Z',
|
||||
imported_at: '2026-05-05T00:00:00Z',
|
||||
last_used_at: '2026-05-05T01:00:00Z',
|
||||
status_snapshot: {
|
||||
oauth: { code: 'none' },
|
||||
account: { code: 'ok', blocked: false },
|
||||
quota: {
|
||||
code: 'ok',
|
||||
exhausted: false,
|
||||
provider_type: providerType,
|
||||
windows: providerType === 'codex'
|
||||
? [
|
||||
{
|
||||
code: '5h',
|
||||
remaining_ratio: 0.8,
|
||||
usage: { request_count: 7, total_tokens: 2500, total_cost_usd: '0.0045' },
|
||||
},
|
||||
{
|
||||
code: 'weekly',
|
||||
remaining_ratio: 0.5,
|
||||
usage: { request_count: 0, total_tokens: 0, total_cost_usd: '0.00000000' },
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function createKeyPage(key: PoolKeyDetail): PoolKeysPageResponse {
|
||||
return {
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 50,
|
||||
keys: [key],
|
||||
}
|
||||
}
|
||||
|
||||
function resetQuery() {
|
||||
for (const key of Object.keys(routeMocks.query)) {
|
||||
delete routeMocks.query[key]
|
||||
}
|
||||
}
|
||||
|
||||
function mountPoolManagement() {
|
||||
const root = document.createElement('div')
|
||||
document.body.appendChild(root)
|
||||
const app = createApp(PoolManagement)
|
||||
app.mount(root)
|
||||
mountedApps.push({ app, root })
|
||||
return root
|
||||
}
|
||||
|
||||
async function settle() {
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
await Promise.resolve()
|
||||
await nextTick()
|
||||
}
|
||||
}
|
||||
|
||||
function seedStoredStatsMode(statsMode: 'current_cycle' | 'account_total') {
|
||||
window.sessionStorage.setItem(
|
||||
POOL_MANAGEMENT_VIEW_STORAGE_KEY,
|
||||
JSON.stringify({ statsMode }),
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetQuery()
|
||||
window.sessionStorage.clear()
|
||||
routeMocks.patchQuery.mockClear()
|
||||
proxyStoreMocks.ensureLoaded.mockClear()
|
||||
|
||||
endpointMocks.getPoolOverview.mockReset()
|
||||
endpointMocks.getPoolSchedulingPresets.mockReset()
|
||||
endpointMocks.listPoolKeys.mockReset()
|
||||
endpointMocks.clearPoolCooldown.mockReset()
|
||||
endpointMocks.getProvider.mockReset()
|
||||
endpointMocks.updateProvider.mockReset()
|
||||
endpointMocks.revealEndpointKey.mockReset()
|
||||
endpointMocks.exportKey.mockReset()
|
||||
endpointMocks.deleteEndpointKey.mockReset()
|
||||
endpointMocks.updateProviderKey.mockReset()
|
||||
endpointMocks.refreshProviderQuota.mockReset()
|
||||
endpointMocks.refreshProviderOAuth.mockReset()
|
||||
|
||||
endpointMocks.getPoolSchedulingPresets.mockResolvedValue([])
|
||||
endpointMocks.clearPoolCooldown.mockResolvedValue({ message: 'ok' })
|
||||
endpointMocks.refreshProviderQuota.mockResolvedValue({ success: 0, failed: 0 })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const { app, root } of mountedApps.splice(0)) {
|
||||
app.unmount()
|
||||
root.remove()
|
||||
}
|
||||
})
|
||||
|
||||
describe('PoolManagement Codex cycle stats mode', () => {
|
||||
it('defaults Codex providers to current-cycle groups and toggles back to account totals', async () => {
|
||||
const codexKey = createPoolKey('codex')
|
||||
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||
|
||||
const root = mountPoolManagement()
|
||||
await settle()
|
||||
|
||||
const modeSwitch = root.querySelector<HTMLInputElement>('[data-testid="pool-stats-mode-switch"]')
|
||||
expect(modeSwitch).not.toBeNull()
|
||||
expect(modeSwitch?.checked).toBe(true)
|
||||
expect(root.querySelectorAll('[data-testid="pool-stats-cycle-group-5h"]').length).toBeGreaterThan(0)
|
||||
expect(root.querySelectorAll('[data-testid="pool-stats-cycle-group-weekly"]').length).toBeGreaterThan(0)
|
||||
expect(root.querySelector('[data-testid="pool-stats-5h-request_count"]')?.textContent?.trim()).toBe('7')
|
||||
expect(root.querySelector('[data-testid="pool-stats-weekly-total_tokens"]')?.textContent?.trim()).toBe('0')
|
||||
|
||||
if (!modeSwitch) throw new Error('expected stats switch')
|
||||
modeSwitch.checked = false
|
||||
modeSwitch.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
await settle()
|
||||
|
||||
expect(routeMocks.query.statsMode).toBe('account_total')
|
||||
expect(window.sessionStorage.getItem(POOL_MANAGEMENT_VIEW_STORAGE_KEY)).toContain('"statsMode":"account_total"')
|
||||
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).not.toBeNull()
|
||||
expect(root.textContent).toContain('9,876')
|
||||
expect(root.textContent).toContain('4.3M')
|
||||
expect(root.textContent).toContain('$8.77')
|
||||
})
|
||||
|
||||
it('renders the Codex stats switch in header actions instead of a standalone mode bar', async () => {
|
||||
const codexKey = createPoolKey('codex')
|
||||
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||
|
||||
const root = mountPoolManagement()
|
||||
await settle()
|
||||
|
||||
const desktopHeaderActions = root.querySelector('[data-testid="pool-header-actions"]')
|
||||
const mobileHeaderActions = root.querySelector('[data-testid="pool-mobile-header-actions"]')
|
||||
const modeControls = Array.from(root.querySelectorAll('[data-testid="pool-stats-mode-control"]'))
|
||||
|
||||
expect(desktopHeaderActions?.querySelector('[data-testid="pool-stats-mode-control"]')).not.toBeNull()
|
||||
expect(mobileHeaderActions?.querySelector('[data-testid="pool-stats-mode-control"]')).not.toBeNull()
|
||||
expect(modeControls).toHaveLength(2)
|
||||
expect(modeControls.every(control => control.closest('[data-testid="pool-header-actions"], [data-testid="pool-mobile-header-actions"]'))).toBe(true)
|
||||
expect(desktopHeaderActions?.textContent).toContain('累计')
|
||||
expect(desktopHeaderActions?.textContent).toContain('周期')
|
||||
expect(root.textContent).not.toContain('Codex 统计模式')
|
||||
expect(root.textContent).not.toContain('当前周期显示 5H 与周窗口')
|
||||
})
|
||||
|
||||
it('restores stored Codex account-total mode when the query omits statsMode', async () => {
|
||||
seedStoredStatsMode('account_total')
|
||||
const codexKey = createPoolKey('codex')
|
||||
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||
|
||||
const root = mountPoolManagement()
|
||||
await settle()
|
||||
|
||||
const modeSwitch = root.querySelector<HTMLInputElement>('[data-testid="pool-stats-mode-switch"]')
|
||||
expect(modeSwitch).not.toBeNull()
|
||||
expect(modeSwitch?.checked).toBe(false)
|
||||
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).not.toBeNull()
|
||||
expect(root.querySelector('[data-testid="pool-stats-cycle-group-5h"]')).toBeNull()
|
||||
expect(routeMocks.query.statsMode).toBe('account_total')
|
||||
expect(window.sessionStorage.getItem(POOL_MANAGEMENT_VIEW_STORAGE_KEY)).toContain('"statsMode":"account_total"')
|
||||
})
|
||||
|
||||
it('lets a current-cycle statsMode query override stored Codex account-total mode', async () => {
|
||||
seedStoredStatsMode('account_total')
|
||||
routeMocks.query.statsMode = 'current_cycle'
|
||||
const codexKey = createPoolKey('codex')
|
||||
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('codex')] })
|
||||
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(codexKey))
|
||||
endpointMocks.getProvider.mockResolvedValue(createProvider('codex'))
|
||||
|
||||
const root = mountPoolManagement()
|
||||
await settle()
|
||||
|
||||
const modeSwitch = root.querySelector<HTMLInputElement>('[data-testid="pool-stats-mode-switch"]')
|
||||
expect(modeSwitch).not.toBeNull()
|
||||
expect(modeSwitch?.checked).toBe(true)
|
||||
expect(root.querySelector('[data-testid="pool-stats-cycle-group-5h"]')).not.toBeNull()
|
||||
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).toBeNull()
|
||||
expect(routeMocks.query.statsMode).toBeUndefined()
|
||||
expect(window.sessionStorage.getItem(POOL_MANAGEMENT_VIEW_STORAGE_KEY)).toContain('"statsMode":"current_cycle"')
|
||||
})
|
||||
|
||||
it('hides the stats mode switch for non-Codex providers and keeps account totals', async () => {
|
||||
const openaiKey = createPoolKey('openai', {
|
||||
request_count: 12,
|
||||
total_tokens: 3456,
|
||||
total_cost_usd: '1.25',
|
||||
})
|
||||
endpointMocks.getPoolOverview.mockResolvedValue({ items: [createOverview('openai')] })
|
||||
endpointMocks.listPoolKeys.mockResolvedValue(createKeyPage(openaiKey))
|
||||
endpointMocks.getProvider.mockResolvedValue(createProvider('openai'))
|
||||
|
||||
const root = mountPoolManagement()
|
||||
await settle()
|
||||
|
||||
expect(root.querySelector('[data-testid="pool-stats-mode-switch"]')).toBeNull()
|
||||
expect(root.querySelector('[data-testid="pool-stats-mode-control"]')).toBeNull()
|
||||
expect(root.querySelector('[data-testid="pool-stats-cycle-group-5h"]')).toBeNull()
|
||||
expect(root.querySelector('[data-testid="pool-stats-account-total"]')).not.toBeNull()
|
||||
expect(root.textContent).toContain('12')
|
||||
expect(root.textContent).toContain('3.5K')
|
||||
expect(root.textContent).toContain('$1.25')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user