refactor(workspace): enforce layered crate boundaries

This commit is contained in:
elky
2026-07-15 23:47:19 +08:00
parent a728c090a9
commit 8616fe6ee2
969 changed files with 40187 additions and 27240 deletions
@@ -0,0 +1,85 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { getMock, cachedRequestMock, buildCacheKeyMock } = vi.hoisted(() => ({
getMock: vi.fn(),
cachedRequestMock: vi.fn(async (_key: string, fetcher: () => Promise<unknown>) => fetcher()),
buildCacheKeyMock: vi.fn((prefix: string) => prefix),
}))
vi.mock('@/api/client', () => ({
default: {
get: getMock,
},
}))
vi.mock('@/utils/cache', () => ({
cache: {
clear: vi.fn(),
delete: vi.fn(),
},
cachedRequest: cachedRequestMock,
buildCacheKey: buildCacheKeyMock,
}))
import { adminApi } from '@/api/admin'
describe('adminApi analytics cache options', () => {
const params = {
start_date: '2026-07-01',
end_date: '2026-07-15',
preset: 'custom',
timezone: 'Asia/Shanghai',
tz_offset_minutes: 480,
}
beforeEach(() => {
getMock.mockReset()
getMock.mockResolvedValue({ data: {} })
cachedRequestMock.mockClear()
buildCacheKeyMock.mockClear()
})
it('keeps the existing 20-second cache TTL by default', async () => {
await adminApi.getTimeSeries(params)
await adminApi.getPercentiles(params)
await adminApi.getProviderPerformance(params)
await adminApi.getErrorDistribution(params)
for (let call = 1; call <= 4; call += 1) {
expect(cachedRequestMock).toHaveBeenNthCalledWith(
call,
expect.any(String),
expect.any(Function),
20 * 1000
)
}
})
it('uses a zero TTL when an analytics request skips the cache', async () => {
const options = { skipCache: true }
const providerParams = { ...params, include_timeline: false }
await adminApi.getTimeSeries(params, options)
await adminApi.getPercentiles(params, options)
await adminApi.getProviderPerformance(providerParams, options)
await adminApi.getErrorDistribution(params, options)
for (let call = 1; call <= 4; call += 1) {
expect(cachedRequestMock).toHaveBeenNthCalledWith(
call,
expect.any(String),
expect.any(Function),
0
)
}
expect(getMock).toHaveBeenNthCalledWith(1, '/api/admin/stats/time-series', { params })
expect(getMock).toHaveBeenNthCalledWith(2, '/api/admin/stats/performance/percentiles', {
params,
})
expect(getMock).toHaveBeenNthCalledWith(3, '/api/admin/stats/performance/providers', {
params: providerParams,
})
expect(getMock).toHaveBeenNthCalledWith(4, '/api/admin/stats/errors/distribution', { params })
})
})
+37
View File
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AxiosAdapter, AxiosInstance, InternalAxiosRequestConfig } from 'axios'
import apiClient, { AUTH_STATE_CHANGE_EVENT } from '@/api/client'
import { cache, cachedRequest } from '@/utils/cache'
type TestableApiClient = typeof apiClient & {
client: AxiosInstance
@@ -34,6 +35,42 @@ describe('apiClient auth state change event', () => {
window.removeEventListener(AUTH_STATE_CHANGE_EVENT, handler as EventListener)
})
it('clears cached API data whenever the authentication identity changes', () => {
apiClient.setToken('first-token')
cache.set('dashboard', { owner: 'first-user' }, 30_000)
apiClient.setToken('second-token')
expect(cache.get('dashboard')).toBeNull()
})
it('does not share or restore an in-flight cached response across token changes', async () => {
let resolveFirst!: (value: string) => void
let resolveSecond!: (value: string) => void
const firstResponse = new Promise<string>((resolve) => {
resolveFirst = resolve
})
const secondResponse = new Promise<string>((resolve) => {
resolveSecond = resolve
})
const secondFetcher = vi.fn(() => secondResponse)
apiClient.setToken('first-token')
const firstRequest = cachedRequest('dashboard', () => firstResponse, 30_000)
apiClient.setToken('second-token')
const secondRequest = cachedRequest('dashboard', secondFetcher, 30_000)
expect(secondFetcher).toHaveBeenCalledTimes(1)
resolveFirst('first-user-data')
await expect(firstRequest).resolves.toBe('first-user-data')
expect(cache.get('dashboard')).toBeNull()
resolveSecond('second-user-data')
await expect(secondRequest).resolves.toBe('second-user-data')
expect(cache.get('dashboard')).toBe('second-user-data')
})
it('sends auth refresh without a request body', async () => {
const rawClient = apiClient as TestableApiClient
const previousAdapter = rawClient.client.defaults.adapter
+88 -49
View File
@@ -1,11 +1,19 @@
import apiClient from './client'
import type { ModelTestCapabilities } from './endpoints/types'
import axios, { type AxiosRequestConfig } from 'axios'
import { cachedRequest, buildCacheKey } from '@/utils/cache'
import { cache, cachedRequest, buildCacheKey } from '@/utils/cache'
import type { BillingSummary } from './auth'
import type { ApiKeyInstallSession, InstallSessionTargetSystem, InstallTargetCli } from './me'
const SYSTEM_DATA_IMPORT_TIMEOUT_MS = 10 * 60 * 1000
const ALL_SYSTEM_CONFIGS_CACHE_KEY = 'admin:system:configs'
export interface AdminSystemConfigItem {
key: string
value: unknown
description?: string
is_set?: boolean
}
export interface SystemDataImportOptions {
onUploadProgress?: AxiosRequestConfig['onUploadProgress']
@@ -736,6 +744,10 @@ export interface QuotaUsageResponse {
providers: QuotaUsageProvider[]
}
export interface AdminAnalyticsRequestOptions {
skipCache?: boolean
}
export interface PercentileItem {
date: string
p50_response_time_ms?: number | null
@@ -947,9 +959,17 @@ export const adminApi = {
// 系统配置相关
// 获取所有系统配置
async getAllSystemConfigs(): Promise<Array<{ key: string; value: unknown; description?: string }>> {
const response = await apiClient.get<Array<{ key: string; value: unknown; description?: string }>>('/api/admin/system/configs')
return response.data
async getAllSystemConfigs(
options: { cacheTtlMs?: number } = {},
): Promise<AdminSystemConfigItem[]> {
return cachedRequest(
ALL_SYSTEM_CONFIGS_CACHE_KEY,
async () => {
const response = await apiClient.get<AdminSystemConfigItem[]>('/api/admin/system/configs')
return response.data
},
options.cacheTtlMs ?? 0,
)
},
// 获取特定系统配置
@@ -983,6 +1003,8 @@ export const adminApi = {
{ value, description },
requestConfig,
)
cache.delete(ALL_SYSTEM_CONFIGS_CACHE_KEY)
cache.delete(buildCacheKey('admin:system:config', { key }))
return response.data
},
@@ -991,6 +1013,8 @@ export const adminApi = {
const response = await apiClient.delete<{ message: string }>(
`/api/admin/system/configs/${key}`
)
cache.delete(ALL_SYSTEM_CONFIGS_CACHE_KEY)
cache.delete(buildCacheKey('admin:system:config', { key }))
return response.data
},
@@ -1021,6 +1045,7 @@ export const adminApi = {
data,
{ timeout: SYSTEM_DATA_IMPORT_TIMEOUT_MS, ...options }
)
cache.clear()
return response.data
},
@@ -1053,6 +1078,7 @@ export const adminApi = {
data,
{ timeout: SYSTEM_DATA_IMPORT_TIMEOUT_MS, ...options }
)
cache.clear()
return response.data
},
@@ -1380,13 +1406,16 @@ export const adminApi = {
)
},
async getPercentiles(params?: {
start_date?: string
end_date?: string
preset?: string
timezone?: string
tz_offset_minutes?: number
}): Promise<PercentileItem[]> {
async getPercentiles(
params?: {
start_date?: string
end_date?: string
preset?: string
timezone?: string
tz_offset_minutes?: number
},
options?: AdminAnalyticsRequestOptions
): Promise<PercentileItem[]> {
const cacheKey = buildCacheKey('admin:stats:performance:percentiles', params)
return cachedRequest(
cacheKey,
@@ -1396,26 +1425,30 @@ export const adminApi = {
})
return response.data
},
20 * 1000
options?.skipCache ? 0 : 20 * 1000
)
},
async getProviderPerformance(params?: {
start_date?: string
end_date?: string
preset?: string
timezone?: string
tz_offset_minutes?: number
granularity?: 'day' | 'hour'
limit?: number
provider_id?: string
model?: string
api_format?: string
endpoint_kind?: string
is_stream?: boolean
has_format_conversion?: boolean
slow_threshold_ms?: number
}): Promise<ProviderPerformanceResponse> {
async getProviderPerformance(
params?: {
start_date?: string
end_date?: string
preset?: string
timezone?: string
tz_offset_minutes?: number
granularity?: 'day' | 'hour'
include_timeline?: boolean
limit?: number
provider_id?: string
model?: string
api_format?: string
endpoint_kind?: string
is_stream?: boolean
has_format_conversion?: boolean
slow_threshold_ms?: number
},
options?: AdminAnalyticsRequestOptions
): Promise<ProviderPerformanceResponse> {
const cacheKey = buildCacheKey('admin:stats:performance:providers', params)
return cachedRequest(
cacheKey,
@@ -1425,17 +1458,20 @@ export const adminApi = {
})
return response.data
},
20 * 1000
options?.skipCache ? 0 : 20 * 1000
)
},
async getErrorDistribution(params?: {
start_date?: string
end_date?: string
preset?: string
timezone?: string
tz_offset_minutes?: number
}): Promise<ErrorDistributionResponse> {
async getErrorDistribution(
params?: {
start_date?: string
end_date?: string
preset?: string
timezone?: string
tz_offset_minutes?: number
},
options?: AdminAnalyticsRequestOptions
): Promise<ErrorDistributionResponse> {
const cacheKey = buildCacheKey('admin:stats:errors:distribution', params)
return cachedRequest(
cacheKey,
@@ -1445,7 +1481,7 @@ export const adminApi = {
})
return response.data
},
20 * 1000
options?.skipCache ? 0 : 20 * 1000
)
},
@@ -1535,17 +1571,20 @@ export const adminApi = {
return response.data
},
async getTimeSeries(params?: {
start_date?: string
end_date?: string
preset?: string
granularity?: 'hour' | 'day' | 'week' | 'month'
timezone?: string
tz_offset_minutes?: number
user_id?: string
model?: string
provider_name?: string
}): Promise<Array<Record<string, unknown>>> {
async getTimeSeries(
params?: {
start_date?: string
end_date?: string
preset?: string
granularity?: 'hour' | 'day' | 'week' | 'month'
timezone?: string
tz_offset_minutes?: number
user_id?: string
model?: string
provider_name?: string
},
options?: AdminAnalyticsRequestOptions
): Promise<Array<Record<string, unknown>>> {
const cacheKey = buildCacheKey('admin:stats:time-series', params)
return cachedRequest(
cacheKey,
@@ -1553,7 +1592,7 @@ export const adminApi = {
const response = await apiClient.get<Array<Record<string, unknown>>>('/api/admin/stats/time-series', { params })
return response.data
},
20 * 1000
options?.skipCache ? 0 : 20 * 1000
)
},
+30 -10
View File
@@ -2,15 +2,30 @@ import axios, { getAdapter } from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig, AxiosAdapter } from 'axios'
import { NETWORK_CONFIG, AUTH_CONFIG } from '@/config/constants'
import { isDemoMode } from '@/config/demo'
import { handleMockRequest, setMockUserToken } from '@/mocks'
import { getClientDeviceId } from '@/utils/deviceId'
import { CrossTabRefreshCoordinator } from '@/utils/crossTabRefresh'
import { log } from '@/utils/logger'
import { cache } from '@/utils/cache'
// 在开发环境下使用代理,生产环境使用环境变量
const API_BASE_URL = import.meta.env.VITE_API_URL || ''
export const AUTH_STATE_CHANGE_EVENT = 'aether-auth-state-change'
type MockRuntime = typeof import('@/mocks')
let mockRuntimePromise: Promise<MockRuntime> | null = null
let currentMockUserToken: string | null = null
function loadMockRuntime(): Promise<MockRuntime> {
if (!mockRuntimePromise) {
mockRuntimePromise = import('@/mocks').catch((error) => {
mockRuntimePromise = null
throw error
})
}
return mockRuntimePromise
}
/**
* 判断请求是否为公共端点
*/
@@ -53,7 +68,9 @@ function createDemoAdapter(defaultAdapter: AxiosAdapter) {
return async (config: InternalAxiosRequestConfig): Promise<AxiosResponse> => {
if (isDemoMode()) {
try {
const mockResponse = await handleMockRequest({
const mockRuntime = await loadMockRuntime()
mockRuntime.setMockUserToken(currentMockUserToken)
const mockResponse = await mockRuntime.handleMockRequest({
method: config.method?.toUpperCase(),
url: config.url,
data: config.data,
@@ -290,30 +307,33 @@ class ApiClient {
}
private syncTokenState(token: string | null): void {
this.token = token
if (isDemoMode()) {
setMockUserToken(token)
if (this.token !== token) {
cache.clear()
}
this.token = token
currentMockUserToken = token
}
setToken(token: string): void {
if (this.token === token) {
cache.clear()
}
this.syncTokenState(token)
localStorage.setItem('access_token', token)
}
getToken(): string | null {
if (!this.token) {
this.token = localStorage.getItem('access_token')
// 页面刷新时,从 localStorage 恢复 token 到 mock handler
if (this.token && isDemoMode()) {
setMockUserToken(this.token)
}
this.syncTokenState(localStorage.getItem('access_token'))
}
return this.token
}
clearAuth(): void {
const hadAuth = this.token !== null || localStorage.getItem('access_token') !== null
if (hadAuth && this.token === null) {
cache.clear()
}
this.syncTokenState(null)
localStorage.removeItem('access_token')
// 同标签页内清理认证状态时不会触发 storage 事件,这里主动广播一次。
+2 -2
View File
@@ -413,7 +413,7 @@ export const dashboardApi = {
const response = await apiClient.get<DashboardStatsResponse>('/api/dashboard/stats', { params })
return response.data
},
10 * 1000
30 * 1000
)
},
@@ -476,7 +476,7 @@ export const dashboardApi = {
})
return response.data
},
20 * 1000
60 * 1000
)
},
+28 -15
View File
@@ -1,6 +1,8 @@
import apiClient from './client'
import { buildCacheKey, cache, cachedRequest } from '@/utils/cache'
const MODULE_MANAGEMENT_ORDER_CONFIG_KEY = 'module_management.extension_order'
const ALL_SYSTEM_CONFIGS_CACHE_KEY = 'admin:system:configs'
export interface ModuleStatus {
name: string
@@ -160,19 +162,30 @@ function normalizePlaceholderPrefix(value: unknown): string {
: CHAT_PII_REDACTION_DEFAULT_CONFIG.placeholder_prefix
}
async function getSystemConfigValue(key: string): Promise<unknown> {
const response = await apiClient.get<{ key: string; value: unknown }>(`/api/admin/system/configs/${key}`)
return response.data.value
}
async function updateSystemConfigValue(key: string, value: unknown, description: string) {
const response = await apiClient.put<{ key: string; value: unknown; description?: string }>(
`/api/admin/system/configs/${key}`,
{ value, description },
)
cache.delete(ALL_SYSTEM_CONFIGS_CACHE_KEY)
cache.delete(buildCacheKey('admin:system:config', { key }))
return response.data.value
}
async function getAllSystemConfigValues(): Promise<Map<string, unknown>> {
const configs = await cachedRequest(
ALL_SYSTEM_CONFIGS_CACHE_KEY,
async () => {
const response = await apiClient.get<Array<{ key: string; value: unknown }>>(
'/api/admin/system/configs'
)
return response.data
},
30_000,
)
return new Map(configs.map(config => [config.key, config.value]))
}
export const modulesApi = {
/**
* 获取所有模块状态(管理员)
@@ -202,6 +215,7 @@ export const modulesApi = {
`/api/admin/modules/status/${moduleName}/enabled`,
{ enabled }
)
cache.delete(ALL_SYSTEM_CONFIGS_CACHE_KEY)
return response.data
},
@@ -227,22 +241,21 @@ export const modulesApi = {
description: '模块管理扩展模块展示顺序',
},
)
cache.delete(ALL_SYSTEM_CONFIGS_CACHE_KEY)
cache.delete(buildCacheKey('admin:system:config', {
key: MODULE_MANAGEMENT_ORDER_CONFIG_KEY,
}))
return normalizeModuleManagementOrder(response.data.value)
},
async getChatPiiRedactionConfig(): Promise<ChatPiiRedactionConfig> {
const [enabled, rules, cacheTtlSeconds, placeholderPrefix] = await Promise.all([
getSystemConfigValue(CHAT_PII_REDACTION_CONFIG_KEYS.enabled),
getSystemConfigValue(CHAT_PII_REDACTION_CONFIG_KEYS.rules),
getSystemConfigValue(CHAT_PII_REDACTION_CONFIG_KEYS.cache_ttl_seconds),
getSystemConfigValue(CHAT_PII_REDACTION_CONFIG_KEYS.placeholder_prefix),
])
const configsByKey = await getAllSystemConfigValues()
return normalizeChatPiiRedactionConfig({
enabled,
rules,
cache_ttl_seconds: cacheTtlSeconds,
placeholder_prefix: placeholderPrefix,
enabled: configsByKey.get(CHAT_PII_REDACTION_CONFIG_KEYS.enabled),
rules: configsByKey.get(CHAT_PII_REDACTION_CONFIG_KEYS.rules),
cache_ttl_seconds: configsByKey.get(CHAT_PII_REDACTION_CONFIG_KEYS.cache_ttl_seconds),
placeholder_prefix: configsByKey.get(CHAT_PII_REDACTION_CONFIG_KEYS.placeholder_prefix),
})
},
+2
View File
@@ -44,6 +44,8 @@ export interface UsageStats {
total_cost: number
total_actual_cost?: number
avg_response_time: number
error_count?: number
error_rate?: number
today?: {
requests: number
tokens: number
+35 -2
View File
@@ -29,7 +29,10 @@
? 'bg-primary/10 text-primary font-medium'
: 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
]"
@pointerdown="emit('prefetch', item.href)"
@pointerenter="schedulePrefetch(item.href)"
@pointerleave="cancelScheduledPrefetch(item.href)"
@pointerdown="prefetchNow(item.href)"
@focus="prefetchNow(item.href)"
@click="handleNavigate(item.href)"
>
<div class="flex items-center gap-2.5">
@@ -55,7 +58,7 @@
</template>
<script setup lang="ts">
import type { Component } from 'vue'
import { onBeforeUnmount, type Component } from 'vue'
export interface NavigationItem {
name: string
@@ -80,6 +83,36 @@ const emit = defineEmits<{
(e: 'prefetch', href: string): void
}>()
const HOVER_PREFETCH_DELAY_MS = 100
let scheduledPrefetchHref: string | null = null
let scheduledPrefetchTimer: ReturnType<typeof setTimeout> | null = null
function cancelScheduledPrefetch(href?: string) {
if (href && scheduledPrefetchHref !== href) return
if (scheduledPrefetchTimer) {
clearTimeout(scheduledPrefetchTimer)
scheduledPrefetchTimer = null
}
scheduledPrefetchHref = null
}
function schedulePrefetch(href: string) {
cancelScheduledPrefetch()
scheduledPrefetchHref = href
scheduledPrefetchTimer = setTimeout(() => {
scheduledPrefetchTimer = null
scheduledPrefetchHref = null
emit('prefetch', href)
}, HOVER_PREFETCH_DELAY_MS)
}
function prefetchNow(href: string) {
cancelScheduledPrefetch()
emit('prefetch', href)
}
onBeforeUnmount(() => cancelScheduledPrefetch())
function isItemActive(href: string) {
if (props.isActive) {
return props.isActive(href)
@@ -601,6 +601,7 @@ import {
EMBEDDING_API_FORMATS,
buildGlobalModelCreatePayload,
buildGlobalModelUpdatePayload,
cloneTieredPricingConfig,
} from './global-model-form-helpers'
import { tieredPricingHasImageOutputPricing } from '../utils/tiered-pricing'
@@ -1106,7 +1107,7 @@ function selectModel(model: ModelsDevModelItem) {
loadVideoPricingFromConfig()
tieredPricing.value = model.tieredPricing
? structuredClone(model.tieredPricing)
? cloneTieredPricingConfig(model.tieredPricing)
: null
presetPanelCollapsed.value = true
@@ -1,10 +1,13 @@
import { describe, expect, it } from 'vitest'
import { reactive } from 'vue'
import {
EMBEDDING_API_FORMATS,
buildGlobalModelCreatePayload,
buildGlobalModelUpdatePayload,
cloneTieredPricingConfig,
} from '../global-model-form-helpers'
import type { TieredPricingConfig } from '@/api/endpoints/types'
const embeddingPricing = {
tiers: [{ up_to: null, input_price_per_1m: 0.02, output_price_per_1m: 0 }],
@@ -66,3 +69,24 @@ describe('global model form embedding payload helpers', () => {
})
})
})
describe('global model form pricing presets', () => {
it('clones reactive pricing before opening the preset editor', () => {
const pricing = reactive({
tiers: [{
up_to: null,
input_price_per_1m: 3,
output_price_per_1m: 15,
}],
}) as TieredPricingConfig
const cloned = cloneTieredPricingConfig(pricing)
expect(cloned).toEqual(pricing)
expect(cloned).not.toBe(pricing)
expect(cloned.tiers[0]).not.toBe(pricing.tiers[0])
cloned.tiers[0].input_price_per_1m = 9
expect(pricing.tiers[0].input_price_per_1m).toBe(3)
})
})
@@ -23,6 +23,14 @@ export interface GlobalModelFormPayloadState {
is_active?: boolean
}
export function cloneTieredPricingConfig(
pricing: TieredPricingConfig,
): TieredPricingConfig {
// Presets live inside a Vue ref and can therefore be reactive proxies, which
// structuredClone cannot clone directly. Pricing configs are JSON payloads.
return JSON.parse(JSON.stringify(pricing)) as TieredPricingConfig
}
function cleanGlobalModelConfig(form: GlobalModelFormPayloadState): Record<string, unknown> | undefined {
return form.config && Object.keys(form.config).length > 0 ? form.config : undefined
}
@@ -1051,7 +1051,7 @@ import { useI18n } from '@/i18n'
import AlertDialog from '@/components/common/AlertDialog.vue'
import EndpointConditionEditor from './EndpointConditionEditor.vue'
import ProxyNodeSelect from './ProxyNodeSelect.vue'
import { getDefaultEndpointBaseUrl, getDefaultEndpointPath, normalizeEndpointApiFormat } from './endpoint-default-paths'
import { getDefaultEndpointBaseUrl, getDefaultEndpointPath } from './endpoint-default-paths'
import { fixedEndpointUpstreamStreamPolicy } from './endpoint-protocol-policy'
import { useProxyNodesStore } from '@/stores/proxy-nodes'
import {
+4 -2
View File
@@ -191,7 +191,9 @@
:class="isNavActive(item.href)
? 'bg-[#cc785c]/10 dark:bg-[#cc785c]/20 text-[#cc785c] dark:text-[#d4a27f]'
: 'text-[#666663] dark:text-muted-foreground hover:bg-black/5 dark:hover:bg-white/5 hover:text-[#191919] dark:hover:text-white'"
@pointerenter="prefetchNavigationItem(item.href)"
@pointerdown="prefetchNavigationItem(item.href)"
@focus="prefetchNavigationItem(item.href)"
@click="mobileMenuOpen = false"
>
<component
@@ -420,7 +422,7 @@ import {
} from 'lucide-vue-next'
import GithubIcon from '@/components/icons/GithubIcon.vue'
import { prefetchAdminNavigationTarget } from '@/utils/adminNavigationPrefetch'
import { prefetchNavigationTarget } from '@/utils/adminNavigationPrefetch'
import { sanitizeMarkdown } from '@/utils/sanitize'
import { useI18n, type MessageKey } from '@/i18n'
import { buildBreadcrumbs, buildNavigation } from './main-layout/navigation'
@@ -1113,7 +1115,7 @@ function isNavActive(href: string) {
}
function prefetchNavigationItem(href: string) {
prefetchAdminNavigationTarget(href)
prefetchNavigationTarget(router, href)
}
const navigation = computed(() => {
@@ -0,0 +1,26 @@
import { describe, expect, it, vi } from 'vitest'
const { importWithRetryMock } = vi.hoisted(() => ({
importWithRetryMock: vi.fn(async (loader: () => Promise<unknown>) => loader()),
}))
vi.mock('@/utils/importRetry', () => ({
importWithRetry: importWithRetryMock,
}))
import { view } from '../helpers'
describe('route view loader', () => {
it('exposes a side-effect-free raw loader for navigation prefetch', async () => {
const component = { name: 'LazyPage' }
const rawLoader = vi.fn(async () => component)
const routeLoader = view(rawLoader)
await expect(routeLoader.prefetch()).resolves.toBe(component)
expect(rawLoader).toHaveBeenCalledTimes(1)
expect(importWithRetryMock).not.toHaveBeenCalled()
await expect(routeLoader()).resolves.toBe(component)
expect(importWithRetryMock).toHaveBeenCalledTimes(1)
})
})
+10 -1
View File
@@ -1,3 +1,12 @@
import { importWithRetry } from '@/utils/importRetry'
export const view = <T>(loader: () => Promise<T>) => () => importWithRetry(loader)
type PrefetchableRouteLoader<T> = (() => Promise<T>) & {
prefetch: () => Promise<T>
}
export const view = <T>(loader: () => Promise<T>): PrefetchableRouteLoader<T> => {
const routeLoader = (() => importWithRetry(loader)) as PrefetchableRouteLoader<T>
// 预取只做一次原始 import;失败时不得触发导航加载器的清缓存和强刷恢复逻辑。
routeLoader.prefetch = loader
return routeLoader
}
+113
View File
@@ -106,6 +106,119 @@ describe('auth store logout', () => {
expect(store.token).toBeNull()
})
it('deduplicates concurrent current-user requests', async () => {
let resolveCurrentUser: ((user: {
id: string
username: string
role: string
is_active: boolean
created_at: string
}) => void) | null = null
getTokenMock.mockReturnValue('access-token')
getCurrentUserMock.mockImplementation(
() => new Promise((resolve) => {
resolveCurrentUser = resolve
})
)
const store = useAuthStore()
const firstRequest = store.fetchCurrentUser()
const secondRequest = store.fetchCurrentUser()
expect(getCurrentUserMock).toHaveBeenCalledTimes(1)
const currentUser = {
id: 'user-1',
username: 'tester',
role: 'user',
is_active: true,
created_at: '2026-03-16T00:00:00Z',
}
resolveCurrentUser?.(currentUser)
await expect(firstRequest).resolves.toEqual(currentUser)
await expect(secondRequest).resolves.toEqual(currentUser)
})
it('does not repeat a failed current-user request on every navigation', async () => {
getTokenMock.mockReturnValue('access-token')
getCurrentUserMock.mockRejectedValue(new Error('network unavailable'))
const store = useAuthStore()
await store.fetchCurrentUser()
await store.fetchCurrentUser()
expect(store.token).toBe('access-token')
expect(store.user).toBeNull()
expect(getCurrentUserMock).toHaveBeenCalledTimes(1)
})
it('does not restore a stale user after logout while the request is in flight', async () => {
let resolveCurrentUser: ((user: {
id: string
username: string
role: string
is_active: boolean
created_at: string
}) => void) | null = null
getTokenMock.mockReturnValue('access-token')
getCurrentUserMock.mockImplementation(
() => new Promise((resolve) => {
resolveCurrentUser = resolve
})
)
const store = useAuthStore()
const currentUserRequest = store.fetchCurrentUser()
await store.logout()
resolveCurrentUser?.({
id: 'stale-user',
username: 'stale',
role: 'user',
is_active: true,
created_at: '2026-03-16T00:00:00Z',
})
await expect(currentUserRequest).resolves.toBeNull()
expect(store.user).toBeNull()
expect(store.token).toBeNull()
})
it('does not restore a stale token when an in-flight request fails after logout', async () => {
let rejectCurrentUser: ((error: Error) => void) | null = null
getTokenMock.mockReturnValue('access-token')
getCurrentUserMock.mockImplementation(
() => new Promise((_resolve, reject) => {
rejectCurrentUser = reject
})
)
const store = useAuthStore()
const currentUserRequest = store.fetchCurrentUser()
await store.logout()
rejectCurrentUser?.(new Error('stale request failed'))
await expect(currentUserRequest).resolves.toBeNull()
expect(store.user).toBeNull()
expect(store.token).toBeNull()
})
it('skips the delayed auth check when the router already loaded the user', async () => {
getTokenMock.mockReturnValue('access-token')
const store = useAuthStore()
store.user = {
id: 'user-1',
username: 'tester',
role: 'user',
is_active: true,
created_at: '2026-03-16T00:00:00Z',
}
await store.checkAuth()
expect(getCurrentUserMock).not.toHaveBeenCalled()
})
it('separates admin access from admin operations for audit administrators', () => {
const store = useAuthStore()
+84 -20
View File
@@ -7,6 +7,8 @@ import { parseApiError } from '@/utils/errorParser'
import { getErrorStatus } from '@/types/api-error'
export const useAuthStore = defineStore('auth', () => {
const CURRENT_USER_FAILURE_BACKOFF_MS = 15_000
// 初始化时从 localStorage 恢复 token
const storedToken = apiClient.getToken()
@@ -14,6 +16,21 @@ export const useAuthStore = defineStore('auth', () => {
const token = ref<string | null>(storedToken)
const loading = ref(false)
const error = ref<string | null>(null)
let fetchCurrentUserPromise: Promise<User | null> | null = null
let fetchCurrentUserToken: string | null = null
let lastCurrentUserFailureAt = 0
let lastCurrentUserFailureToken: string | null = null
let authStateVersion = 0
function resetCurrentUserFailure() {
lastCurrentUserFailureAt = 0
lastCurrentUserFailureToken = null
}
function markAuthStateChanged() {
authStateVersion += 1
resetCurrentUserFailure()
}
const isAuthenticated = computed(() => {
// 使用 store 中的 token 状态判断认证状态
@@ -29,6 +46,7 @@ export const useAuthStore = defineStore('auth', () => {
const currentToken = apiClient.getToken()
if (token.value !== currentToken) {
token.value = currentToken
markAuthStateChanged()
}
}
const isAdmin = computed(() => user.value?.role === 'admin')
@@ -43,10 +61,12 @@ export const useAuthStore = defineStore('auth', () => {
try {
const response = await authApi.login({ email, password, auth_type: authType })
token.value = response.access_token
markAuthStateChanged()
// 获取用户信息
const userInfo = await authApi.getCurrentUser()
user.value = userInfo
resetCurrentUserFailure()
return true
} catch (err: unknown) {
@@ -73,6 +93,7 @@ export const useAuthStore = defineStore('auth', () => {
async function logout() {
user.value = null
token.value = null
markAuthStateChanged()
await authApi.logout()
}
@@ -80,32 +101,75 @@ export const useAuthStore = defineStore('auth', () => {
user.value = null
token.value = null
error.value = null
markAuthStateChanged()
}
async function fetchCurrentUser() {
try {
const userInfo = await authApi.getCurrentUser()
user.value = userInfo
return userInfo
} catch (err: unknown) {
log.error('Failed to fetch user info', err)
syncToken()
if (!token.value) {
user.value = null
}
// 根据用户要求,不管什么错误都不清除状态
// 保持登录状态,除非用户手动退出
log.info('Keeping session despite error, as per user requirement')
return null
function fetchCurrentUser(): Promise<User | null> {
const requestToken = token.value || apiClient.getToken()
if (!requestToken) {
user.value = null
return Promise.resolve(null)
}
// 路由守卫、App 初始化和认证同步可能同时触发,复用同一个请求。
if (fetchCurrentUserPromise && fetchCurrentUserToken === requestToken) {
return fetchCurrentUserPromise
}
// 后端暂时不可用时,不要让每一次导航都重新等待全局请求超时。
if (
lastCurrentUserFailureToken === requestToken &&
Date.now() - lastCurrentUserFailureAt < CURRENT_USER_FAILURE_BACKOFF_MS
) {
return Promise.resolve(null)
}
fetchCurrentUserToken = requestToken
const requestAuthStateVersion = authStateVersion
const request = (async () => {
try {
const userInfo = await authApi.getCurrentUser()
if (requestAuthStateVersion !== authStateVersion || !token.value) {
return null
}
user.value = userInfo
resetCurrentUserFailure()
return userInfo
} catch (err: unknown) {
log.error('Failed to fetch user info', err)
if (requestAuthStateVersion !== authStateVersion) {
return null
}
syncToken()
if (requestAuthStateVersion !== authStateVersion) {
if (!token.value) user.value = null
return null
}
if (!token.value) {
user.value = null
} else {
lastCurrentUserFailureAt = Date.now()
lastCurrentUserFailureToken = token.value
}
// 保留登录状态;短暂退避后允许再次校验。
log.info('Keeping session despite error, as per user requirement')
return null
} finally {
if (fetchCurrentUserPromise === request) {
fetchCurrentUserPromise = null
fetchCurrentUserToken = null
}
}
})()
fetchCurrentUserPromise = request
return request
}
async function checkAuth() {
const storedToken = apiClient.getToken()
if (storedToken) {
token.value = storedToken
// 即使获取用户信息失败,也保留 token
// 只有 401 错误才表示 token 真正失效
syncToken()
if (token.value && !user.value) {
// 即使获取用户信息失败,也保留 token。
await fetchCurrentUser()
}
}
@@ -0,0 +1,22 @@
import { describe, expect, it, vi } from 'vitest'
import { createMemoryHistory, createRouter } from 'vue-router'
import { view } from '@/router/routes/helpers'
import { prefetchNavigationTarget } from '@/utils/adminNavigationPrefetch'
describe('navigation prefetch', () => {
it('warms the async component resolved from the target route', async () => {
const component = { render: () => null }
const rawLoader = vi.fn(async () => component)
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/settings', component: view(rawLoader) }],
})
prefetchNavigationTarget(router, '/settings')
await vi.waitFor(() => {
expect(rawLoader).toHaveBeenCalledTimes(1)
})
})
})
@@ -0,0 +1,52 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { cache, cachedRequest } from '@/utils/cache'
function deferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((resolvePromise) => {
resolve = resolvePromise
})
return { promise, resolve }
}
describe('request cache invalidation', () => {
beforeEach(() => {
cache.clear()
})
it('does not let an invalidated request overwrite a newer in-flight request', async () => {
const oldResponse = deferred<string>()
const newResponse = deferred<string>()
const staleFetcher = vi.fn(() => oldResponse.promise)
const freshFetcher = vi.fn(() => newResponse.promise)
const unexpectedFetcher = vi.fn(async () => 'unexpected')
const staleRequest = cachedRequest('config', staleFetcher, 30_000)
cache.delete('config')
const freshRequest = cachedRequest('config', freshFetcher, 30_000)
oldResponse.resolve('stale')
await expect(staleRequest).resolves.toBe('stale')
expect(cache.get('config')).toBeNull()
const deduplicatedRequest = cachedRequest('config', unexpectedFetcher, 30_000)
expect(unexpectedFetcher).not.toHaveBeenCalled()
newResponse.resolve('fresh')
await expect(freshRequest).resolves.toBe('fresh')
await expect(deduplicatedRequest).resolves.toBe('fresh')
expect(cache.get('config')).toBe('fresh')
})
it('does not refill the cache from a request started before a global clear', async () => {
const response = deferred<string>()
const request = cachedRequest('dashboard', () => response.promise, 30_000)
cache.clear()
response.resolve('previous-user-data')
await expect(request).resolves.toBe('previous-user-data')
expect(cache.get('dashboard')).toBeNull()
})
})
@@ -0,0 +1,99 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { observeNearViewportOnce } from '@/utils/nearViewport'
interface MockObserverInstance {
callback: IntersectionObserverCallback
options?: IntersectionObserverInit
observed: Element[]
disconnect: ReturnType<typeof vi.fn>
}
const instances: MockObserverInstance[] = []
class MockIntersectionObserver {
readonly root = null
readonly rootMargin = ''
readonly thresholds = [0]
readonly callback: IntersectionObserverCallback
readonly options?: IntersectionObserverInit
readonly observed: Element[] = []
readonly disconnect = vi.fn()
constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {
this.callback = callback
this.options = options
instances.push(this)
}
observe(target: Element) {
this.observed.push(target)
}
unobserve() {}
takeRecords(): IntersectionObserverEntry[] { return [] }
}
afterEach(() => {
instances.length = 0
vi.unstubAllGlobals()
})
describe('observeNearViewportOnce', () => {
it('uses the provided scroll root and loads once on intersection', () => {
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver)
const target = document.createElement('section')
const root = document.createElement('main')
const onNearViewport = vi.fn()
observeNearViewportOnce({
target,
root,
rootMargin: '600px 0px',
onNearViewport,
})
const observer = instances[0]
expect(observer?.observed).toEqual([target])
expect(observer?.options).toMatchObject({ root, rootMargin: '600px 0px', threshold: 0 })
expect(onNearViewport).not.toHaveBeenCalled()
observer?.callback([
{ isIntersecting: true, target } as IntersectionObserverEntry,
], observer as unknown as IntersectionObserver)
observer?.callback([
{ isIntersecting: true, target } as IntersectionObserverEntry,
], observer as unknown as IntersectionObserver)
expect(onNearViewport).toHaveBeenCalledTimes(1)
expect(observer?.disconnect).toHaveBeenCalledTimes(1)
})
it('disconnects without loading when disposed before intersection', () => {
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver)
const target = document.createElement('section')
const onNearViewport = vi.fn()
const stop = observeNearViewportOnce({ target, onNearViewport })
const observer = instances[0]
stop()
observer?.callback([
{ isIntersecting: true, target } as IntersectionObserverEntry,
], observer as unknown as IntersectionObserver)
expect(observer?.disconnect).toHaveBeenCalledTimes(1)
expect(onNearViewport).not.toHaveBeenCalled()
})
it('falls back to immediate loading when IntersectionObserver is unavailable', () => {
vi.stubGlobal('IntersectionObserver', undefined)
const onNearViewport = vi.fn()
const stop = observeNearViewportOnce({
target: document.createElement('section'),
onNearViewport,
})
expect(onNearViewport).toHaveBeenCalledTimes(1)
expect(() => stop()).not.toThrow()
})
})
+27 -29
View File
@@ -1,45 +1,43 @@
import { log } from '@/utils/logger'
import type { Router } from 'vue-router'
const PREFETCH_COOLDOWN_MS = 5 * 1000
const lastPrefetchAt = new Map<string, number>()
const adminRouteWarmers: Record<string, () => Promise<void>> = {
'/admin/users': async () => {
await import('@/views/admin/Users.vue')
},
'/admin/providers': async () => {
await import('@/views/admin/ProviderManagement.vue')
},
'/admin/models': async () => {
await import('@/views/admin/ModelManagement.vue')
},
'/admin/routing': async () => {
await import('@/views/admin/RoutingProfiles.vue')
},
'/admin/pool': async () => {
await import('@/views/admin/PoolManagement.vue')
},
'/admin/payment-gateways': async () => {
await import('@/views/admin/PaymentGatewaySettings.vue')
},
'/admin/billing-plans': async () => {
await import('@/views/admin/BillingPlansManagement.vue')
},
type PrefetchableRouteLoader = (() => unknown) & {
prefetch?: () => Promise<unknown>
}
export function prefetchAdminNavigationTarget(href: string): void {
const warmer = adminRouteWarmers[href]
if (!warmer) return
/**
* 预取目标路由链中的异步组件。
*
* 直接从 Router 解析组件,避免维护一份容易遗漏用户页和新增管理页的硬编码表。
*/
export function prefetchNavigationTarget(router: Router, href: string): void {
const now = Date.now()
const lastRun = lastPrefetchAt.get(href) ?? 0
if (now - lastRun < PREFETCH_COOLDOWN_MS) {
return
}
const loaders = router.resolve(href).matched.flatMap((record) =>
Object.values(record.components ?? {})
.filter((component): component is PrefetchableRouteLoader =>
typeof component === 'function'
&& typeof (component as PrefetchableRouteLoader).prefetch === 'function'
)
.map(component => component.prefetch as () => Promise<unknown>)
)
if (loaders.length === 0) return
lastPrefetchAt.set(href, now)
void warmer().catch((err) => {
log.debug('[adminNavigationPrefetch] ignore prefetch failure', err)
})
for (const loader of new Set(loaders)) {
void Promise.resolve()
.then(() => loader())
.catch((err) => {
log.debug('[navigationPrefetch] ignore prefetch failure', err)
})
}
}
+29 -5
View File
@@ -12,6 +12,8 @@ interface CacheItem<T> {
class MemoryCache {
private cache: Map<string, CacheItem<unknown>> = new Map()
private inFlight: Map<string, Promise<unknown>> = new Map()
private epoch = 0
private keyVersions: Map<string, number> = new Map()
private defaultTTL = 60000 // 默认缓存60秒
/**
@@ -55,14 +57,18 @@ class MemoryCache {
*/
delete(key: string): void {
this.cache.delete(key)
this.inFlight.delete(key)
this.keyVersions.set(key, (this.keyVersions.get(key) ?? 0) + 1)
}
/**
* 清空所有缓存
*/
clear(): void {
this.epoch += 1
this.cache.clear()
this.inFlight.clear()
this.keyVersions.clear()
}
/**
@@ -101,8 +107,21 @@ class MemoryCache {
/**
* 清除进行中的请求
*/
deleteInFlight(key: string): void {
this.inFlight.delete(key)
deleteInFlight(key: string, request?: Promise<unknown>): void {
if (!request || this.inFlight.get(key) === request) {
this.inFlight.delete(key)
}
}
/**
* 捕获 key 当前的失效版本,防止退出登录或写操作之后,旧请求重新回填缓存。
*/
version(key: string): readonly [number, number] {
return [this.epoch, this.keyVersions.get(key) ?? 0]
}
isCurrentVersion(key: string, version: readonly [number, number]): boolean {
return version[0] === this.epoch && version[1] === (this.keyVersions.get(key) ?? 0)
}
}
@@ -140,15 +159,20 @@ export async function cachedRequest<T>(
}
// 缓存未命中,执行请求并登记为 in-flight
const request = (async () => {
const version = cache.version(key)
// Keep this mutable declaration: a synchronously throwing fetcher can reach `finally`
// before the Promise assignment completes, so a self-referencing `const` would hit TDZ.
let request: Promise<T>
// eslint-disable-next-line prefer-const
request = (async () => {
try {
const data = await fetcher()
if (ttl !== 0) {
if (ttl !== 0 && cache.isCurrentVersion(key, version)) {
cache.set(key, data, ttl)
}
return data
} finally {
cache.deleteInFlight(key)
cache.deleteInFlight(key, request)
}
})()
+45
View File
@@ -0,0 +1,45 @@
export interface ObserveNearViewportOnceOptions {
target: Element
root?: Element | null
rootMargin?: string
onNearViewport: () => void
}
/**
* Run a callback once when an element reaches the viewport's preload margin.
* Browsers without IntersectionObserver load eagerly so content never remains stuck.
*/
export function observeNearViewportOnce({
target,
root = null,
rootMargin = '0px',
onNearViewport,
}: ObserveNearViewportOnceOptions): () => void {
if (typeof IntersectionObserver === 'undefined') {
onNearViewport()
return () => {}
}
let stopped = false
let observer: IntersectionObserver | null = null
observer = new IntersectionObserver((entries) => {
if (stopped || !entries.some(entry => entry.isIntersecting)) return
stopped = true
observer?.disconnect()
onNearViewport()
}, {
root,
rootMargin,
threshold: 0,
})
observer.observe(target)
return () => {
if (stopped) return
stopped = true
observer?.disconnect()
}
}
@@ -11,7 +11,7 @@
</div>
<div class="flex flex-wrap items-center gap-2">
<Badge variant="outline">
自动刷新 10s
手动刷新
</Badge>
<span class="text-xs text-muted-foreground">
更新 {{ lastUpdatedLabel }}
@@ -19,7 +19,7 @@
<RefreshButton
:loading="refreshing"
title="刷新运维总览"
@click="refreshAll"
@click="refreshAll()"
/>
<TimeRangePicker
v-model="timeRange"
@@ -702,8 +702,8 @@
:value-class="errorRateValueClass"
/>
<MetricCell
label="请求错误"
:value="formatMetricNumber(summaryStats?.error_requests)"
label="已分类错误"
:value="formatMetricNumber(classifiedErrorCount)"
/>
<MetricCell
label="熔断打开"
@@ -1012,7 +1012,7 @@
</template>
<script setup lang="ts">
import { computed, defineComponent, h, onMounted, onUnmounted, ref, watch, type Component } from 'vue'
import { computed, defineComponent, h, onUnmounted, ref, watch, type Component } from 'vue'
import { RouterLink } from 'vue-router'
import type { ChartData, ChartOptions } from 'chart.js'
import {
@@ -1034,9 +1034,8 @@ import LineChart from '@/components/charts/LineChart.vue'
import DoughnutChart from '@/components/charts/DoughnutChart.vue'
import { adminApi, type ErrorDistributionItem, type PercentileItem, type ProviderPerformanceResponse } from '@/api/admin'
import { cacheApi, redisCacheApi, type CacheStats, type RedisCacheCategoriesResponse } from '@/api/cache'
import { monitoringApi, type AdminMonitoringRecentError, type AdminMonitoringResilienceStatus, type AdminMonitoringSystemStatus, type GatewayMetricsSummary } from '@/api/monitoring'
import { monitoringApi, type AdminMonitoringRecentError, type AdminMonitoringResilienceStatus, type GatewayMetricsSummary } from '@/api/monitoring'
import { proxyNodesApi, type ProxyNode, type ProxyNodeMetricsResponse } from '@/api/proxy-nodes'
import { usageApi, type UsageStats } from '@/api/usage'
import { getDateRangeFromPeriod } from '@/features/usage/composables'
import type { DateRangeParams } from '@/features/usage/types'
import { formatByteSize, formatCurrency, formatNumber, formatTokens } from '@/utils/format'
@@ -1063,7 +1062,6 @@ const MetricCell = defineComponent<MetricCellProps>({
},
})
const AUTO_REFRESH_MS = 10_000
const DEFAULT_SLOW_THRESHOLD_MS = 10_000
interface ResourceSnapshot {
@@ -1079,24 +1077,28 @@ const timeRange = ref<DateRangeParams>({
...getDateRangeFromPeriod('today'),
granularity: 'hour',
})
const summaryStats = ref<UsageStats | null>(null)
const timeSeries = ref<Array<Record<string, unknown>>>([])
const percentiles = ref<PercentileItem[]>([])
const providerPerformance = ref<ProviderPerformanceResponse | null>(null)
const errorDistribution = ref<ErrorDistributionItem[]>([])
const systemStatus = ref<AdminMonitoringSystemStatus | null>(null)
const errorDistributionLoaded = ref(false)
const resilienceStatus = ref<AdminMonitoringResilienceStatus | null>(null)
const gatewayMetrics = ref<GatewayMetricsSummary | null>(null)
const cacheStats = ref<CacheStats | null>(null)
const redisCategories = ref<RedisCacheCategoriesResponse | null>(null)
const resourceSnapshot = ref<ResourceSnapshot | null>(null)
const lastUpdatedAt = ref<string | null>(null)
const loadWarning = ref<string | null>(null)
const analyticsWarning = ref<string | null>(null)
const realtimeWarning = ref<string | null>(null)
const loadWarning = computed(() =>
[analyticsWarning.value, realtimeWarning.value].filter(Boolean).join(';') || null
)
const refreshing = ref(false)
const trendLoading = ref(false)
const percentileLoading = ref(false)
let refreshTimer: ReturnType<typeof setInterval> | null = null
let requestId = 0
let refreshPromise: Promise<void> | null = null
let analyticsGeneration = 0
const timeRangeParams = computed(() => ({
start_date: timeRange.value.start_date,
@@ -1314,80 +1316,140 @@ function sumSeries(field: string): number {
return timeSeries.value.reduce((total, item) => total + numeric(item[field]), 0)
}
async function refreshAll() {
function seriesTokenTotal(item: Record<string, unknown>): number {
return numeric(item.input_tokens)
+ numeric(item.output_tokens)
+ numeric(item.cache_creation_tokens)
+ numeric(item.cache_read_tokens)
}
async function performRefresh(refreshAnalytics: boolean) {
const currentRequestId = ++requestId
const currentAnalyticsGeneration = analyticsGeneration
refreshing.value = true
trendLoading.value = timeSeries.value.length === 0
percentileLoading.value = percentiles.value.length === 0
if (refreshAnalytics) {
trendLoading.value = timeSeries.value.length === 0
percentileLoading.value = percentiles.value.length === 0
analyticsWarning.value = null
}
realtimeWarning.value = null
const params = timeRangeParams.value
const canCommitRealtime = () => currentRequestId === requestId
const canCommitAnalytics = () => (
refreshAnalytics
&& canCommitRealtime()
&& currentAnalyticsGeneration === analyticsGeneration
)
const timeSeriesRequest = (refreshAnalytics
? adminApi.getTimeSeries(params, { skipCache: true })
: Promise.resolve(timeSeries.value)
).then((value) => {
if (canCommitAnalytics()) timeSeries.value = value
return value
}).finally(() => {
if (canCommitAnalytics()) trendLoading.value = false
})
const percentilesRequest = (refreshAnalytics
? adminApi.getPercentiles(params, { skipCache: true })
: Promise.resolve(percentiles.value)
).then((value) => {
if (canCommitAnalytics()) percentiles.value = value
return value
}).finally(() => {
if (canCommitAnalytics()) percentileLoading.value = false
})
const providerPerformanceRequest = (refreshAnalytics
? adminApi.getProviderPerformance({
...params,
granularity: params.granularity === 'hour' ? 'hour' : 'day',
limit: 8,
slow_threshold_ms: DEFAULT_SLOW_THRESHOLD_MS,
include_timeline: false,
}, { skipCache: true })
: Promise.resolve(providerPerformance.value)
).then((value) => {
if (canCommitAnalytics()) providerPerformance.value = value
return value
})
const errorDistributionRequest = (refreshAnalytics
? adminApi.getErrorDistribution(params, { skipCache: true })
: Promise.resolve({ distribution: errorDistribution.value })
).then((value) => {
if (canCommitAnalytics()) {
errorDistribution.value = value.distribution
errorDistributionLoaded.value = true
}
return value
})
const resilienceRequest = monitoringApi.getResilienceStatus().then((value) => {
if (canCommitRealtime()) resilienceStatus.value = value
return value
})
const gatewayRequest = monitoringApi.getGatewayMetricsSummary().then((value) => {
if (canCommitRealtime()) gatewayMetrics.value = value
return value
})
const cacheRequest = cacheApi.getStats().then((value) => {
if (canCommitRealtime()) cacheStats.value = value
return value
})
const redisRequest = redisCacheApi.getCategories().then((value) => {
if (canCommitRealtime()) redisCategories.value = value
return value
})
const resourceRequest = loadResourceSnapshot().then((value) => {
if (canCommitRealtime()) resourceSnapshot.value = value
return value
})
const results = await Promise.allSettled([
usageApi.getUsageStats(params, { skipCache: true }),
adminApi.getTimeSeries(params),
adminApi.getPercentiles(params),
adminApi.getProviderPerformance({
...params,
granularity: params.granularity === 'hour' ? 'hour' : 'day',
limit: 8,
slow_threshold_ms: DEFAULT_SLOW_THRESHOLD_MS,
}),
adminApi.getErrorDistribution(params),
monitoringApi.getSystemStatus(),
monitoringApi.getResilienceStatus(),
monitoringApi.getGatewayMetricsSummary(),
cacheApi.getStats(),
redisCacheApi.getCategories(),
loadResourceSnapshot(),
timeSeriesRequest,
percentilesRequest,
providerPerformanceRequest,
errorDistributionRequest,
resilienceRequest,
gatewayRequest,
cacheRequest,
redisRequest,
resourceRequest,
])
if (currentRequestId !== requestId) return
const failed: string[] = []
const analyticsFailed: string[] = []
const realtimeFailed: string[] = []
const [
summaryResult,
timeSeriesResult,
percentilesResult,
providerPerformanceResult,
errorDistributionResult,
systemStatusResult,
resilienceResult,
gatewayResult,
cacheResult,
redisResult,
resourceResult,
] = results
if (summaryResult.status === 'fulfilled') summaryStats.value = summaryResult.value
else failed.push('统计摘要')
if (refreshAnalytics && currentAnalyticsGeneration === analyticsGeneration) {
if (timeSeriesResult.status === 'rejected') analyticsFailed.push('流量趋势')
if (percentilesResult.status === 'rejected') analyticsFailed.push('延迟百分位')
if (providerPerformanceResult.status === 'rejected') analyticsFailed.push('上游性能')
if (errorDistributionResult.status === 'rejected') analyticsFailed.push('错误分类')
if (timeSeriesResult.status === 'fulfilled') timeSeries.value = timeSeriesResult.value
else failed.push('流量趋势')
analyticsWarning.value = analyticsFailed.length
? `分析数据加载失败:${analyticsFailed.join('、')}`
: null
}
if (percentilesResult.status === 'fulfilled') percentiles.value = percentilesResult.value
else failed.push('延迟百分位')
if (providerPerformanceResult.status === 'fulfilled') providerPerformance.value = providerPerformanceResult.value
else failed.push('上游性能')
if (errorDistributionResult.status === 'fulfilled') errorDistribution.value = errorDistributionResult.value.distribution
else failed.push('错误分类')
if (systemStatusResult.status === 'fulfilled') systemStatus.value = systemStatusResult.value
else failed.push('系统状态')
if (resilienceResult.status === 'fulfilled') resilienceStatus.value = resilienceResult.value
else failed.push('韧性状态')
if (gatewayResult.status === 'fulfilled') gatewayMetrics.value = gatewayResult.value
else failed.push('网关指标')
if (cacheResult.status === 'fulfilled') cacheStats.value = cacheResult.value
else failed.push('缓存统计')
if (redisResult.status === 'fulfilled') redisCategories.value = redisResult.value
else failed.push('Redis 分类')
if (resourceResult.status === 'fulfilled') resourceSnapshot.value = resourceResult.value
if (resilienceResult.status === 'rejected') realtimeFailed.push('韧性状态')
if (gatewayResult.status === 'rejected') realtimeFailed.push('网关指标')
if (cacheResult.status === 'rejected') realtimeFailed.push('缓存统计')
if (redisResult.status === 'rejected') realtimeFailed.push('Redis 分类')
results.forEach((result, index) => {
if (result.status === 'rejected') {
@@ -1395,19 +1457,45 @@ async function refreshAll() {
}
})
loadWarning.value = failed.length ? `部分数据加载失败:${failed.join('、')}` : null
lastUpdatedAt.value = new Date().toISOString()
refreshing.value = false
trendLoading.value = false
percentileLoading.value = false
realtimeWarning.value = realtimeFailed.length
? `实时数据加载失败:${realtimeFailed.join('、')}`
: null
if (currentAnalyticsGeneration === analyticsGeneration) {
lastUpdatedAt.value = new Date().toISOString()
}
}
function refreshAll(): Promise<void> {
if (refreshPromise) {
return refreshPromise
}
const request = performRefresh(true).finally(() => {
if (refreshPromise === request) {
refreshPromise = null
}
refreshing.value = false
trendLoading.value = false
percentileLoading.value = false
})
refreshPromise = request
return request
}
const lastUpdatedLabel = computed(() => formatShortDate(lastUpdatedAt.value))
const totalRequests = computed(() => summaryStats.value?.total_requests ?? sumSeries('total_requests'))
const totalTokens = computed(() => summaryStats.value?.total_tokens ?? sumSeries('total_tokens'))
const totalCost = computed(() => summaryStats.value?.total_cost ?? sumSeries('total_cost'))
const avgResponseMs = computed(() => providerPerformance.value?.summary.avg_response_time_ms ?? (summaryStats.value?.avg_response_time ? summaryStats.value.avg_response_time * 1000 : null))
const totalRequests = computed(() => sumSeries('total_requests'))
const totalTokens = computed(() => timeSeries.value.reduce(
(total, item) => total + seriesTokenTotal(item),
0,
))
const totalCost = computed(() => sumSeries('total_cost'))
const classifiedErrorCount = computed(() => (
errorDistributionLoaded.value
? errorDistribution.value.reduce((total, item) => total + numeric(item.count), 0)
: null
))
const avgResponseMs = computed(() => providerPerformance.value?.summary.avg_response_time_ms ?? null)
const avgFirstByteMs = computed(() => providerPerformance.value?.summary.avg_first_byte_time_ms ?? average(percentiles.value.map(item => item.p50_first_byte_time_ms)))
const avgOutputTps = computed(() => providerPerformance.value?.summary.avg_output_tps ?? null)
const windowSeconds = computed(() => {
@@ -1446,9 +1534,9 @@ const kpiCards = computed<Array<{
iconClass: 'text-sky-500',
},
{
title: '吞吐 Tokens',
title: '趋势 Tokens',
value: formatTokens(totalTokens.value),
hint: `${formatMetricNumber(tokensPerMinute.value)} TPM`,
hint: `趋势聚合 · ${formatMetricNumber(tokensPerMinute.value)} TPM`,
icon: Zap,
iconClass: 'text-amber-500',
},
@@ -1511,7 +1599,7 @@ const trafficChartData = computed<ChartData<'line'>>(() => ({
},
{
label: 'Tokens',
data: timeSeries.value.map(item => numeric(item.total_tokens)),
data: timeSeries.value.map(seriesTokenTotal),
borderColor: 'rgb(245, 158, 11)',
backgroundColor: 'rgba(245, 158, 11, 0.12)',
tension: 0.25,
@@ -1609,8 +1697,8 @@ const distributedGateVariant = computed<'warning' | 'outline'>(() => (
const distributedGateText = computed(() => (
gatewayMetrics.value?.distributed.unavailable ? '全局不可用' : '全局在线'
))
const currentActiveStreams = computed(() => gatewayMetrics.value?.tunnel.activeStreams ?? systemStatus.value?.tunnel.active_streams ?? null)
const currentProxyConnections = computed(() => gatewayMetrics.value?.tunnel.proxyConnections ?? systemStatus.value?.tunnel.proxy_connections ?? null)
const currentActiveStreams = computed(() => gatewayMetrics.value?.tunnel.activeStreams ?? null)
const currentProxyConnections = computed(() => gatewayMetrics.value?.tunnel.proxyConnections ?? null)
const localGateUtilization = computed(() => gateUtilization(gatewayMetrics.value?.local))
const distributedGateUtilization = computed(() => gateUtilization(gatewayMetrics.value?.distributed))
const candidatePlanningGateUtilization = computed(() => gateUtilization(gatewayMetrics.value?.candidatePlanning))
@@ -2078,20 +2166,21 @@ const opsLinks = [
]
watch(timeRange, () => {
void refreshAll()
// 手动模式下切换范围只清空旧范围数据,不自动发起请求。
analyticsGeneration += 1
timeSeries.value = []
percentiles.value = []
providerPerformance.value = null
errorDistribution.value = []
errorDistributionLoaded.value = false
analyticsWarning.value = null
lastUpdatedAt.value = null
trendLoading.value = false
percentileLoading.value = false
}, { deep: true })
onMounted(() => {
void refreshAll()
refreshTimer = setInterval(() => {
void refreshAll()
}, AUTO_REFRESH_MS)
})
onUnmounted(() => {
if (refreshTimer) {
clearInterval(refreshTimer)
refreshTimer = null
}
requestId += 1
analyticsGeneration += 1
})
</script>
+53 -8
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue'
import { ref, computed, nextTick, onMounted, watch, onBeforeUnmount } from 'vue'
import Card from '@/components/ui/card.vue'
import Button from '@/components/ui/button.vue'
import Badge from '@/components/ui/badge.vue'
@@ -34,6 +34,7 @@ import {
import { log } from '@/utils/logger'
import { formatApiFormat } from '@/api/endpoints/types/api-format'
import { formatClientFamily } from '@/features/usage/utils/clientFamily'
import { observeNearViewportOnce } from '@/utils/nearViewport'
// ==================== 缓存统计与亲和性列表 ====================
@@ -71,6 +72,12 @@ const { confirm: showConfirm } = useConfirm()
let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null
let skipNextKeywordWatch = false
let countdownTimer: ReturnType<typeof setInterval> | null = null
let stopAnalysisObserver: (() => void) | null = null
let initialDataPromise: Promise<void> | null = null
let analysisLoadRequested = false
let isUnmounted = false
const analysisSectionRef = ref<HTMLElement | null>(null)
// ==================== TTL 分析 (使用 composable) ====================
@@ -521,6 +528,34 @@ async function refreshData() {
])
}
function requestAnalysisLoad() {
if (analysisLoadRequested) return
analysisLoadRequested = true
const waitForInitialData = initialDataPromise ?? Promise.resolve()
void waitForInitialData.then(() => {
if (!isUnmounted) {
return refreshAnalysis()
}
})
}
function setupAnalysisObserver() {
const target = analysisSectionRef.value
if (!target) {
requestAnalysisLoad()
return
}
const scrollRoot = target.closest('.app-shell__content')
stopAnalysisObserver = observeNearViewportOnce({
target,
root: scrollRoot,
rootMargin: '600px 0px',
onNearViewport: requestAnalysisLoad,
})
}
// ==================== 生命周期 ====================
watch(tableKeyword, (value) => {
@@ -540,18 +575,25 @@ watch(tableKeyword, (value) => {
onMounted(() => {
document.addEventListener('visibilitychange', handleVisibilityChange)
fetchCacheStats()
fetchCacheConfig()
fetchAffinityList()
fetchModelMappingStats()
fetchRedisCacheCategories()
const initialLoad = refreshData()
initialDataPromise = initialLoad
void initialLoad.finally(() => {
if (initialDataPromise === initialLoad) {
initialDataPromise = null
}
})
startCountdown()
refreshAnalysis()
void nextTick().then(() => {
if (!isUnmounted) setupAnalysisObserver()
})
})
onBeforeUnmount(() => {
isUnmounted = true
document.removeEventListener('visibilitychange', handleVisibilityChange)
if (searchDebounceTimer) clearTimeout(searchDebounceTimer)
stopAnalysisObserver?.()
stopAnalysisObserver = null
stopCountdown()
})
</script>
@@ -1342,7 +1384,10 @@ onBeforeUnmount(() => {
<!-- TTL 分析区域 -->
<Card class="overflow-hidden">
<div class="px-4 sm:px-6 py-3 sm:py-3.5 border-b border-border/60">
<div
ref="analysisSectionRef"
class="px-4 sm:px-6 py-3 sm:py-3.5 border-b border-border/60"
>
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
<div class="flex items-center gap-3 shrink-0">
<BarChart3 class="h-5 w-5 text-muted-foreground hidden sm:block" />
+12 -13
View File
@@ -742,7 +742,7 @@ async function handleResetTemplate() {
async function loadEmailConfig() {
try {
const configs = [
const configKeys = [
// SMTP 邮件配置
'smtp_host',
'smtp_port',
@@ -756,19 +756,18 @@ async function loadEmailConfig() {
'email_suffix_mode',
'email_suffix_list',
]
const configs = await adminApi.getAllSystemConfigs({ cacheTtlMs: 30_000 })
const configsByKey = new Map(configs.map(config => [config.key, config]))
for (const key of configs) {
try {
const response = await adminApi.getSystemConfig(key)
// 特殊处理敏感字段:只记录是否已设置,不填充值
if (key === 'smtp_password') {
smtpPasswordIsSet.value = response.is_set === true
// 不设置 smtp_password 的值,保持为 null
} else if (response.value !== null && response.value !== undefined) {
(emailConfig.value as Record<string, unknown>)[key] = response.value
}
} catch {
// 配置不存在时使用默认值,无需处理
for (const key of configKeys) {
const response = configsByKey.get(key)
if (!response) continue
// 特殊处理敏感字段:只记录是否已设置,不填充值
if (key === 'smtp_password') {
smtpPasswordIsSet.value = response.is_set === true
// 不设置 smtp_password 的值,保持为 null
} else if (response.value !== null && response.value !== undefined) {
(emailConfig.value as Record<string, unknown>)[key] = response.value
}
}
} catch (err) {
@@ -1145,11 +1145,27 @@ async function loadLiveData(options: { silent?: boolean } = {}) {
liveRefreshing.value = true
}
function commitIfCurrent<T>(request: Promise<T>, commit: (value: T) => void): Promise<void> {
return request.then((value) => {
if (requestId !== liveRequestId) return
commit(value)
liveReady.value = true
})
}
const results = await Promise.allSettled([
monitoringApi.getSystemStatus(),
monitoringApi.getResilienceStatus(),
monitoringApi.getCircuitHistory(8),
monitoringApi.getGatewayMetricsSummary(),
commitIfCurrent(monitoringApi.getSystemStatus(), (value) => {
systemStatus.value = value
}),
commitIfCurrent(monitoringApi.getResilienceStatus(), (value) => {
resilienceStatus.value = value
}),
commitIfCurrent(monitoringApi.getCircuitHistory(8), (value) => {
circuitHistory.value = value.items
}),
commitIfCurrent(monitoringApi.getGatewayMetricsSummary(), (value) => {
gatewayMetrics.value = value
}),
])
if (requestId !== liveRequestId) {
@@ -1162,7 +1178,6 @@ async function loadLiveData(options: { silent?: boolean } = {}) {
const [systemResult, resilienceResult, circuitResult, metricsResult] = results
if (systemResult.status === 'fulfilled') {
systemStatus.value = systemResult.value
successCount += 1
} else {
failedScopes.push('系统状态')
@@ -1170,7 +1185,6 @@ async function loadLiveData(options: { silent?: boolean } = {}) {
}
if (resilienceResult.status === 'fulfilled') {
resilienceStatus.value = resilienceResult.value
successCount += 1
} else {
failedScopes.push('韧性状态')
@@ -1178,7 +1192,6 @@ async function loadLiveData(options: { silent?: boolean } = {}) {
}
if (circuitResult.status === 'fulfilled') {
circuitHistory.value = circuitResult.value.items
successCount += 1
} else {
failedScopes.push('熔断历史')
@@ -1186,7 +1199,6 @@ async function loadLiveData(options: { silent?: boolean } = {}) {
}
if (metricsResult.status === 'fulfilled') {
gatewayMetrics.value = metricsResult.value
successCount += 1
} else {
failedScopes.push('网关指标')
@@ -221,6 +221,7 @@
/>
<ProviderDetailDrawer
v-if="providerDrawerOpen"
:open="providerDrawerOpen"
:provider-id="selectedProviderId"
:initial-provider="selectedProvider"
@@ -239,7 +240,7 @@
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { ref, computed, watch, onMounted, onUnmounted, defineAsyncComponent } from 'vue'
import Card from '@/components/ui/card.vue'
import Table from '@/components/ui/table.vue'
import TableHeader from '@/components/ui/table-header.vue'
@@ -251,7 +252,6 @@ import TableFilterMenu from '@/components/ui/table-filter-menu.vue'
import Pagination from '@/components/ui/pagination.vue'
import { ProviderFormDialog, PriorityManagementDialog, ProviderAuthDialog } from '@/features/providers/components'
import ProviderBatchActionDialog from '@/features/providers/components/ProviderBatchActionDialog.vue'
import ProviderDetailDrawer from '@/features/providers/components/ProviderDetailDrawer.vue'
import ProviderTableHeader from '@/features/providers/components/ProviderTableHeader.vue'
import ProviderTableRow from '@/features/providers/components/ProviderTableRow.vue'
import ProviderMobileCard from '@/features/providers/components/ProviderMobileCard.vue'
@@ -275,6 +275,10 @@ import { adminApi } from '@/api/admin'
import { parseApiError } from '@/utils/errorParser'
import { useI18n } from '@/i18n'
const ProviderDetailDrawer = defineAsyncComponent(
() => import('@/features/providers/components/ProviderDetailDrawer.vue'),
)
interface ProviderDeleteProgressState {
providerId: string
providerName: string
+1 -2
View File
@@ -367,10 +367,9 @@ watch([timeRange, metric], scheduleLeaderboardLoad, { deep: true })
watch([timeRange, selectedUserId, compareUserId], scheduleUserPanelsLoad, { deep: true })
onMounted(async () => {
await loadUsers()
await Promise.all([
loadLeaderboard(),
loadUserPanels()
loadUsers()
])
})
+57 -24
View File
@@ -24,7 +24,7 @@
@update:sort-option="sortOption = $event"
@open-groups="showUserGroupsDialog = true"
@create-user="openCreateDialog"
@refresh="refreshUsers"
@refresh="handleManualRefresh"
/>
<UserSelectionToolbar
@@ -189,7 +189,7 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useUsersStore } from '@/stores/users'
import { useAuthStore } from '@/stores/auth'
import {
@@ -325,7 +325,9 @@ const currentPage = ref(1)
const pageSize = ref(20)
const USERS_PAGE_CACHE_TTL_MS = 10 * 1000
const USER_WALLETS_CACHE_TTL_MS = 10 * 1000
const USERS_SEARCH_DEBOUNCE_MS = 300
let userWalletsRequestId = 0
let usersSearchDebounceTimer: ReturnType<typeof setTimeout> | null = null
const filteredUsers = computed(() => usersStore.users)
@@ -404,41 +406,72 @@ const userRows = computed<UserManagementRow[]>(() =>
})
)
// Watch filter changes and reset to first page
watch([searchQuery, filterRole, filterStatus, filterGroup, sortOption], () => {
function resetUserListForFilterChange() {
currentPage.value = 1
resetBatchSelection()
}
function clearUsersSearchDebounce() {
if (usersSearchDebounceTimer) {
clearTimeout(usersSearchDebounceTimer)
usersSearchDebounceTimer = null
}
}
watch(searchQuery, () => {
resetUserListForFilterChange()
clearUsersSearchDebounce()
usersSearchDebounceTimer = setTimeout(() => {
usersSearchDebounceTimer = null
void refreshUsers()
}, USERS_SEARCH_DEBOUNCE_MS)
})
watch([filterRole, filterStatus, filterGroup, sortOption], () => {
resetUserListForFilterChange()
clearUsersSearchDebounce()
void refreshUsers()
})
watch(paginatedUsers, (users) => rememberBatchPageUsers(users), { immediate: true })
onMounted(() => {
void refreshUsers({ preferCache: true })
void refreshUsers({ preferCache: true }).then(() =>
loadUserWallets({ cacheTtlMs: USER_WALLETS_CACHE_TTL_MS })
)
void loadUserGroups()
})
onBeforeUnmount(() => {
clearUsersSearchDebounce()
userWalletsRequestId += 1
})
async function refreshUsers(options: { preferCache?: boolean } = {}) {
const cacheTtlMs = options.preferCache ? USERS_PAGE_CACHE_TTL_MS : 0
const search = searchQuery.value.trim()
await Promise.all([
usersStore.fetchUsers({
cacheTtlMs,
search: search || undefined,
role: filterRole.value === 'all' ? undefined : filterRole.value,
is_active: filterStatus.value === 'all' ? undefined : filterStatus.value === 'active',
group_id: filterGroup.value === 'all' ? undefined : filterGroup.value,
sort_by: sortBy.value ?? undefined,
sort_order: sortBy.value ? sortOrder.value : undefined,
skip: (currentPage.value - 1) * pageSize.value,
limit: pageSize.value,
}),
loadUserGroups(),
])
void loadUserWallets({
cacheTtlMs: options.preferCache ? USER_WALLETS_CACHE_TTL_MS : 0,
await usersStore.fetchUsers({
cacheTtlMs,
search: search || undefined,
role: filterRole.value === 'all' ? undefined : filterRole.value,
is_active: filterStatus.value === 'all' ? undefined : filterStatus.value === 'active',
group_id: filterGroup.value === 'all' ? undefined : filterGroup.value,
sort_by: sortBy.value ?? undefined,
sort_order: sortBy.value ? sortOrder.value : undefined,
skip: (currentPage.value - 1) * pageSize.value,
limit: pageSize.value,
})
}
async function handleManualRefresh() {
clearUsersSearchDebounce()
await Promise.all([
refreshUsers(),
loadUserGroups(),
loadUserWallets(),
])
}
function handleTableSort(payload: { key: string, direction: AdminUserSortOrder }): void {
if (payload.key !== 'created_at') return
sortOption.value = payload.direction === 'asc' ? 'created_at_asc' : 'created_at_desc'
@@ -469,7 +502,7 @@ async function loadUserGroups(): Promise<void> {
}
async function handleUserGroupsChanged(): Promise<void> {
await refreshUsers()
await Promise.all([refreshUsers(), loadUserGroups()])
}
function openUserBatchDialog(): void {
@@ -478,7 +511,7 @@ function openUserBatchDialog(): void {
}
async function handleUserBatchCompleted(_result: UserBatchActionResponse): Promise<void> {
await refreshUsers()
await Promise.all([refreshUsers(), loadUserWallets()])
resetBatchSelection(true)
}
@@ -740,7 +773,7 @@ async function handleUserFormSubmit(data: UserFormData & { password?: string; un
success(legacyT('用户创建成功'))
}
closeUserFormDialog()
await refreshUsers()
await Promise.all([refreshUsers(), loadUserWallets()])
} catch (err: unknown) {
const title = data.id ? '更新用户失败' : '创建用户失败'
error(localizedApiError(err, '未知错误'), legacyT(title))
+33 -9
View File
@@ -1427,6 +1427,7 @@ const { legacyT } = useI18n()
const route = useRoute()
const activeTab = ref<WalletManagementTab>('ledger')
const activeTabLoadPromises = new Map<WalletManagementTab, Promise<void>>()
const loadingLedger = ref(false)
const loadingRefunds = ref(false)
@@ -1596,23 +1597,46 @@ watch(
)
onMounted(async () => {
await Promise.all([
loadWalletMetaMap(),
loadLedger(),
loadRefunds(),
loadOrders(),
loadCallbacks(),
loadRedeemCodeBatches(),
])
await loadActiveTab()
})
watch(activeTab, () => {
void loadActiveTab()
})
function isValidTab(tab: unknown): tab is WalletManagementTab {
return tab === 'ledger' || tab === 'refunds' || tab === 'orders' || tab === 'callbacks' || tab === 'redeem_codes'
}
function loadActiveTab(): Promise<void> {
const tab = activeTab.value
const existing = activeTabLoadPromises.get(tab)
if (existing) return existing
const request = (async () => {
switch (tab) {
case 'refunds':
return loadRefunds()
case 'orders':
await Promise.all([loadOrders(), loadWalletMetaMap()])
return
case 'callbacks':
return loadCallbacks()
case 'redeem_codes':
return loadRedeemCodeBatches()
default:
return loadLedger()
}
})().finally(() => {
if (activeTabLoadPromises.get(tab) === request) activeTabLoadPromises.delete(tab)
})
activeTabLoadPromises.set(tab, request)
return request
}
async function loadWalletMetaMap() {
try {
const wallets = await adminWalletApi.listAllWallets()
const wallets = await adminWalletApi.listAllWallets(undefined, { cacheTtlMs: 30_000 })
walletMetaMap.value = wallets.reduce<Record<string, { ownerName: string; ownerType: 'user' | 'api_key' }>>(
(acc, wallet) => {
const ownerName =
@@ -0,0 +1,55 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const source = readFileSync(
resolve(process.cwd(), 'src/views/admin/AdminOperationsDashboard.vue'),
'utf8',
)
describe('AdminOperationsDashboard manual refresh', () => {
it('only starts a refresh from the explicit refresh button', () => {
expect(source).toContain('@click="refreshAll()"')
expect(source).not.toContain('onMounted(')
expect(source).not.toContain('setInterval(')
expect(source).not.toContain('visibilitychange')
const rangeWatcher = source
.split('watch(timeRange, () => {')[1]
?.split('}, { deep: true })')[0]
expect(rangeWatcher).toBeTruthy()
expect(rangeWatcher).not.toContain('refreshAll(')
})
it('does not request the heavyweight system-status fallback', () => {
expect(source).not.toContain('monitoringApi.getSystemStatus()')
})
it('forces fresh analytics and renders each result as soon as it settles', () => {
expect(source).toContain('adminApi.getTimeSeries(params, { skipCache: true })')
expect(source).toContain('adminApi.getPercentiles(params, { skipCache: true })')
expect(source).toContain('}, { skipCache: true })')
expect(source).toContain('adminApi.getErrorDistribution(params, { skipCache: true })')
expect(source).toContain('include_timeline: false')
const progressiveSetup = source.split('const results = await Promise.allSettled([')[0]
expect(progressiveSetup).toContain('timeSeries.value = value')
expect(progressiveSetup).toContain('percentiles.value = value')
expect(progressiveSetup).toContain('providerPerformance.value = value')
expect(progressiveSetup).toContain('errorDistribution.value = value.distribution')
expect(progressiveSetup).toContain('gatewayMetrics.value = value')
})
it('reuses analytics responses instead of requesting a duplicate usage summary', () => {
expect(source).not.toContain('usageApi.getUsageStats(')
expect(source).not.toContain('summaryStats')
expect(source).toContain('function seriesTokenTotal(')
expect(source).toContain('numeric(item.input_tokens)')
expect(source).toContain('numeric(item.output_tokens)')
expect(source).toContain('numeric(item.cache_creation_tokens)')
expect(source).toContain('numeric(item.cache_read_tokens)')
expect(source).toContain('timeSeries.value.map(seriesTokenTotal)')
expect(source).toContain('label="已分类错误"')
expect(source).toContain('errorDistribution.value.reduce(')
})
})
@@ -0,0 +1,34 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const source = readFileSync(
resolve(process.cwd(), 'src/views/admin/CacheMonitoring.vue'),
'utf8',
)
describe('CacheMonitoring analysis loading', () => {
it('observes the TTL section against the app scroll container', () => {
expect(source).toContain('ref="analysisSectionRef"')
expect(source).toContain("target.closest('.app-shell__content')")
expect(source).toContain("rootMargin: '600px 0px'")
})
it('keeps TTL and hit analysis out of the initial request group', () => {
const mountedBlock = source
.split('onMounted(() => {')[1]
?.split('onBeforeUnmount')[0]
expect(mountedBlock).toBeTruthy()
expect(mountedBlock).toContain('const initialLoad = refreshData()')
expect(mountedBlock).not.toContain('refreshAnalysis()')
expect(source).toContain('const waitForInitialData = initialDataPromise ?? Promise.resolve()')
})
it('cleans up the observer when the page unmounts', () => {
const unmountedBlock = source.split('onBeforeUnmount(() => {')[1]
expect(unmountedBlock).toBeTruthy()
expect(unmountedBlock).toContain('stopAnalysisObserver?.()')
})
})
@@ -0,0 +1,41 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const source = readFileSync(
resolve(process.cwd(), 'src/views/admin/PerformanceAnalysis.vue'),
'utf8',
)
describe('PerformanceAnalysis progressive live data', () => {
it('commits each live response before the full request group settles', () => {
const liveDataBlock = source
.split('async function loadLiveData')[1]
?.split('const errorTrendChartData')[0]
expect(liveDataBlock).toBeTruthy()
expect(liveDataBlock).toContain('function commitIfCurrent<T>')
expect(liveDataBlock).toContain('if (requestId !== liveRequestId) return')
expect(liveDataBlock).toContain('systemStatus.value = value')
expect(liveDataBlock).toContain('resilienceStatus.value = value')
expect(liveDataBlock).toContain('circuitHistory.value = value.items')
expect(liveDataBlock).toContain('gatewayMetrics.value = value')
expect(liveDataBlock).toContain('liveReady.value = true')
expect(liveDataBlock).not.toContain('systemStatus.value = systemResult.value')
expect(liveDataBlock).not.toContain('resilienceStatus.value = resilienceResult.value')
expect(liveDataBlock).not.toContain('gatewayMetrics.value = metricsResult.value')
})
it('keeps group completion for loading state and error aggregation', () => {
const liveDataBlock = source
.split('async function loadLiveData')[1]
?.split('const errorTrendChartData')[0]
expect(liveDataBlock).toContain('await Promise.allSettled([')
expect(liveDataBlock).toContain("failedScopes.push('系统状态')")
expect(liveDataBlock).toContain("failedScopes.push('韧性状态')")
expect(liveDataBlock).toContain("failedScopes.push('熔断历史')")
expect(liveDataBlock).toContain("failedScopes.push('网关指标')")
expect(liveDataBlock).toContain('liveLoading.value = false')
expect(liveDataBlock).toContain('liveRefreshing.value = false')
})
})
@@ -0,0 +1,28 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const source = readFileSync(
resolve(process.cwd(), 'src/views/admin/ProviderManagement.vue'),
'utf8',
)
describe('ProviderManagement detail drawer loading', () => {
it('keeps the heavy detail drawer out of the initial route chunk', () => {
expect(source).not.toContain(
"import ProviderDetailDrawer from '@/features/providers/components/ProviderDetailDrawer.vue'",
)
expect(source).toContain(
"() => import('@/features/providers/components/ProviderDetailDrawer.vue')",
)
})
it('does not resolve the async drawer until it is opened', () => {
const drawerTemplate = source
.split('<ProviderDetailDrawer')[1]
?.split('/>')[0]
expect(drawerTemplate).toBeTruthy()
expect(drawerTemplate).toContain('v-if="providerDrawerOpen"')
})
})
@@ -0,0 +1,56 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const source = readFileSync(
resolve(process.cwd(), 'src/views/admin/Users.vue'),
'utf8',
)
describe('Users request loading', () => {
it('debounces search without delaying discrete filters', () => {
const searchWatcher = source
.split('watch(searchQuery, () => {')[1]
?.split('watch([filterRole, filterStatus, filterGroup, sortOption]')[0]
expect(searchWatcher).toBeTruthy()
expect(searchWatcher).toContain('setTimeout(')
expect(searchWatcher).toContain('USERS_SEARCH_DEBOUNCE_MS')
const discreteFilterWatcher = source
.split('watch([filterRole, filterStatus, filterGroup, sortOption], () => {')[1]
?.split('watch(paginatedUsers')[0]
expect(discreteFilterWatcher).toBeTruthy()
expect(discreteFilterWatcher).not.toContain('setTimeout(')
expect(discreteFilterWatcher).toContain('refreshUsers()')
})
it('does not reload invariant metadata for every list refresh', () => {
const listRefresh = source
.split('async function refreshUsers(')[1]
?.split('async function handleManualRefresh()')[0]
expect(listRefresh).toBeTruthy()
expect(listRefresh).not.toContain('loadUserGroups()')
expect(listRefresh).not.toContain('loadUserWallets(')
const manualRefresh = source
.split('async function handleManualRefresh()')[1]
?.split('function handleTableSort')[0]
expect(manualRefresh).toBeTruthy()
expect(manualRefresh).toContain('refreshUsers()')
expect(manualRefresh).toContain('loadUserGroups()')
expect(manualRefresh).toContain('loadUserWallets()')
expect(source).toContain('@refresh="handleManualRefresh"')
})
it('refreshes wallet state after user access-control mutations', () => {
const batchCompleted = source
.split('async function handleUserBatchCompleted')[1]
?.split('function invalidateUserOptions')[0]
expect(batchCompleted).toContain('Promise.all([refreshUsers(), loadUserWallets()])')
const formSubmit = source
.split('async function handleUserFormSubmit')[1]
?.split('async function manageApiKeys')[0]
expect(formSubmit).toContain('Promise.all([refreshUsers(), loadUserWallets()])')
})
})
@@ -0,0 +1,24 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const source = readFileSync(
resolve(process.cwd(), 'src/views/admin/WalletsManagement.vue'),
'utf8',
)
describe('WalletsManagement wallet metadata loading', () => {
it('only loads the full wallet metadata map for the orders tab', () => {
const mountedBlock = source
.split('onMounted(async () => {')[1]
?.split('})')[0]
expect(mountedBlock).toBeTruthy()
expect(mountedBlock).not.toContain('loadWalletMetaMap()')
const ordersBranch = source
.split("case 'orders':")[1]
?.split("case 'callbacks':")[0]
expect(ordersBranch).toBeTruthy()
expect(ordersBranch).toContain('Promise.all([loadOrders(), loadWalletMetaMap()])')
})
})
@@ -180,20 +180,22 @@ onMounted(() => {
async function loadConfig() {
try {
const [moduleStatus, deviceKey, serverUrl, template] = await Promise.all([
const [moduleStatus, configs] = await Promise.all([
modulesApi.getStatus('bark_push'),
adminApi.getSystemConfig(CONFIG_KEYS.device_key),
adminApi.getSystemConfig(CONFIG_KEYS.server_url),
adminApi.getSystemConfig(CONFIG_KEYS.template),
adminApi.getAllSystemConfigs({ cacheTtlMs: 30_000 }),
])
const configsByKey = new Map(configs.map(config => [config.key, config]))
const deviceKey = configsByKey.get(CONFIG_KEYS.device_key)
const serverUrl = configsByKey.get(CONFIG_KEYS.server_url)
const template = configsByKey.get(CONFIG_KEYS.template)
enabled.value = moduleStatus.enabled === true
deviceKeyIsSet.value = deviceKey.is_set === true
deviceKeyIsSet.value = deviceKey?.is_set === true
deviceKeyInput.value = ''
serverUrlInput.value = typeof serverUrl.value === 'string' && serverUrl.value.trim()
serverUrlInput.value = typeof serverUrl?.value === 'string' && serverUrl.value.trim()
? serverUrl.value
: DEFAULT_SERVER_URL
templateInput.value = typeof template.value === 'string' ? template.value : ''
templateInput.value = typeof template?.value === 'string' ? template.value : ''
} catch (err) {
error(parseApiError(err, '加载 Bark 推送配置失败'))
log.error('加载 Bark 推送配置失败:', err)
@@ -532,42 +532,33 @@ onMounted(() => {
async function loadConfig() {
try {
const [
moduleStatus,
emailEnabled,
recipients,
defaultChannel,
items,
serverChanModuleStatus,
serverChanKey,
barkModuleStatus,
barkDeviceKey,
smtpHost,
smtpFromEmail,
] = await Promise.all([
modulesApi.getStatus('important_notification'),
adminApi.getSystemConfig(CONFIG_KEYS.email_enabled),
adminApi.getSystemConfig(CONFIG_KEYS.email_recipients),
adminApi.getSystemConfig(CONFIG_KEYS.default_channel),
adminApi.getSystemConfig(CONFIG_KEYS.items),
modulesApi.getStatus('server_chan_push'),
adminApi.getSystemConfig(CONFIG_KEYS.server_chan_send_key),
modulesApi.getStatus('bark_push'),
adminApi.getSystemConfig(CONFIG_KEYS.bark_device_key),
adminApi.getSystemConfig('smtp_host'),
adminApi.getSystemConfig('smtp_from_email'),
const [moduleStatuses, configs] = await Promise.all([
modulesApi.getAllStatus(),
adminApi.getAllSystemConfigs({ cacheTtlMs: 30_000 }),
])
const moduleStatus = moduleStatuses.important_notification
const serverChanModuleStatus = moduleStatuses.server_chan_push
const barkModuleStatus = moduleStatuses.bark_push
const configsByKey = new Map(configs.map(config => [config.key, config]))
const emailEnabled = configsByKey.get(CONFIG_KEYS.email_enabled)
const recipients = configsByKey.get(CONFIG_KEYS.email_recipients)
const defaultChannel = configsByKey.get(CONFIG_KEYS.default_channel)
const items = configsByKey.get(CONFIG_KEYS.items)
const serverChanKey = configsByKey.get(CONFIG_KEYS.server_chan_send_key)
const barkDeviceKey = configsByKey.get(CONFIG_KEYS.bark_device_key)
const smtpHost = configsByKey.get('smtp_host')
const smtpFromEmail = configsByKey.get('smtp_from_email')
config.value.enabled = moduleStatus.enabled === true
config.value.email_enabled = emailEnabled.value === true
config.value.email_recipients = normalizeRecipients(recipients.value)
config.value.default_channel = normalizeDefaultChannel(defaultChannel.value)
config.value.items = normalizeItems(items.value)
config.value.email_enabled = emailEnabled?.value === true
config.value.email_recipients = normalizeRecipients(recipients?.value)
config.value.default_channel = normalizeDefaultChannel(defaultChannel?.value)
config.value.items = normalizeItems(items?.value)
serverChanStatus.value = serverChanModuleStatus
serverChanKeyIsSet.value = serverChanKey.is_set === true
serverChanKeyIsSet.value = serverChanKey?.is_set === true
barkStatus.value = barkModuleStatus
barkKeyIsSet.value = barkDeviceKey.is_set === true
smtpConfigured.value = isNonEmptyString(smtpHost.value) && isNonEmptyString(smtpFromEmail.value)
barkKeyIsSet.value = barkDeviceKey?.is_set === true
smtpConfigured.value = isNonEmptyString(smtpHost?.value) && isNonEmptyString(smtpFromEmail?.value)
if (!config.value.items.some(item => item.key === testItemKey.value)) {
testItemKey.value = config.value.items[0]?.key || ''
}
@@ -154,16 +154,18 @@ onMounted(() => {
async function loadConfig() {
try {
const [moduleStatus, sendKey, template] = await Promise.all([
const [moduleStatus, configs] = await Promise.all([
modulesApi.getStatus('server_chan_push'),
adminApi.getSystemConfig(CONFIG_KEYS.send_key),
adminApi.getSystemConfig(CONFIG_KEYS.template),
adminApi.getAllSystemConfigs({ cacheTtlMs: 30_000 }),
])
const configsByKey = new Map(configs.map(config => [config.key, config]))
const sendKey = configsByKey.get(CONFIG_KEYS.send_key)
const template = configsByKey.get(CONFIG_KEYS.template)
enabled.value = moduleStatus.enabled === true
sendKeyIsSet.value = sendKey.is_set === true
sendKeyIsSet.value = sendKey?.is_set === true
sendKeyInput.value = ''
templateInput.value = typeof template.value === 'string' ? template.value : ''
templateInput.value = typeof template?.value === 'string' ? template.value : ''
} catch (err) {
error(parseApiError(err, '加载 Server 酱推送配置失败'))
log.error('加载 Server 酱推送配置失败:', err)
@@ -1,8 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { getSystemConfigMock, updateSystemConfigMock, runS3BackupMock, errorMock, successMock } =
const { getAllSystemConfigsMock, updateSystemConfigMock, runS3BackupMock, errorMock, successMock } =
vi.hoisted(() => ({
getSystemConfigMock: vi.fn(),
getAllSystemConfigsMock: vi.fn(),
updateSystemConfigMock: vi.fn(),
runS3BackupMock: vi.fn(),
errorMock: vi.fn(),
@@ -11,7 +11,7 @@ const { getSystemConfigMock, updateSystemConfigMock, runS3BackupMock, errorMock,
vi.mock('@/api/admin', () => ({
adminApi: {
getSystemConfig: getSystemConfigMock,
getAllSystemConfigs: getAllSystemConfigsMock,
updateSystemConfig: updateSystemConfigMock,
runS3Backup: runS3BackupMock,
},
@@ -28,7 +28,7 @@ import { useS3BackupConfig } from '../composables/useS3BackupConfig'
describe('useS3BackupConfig', () => {
beforeEach(() => {
getSystemConfigMock.mockReset()
getAllSystemConfigsMock.mockReset()
updateSystemConfigMock.mockReset()
runS3BackupMock.mockReset()
errorMock.mockReset()
@@ -36,15 +36,10 @@ describe('useS3BackupConfig', () => {
})
it('loads write-only secret as configured without exposing the value', async () => {
getSystemConfigMock.mockImplementation(async (key: string) => {
if (key === 'backup_s3_secret_access_key') {
return { key, value: null, is_set: true }
}
if (key === 'backup_s3_scope') {
return { key, value: 'data' }
}
return { key, value: null }
})
getAllSystemConfigsMock.mockResolvedValue([
{ key: 'backup_s3_secret_access_key', value: null, is_set: true },
{ key: 'backup_s3_scope', value: 'data' },
])
const backup = useS3BackupConfig()
await backup.loadS3BackupConfig()
@@ -55,12 +50,9 @@ describe('useS3BackupConfig', () => {
})
it('keeps an existing secret when saving with an empty secret field', async () => {
getSystemConfigMock.mockImplementation(async (key: string) => {
if (key === 'backup_s3_secret_access_key') {
return { key, value: null, is_set: true }
}
return { key, value: null }
})
getAllSystemConfigsMock.mockResolvedValue([
{ key: 'backup_s3_secret_access_key', value: null, is_set: true },
])
updateSystemConfigMock.mockResolvedValue({})
const backup = useS3BackupConfig()
@@ -76,15 +68,10 @@ describe('useS3BackupConfig', () => {
it('reloads server state when saving fails before writing a new secret', async () => {
let loadRound = 0
getSystemConfigMock.mockImplementation(async (key: string) => {
if (key === 'backup_s3_secret_access_key') {
return { key, value: null, is_set: false }
}
if (key === 'backup_s3_bucket') {
return { key, value: loadRound === 0 ? 'old-bucket' : 'server-bucket' }
}
return { key, value: null }
})
getAllSystemConfigsMock.mockImplementation(async () => [
{ key: 'backup_s3_secret_access_key', value: null, is_set: false },
{ key: 'backup_s3_bucket', value: loadRound === 0 ? 'old-bucket' : 'server-bucket' },
])
updateSystemConfigMock.mockImplementation(async (key: string) => {
if (key === 'backup_s3_bucket') {
loadRound += 1
@@ -143,38 +143,37 @@ export function useS3BackupConfig() {
loading.value = true
try {
const next = defaultS3BackupConfig()
await Promise.all(CONFIG_KEYS.map(async (key) => {
try {
const response = await adminApi.getSystemConfig(key)
const field = FIELD_BY_CONFIG_KEY[key]
if (field === 'secretAccessKey') {
next.secretAccessKey = ''
next.secretAccessKeyIsSet = !!response.is_set
return
}
if (response.value === null || response.value === undefined) return
if (field === 'enabled' || field === 'pathStyle') {
next[field] = booleanValue(response.value, next[field])
} else if (
field === 'scheduleInterval' ||
field === 'scheduleMinute' ||
field === 'scheduleHour' ||
field === 'scheduleWeekday' ||
field === 'scheduleMonthDay' ||
field === 'retentionCount'
) {
next[field] = numberValue(response.value, next[field])
} else if (field === 'scope') {
next.scope = scopeValue(response.value, next.scope)
} else if (field === 'scheduleUnit') {
next.scheduleUnit = scheduleUnitValue(response.value, next.scheduleUnit)
} else {
next[field] = stringValue(response.value, next[field] as string)
}
} catch {
// 单个配置缺失时使用默认值
const configs = await adminApi.getAllSystemConfigs({ cacheTtlMs: 30_000 })
const configsByKey = new Map(configs.map((item) => [item.key, item]))
for (const key of CONFIG_KEYS) {
const response = configsByKey.get(key)
if (!response) continue
const field = FIELD_BY_CONFIG_KEY[key]
if (field === 'secretAccessKey') {
next.secretAccessKey = ''
next.secretAccessKeyIsSet = !!response.is_set
continue
}
}))
if (response.value === null || response.value === undefined) continue
if (field === 'enabled' || field === 'pathStyle') {
next[field] = booleanValue(response.value, next[field])
} else if (
field === 'scheduleInterval' ||
field === 'scheduleMinute' ||
field === 'scheduleHour' ||
field === 'scheduleWeekday' ||
field === 'scheduleMonthDay' ||
field === 'retentionCount'
) {
next[field] = numberValue(response.value, next[field])
} else if (field === 'scope') {
next.scope = scopeValue(response.value, next.scope)
} else if (field === 'scheduleUnit') {
next.scheduleUnit = scheduleUnitValue(response.value, next.scheduleUnit)
} else {
next[field] = stringValue(response.value, next[field] as string)
}
}
config.value = next
originalConfig.value = cloneConfig(next)
} catch (err) {
@@ -1,13 +1,13 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { getSystemConfigMock, updateSystemConfigMock } = vi.hoisted(() => ({
getSystemConfigMock: vi.fn(),
const { getAllSystemConfigsMock, updateSystemConfigMock } = vi.hoisted(() => ({
getAllSystemConfigsMock: vi.fn(),
updateSystemConfigMock: vi.fn(),
}))
vi.mock('@/api/admin', () => ({
adminApi: {
getSystemConfig: getSystemConfigMock,
getAllSystemConfigs: getAllSystemConfigsMock,
updateSystemConfig: updateSystemConfigMock,
getSystemVersion: vi.fn(),
},
@@ -34,40 +34,33 @@ vi.mock('@/utils/logger', () => ({
import { useSystemConfig } from '../composables/useSystemConfig'
interface DeferredConfigResponse {
resolve: (value: { key: string, value: unknown, is_set?: boolean }) => void
}
describe('useSystemConfig', () => {
beforeEach(() => {
getSystemConfigMock.mockReset()
getAllSystemConfigsMock.mockReset()
updateSystemConfigMock.mockReset()
})
it('loads config keys in parallel and keeps change detection disabled until the baseline is ready', async () => {
const pending = new Map<string, DeferredConfigResponse>()
getSystemConfigMock.mockImplementation((key: string) => new Promise((resolve) => {
pending.set(key, { resolve })
it('loads config keys in one request and keeps change detection disabled until the baseline is ready', async () => {
let resolveConfigs: ((value: Array<{ key: string, value: unknown, is_set?: boolean }>) => void) | null = null
getAllSystemConfigsMock.mockImplementation(() => new Promise((resolve) => {
resolveConfigs = resolve
}))
const state = useSystemConfig()
const loadPromise = state.loadSystemConfig()
expect(getSystemConfigMock.mock.calls.map(([key]) => key)).toContain('request_record_level')
expect(getSystemConfigMock.mock.calls.map(([key]) => key)).toContain('proxy_node_metrics_cleanup_batch_size')
expect(getSystemConfigMock.mock.calls.map(([key]) => key)).toContain('enable_standard_text_sync_heartbeat')
expect(getAllSystemConfigsMock).toHaveBeenCalledTimes(1)
expect(getAllSystemConfigsMock).toHaveBeenCalledWith({ cacheTtlMs: 30_000 })
state.systemConfig.value.request_record_level = 'headers'
expect(state.systemConfigLoading.value).toBe(true)
expect(state.hasLogConfigChanges.value).toBe(false)
for (const [key, deferred] of pending) {
deferred.resolve({
key,
value: key === 'request_record_level' ? 'basic' : undefined,
is_set: false,
})
}
resolveConfigs?.([
{ key: 'request_record_level', value: 'basic' },
{ key: 'proxy_node_metrics_cleanup_batch_size', value: 5000 },
{ key: 'enable_standard_text_sync_heartbeat', value: false },
])
await loadPromise
expect(state.systemConfigLoading.value).toBe(false)
@@ -79,11 +72,9 @@ describe('useSystemConfig', () => {
})
it('loads and saves the standard text sync heartbeat flag as a basic config item', async () => {
getSystemConfigMock.mockImplementation(async (key: string) => ({
key,
value: key === 'enable_standard_text_sync_heartbeat' ? false : undefined,
is_set: key === 'enable_standard_text_sync_heartbeat',
}))
getAllSystemConfigsMock.mockResolvedValue([
{ key: 'enable_standard_text_sync_heartbeat', value: false },
])
updateSystemConfigMock.mockResolvedValue({})
const state = useSystemConfig()
@@ -102,4 +93,15 @@ describe('useSystemConfig', () => {
)
expect(state.hasBasicConfigChanges.value).toBe(false)
})
it('uses backend-compatible defaults when config rows have not been persisted yet', async () => {
getAllSystemConfigsMock.mockResolvedValue([])
const state = useSystemConfig()
await state.loadSystemConfig()
expect(state.systemConfig.value.request_record_level).toBe('full')
expect(state.systemConfig.value.max_request_body_size).toBe(5_242_880)
expect(state.systemConfig.value.max_response_body_size).toBe(5_242_880)
})
})
@@ -152,9 +152,9 @@ function createDefaultConfig(): SystemConfig {
// 标准文本非流式心跳
enable_standard_text_sync_heartbeat: false,
// 请求记录
request_record_level: 'basic',
max_request_body_size: 1048576,
max_response_body_size: 1048576,
request_record_level: 'full',
max_request_body_size: 5_242_880,
max_response_body_size: 5_242_880,
sensitive_headers: ['authorization', 'x-api-key', 'api-key', 'cookie', 'set-cookie'],
// 请求记录清理
enable_auto_cleanup: true,
@@ -321,25 +321,13 @@ export function useSystemConfig() {
async function loadSystemConfig() {
systemConfigLoading.value = true
try {
const results = await Promise.all(
CONFIG_KEYS.map(async (key) => {
try {
return {
key,
response: await adminApi.getSystemConfig(key),
}
} catch {
return null
}
})
)
const configs = await adminApi.getAllSystemConfigs({ cacheTtlMs: 30_000 })
const configsByKey = new Map(configs.map((config) => [config.key, config]))
const nextConfig = createDefaultConfig()
for (const result of results) {
if (!result) {
continue
}
const { key, response } = result
for (const key of CONFIG_KEYS) {
const response = configsByKey.get(key)
if (!response) continue
try {
if (key === 'turnstile_secret_key') {
nextConfig.turnstile_secret_key = ''
+17 -97
View File
@@ -7,30 +7,12 @@
ref="statsPanelRef"
class="flex-1 min-w-0 flex flex-col"
>
<div class="mb-4 flex items-center justify-between gap-3">
<Badge
:variant="authStore.isAdmin ? 'default' : 'secondary'"
class="uppercase tracking-[0.45em]"
>
{{ dashboardModeLabel }}
</Badge>
<Button
type="button"
:variant="autoRefreshEnabled ? 'default' : 'outline'"
class="h-8 gap-1.5 px-3 text-xs"
:aria-pressed="autoRefreshEnabled"
:title="autoRefreshButtonTitle"
@click="toggleDashboardAutoRefresh"
>
<RefreshCw
class="h-3.5 w-3.5"
:class="{
'animate-spin': autoRefreshEnabled && autoRefreshLoading,
}"
/>
<span>{{ autoRefreshButtonLabel }}</span>
</Button>
</div>
<Badge
:variant="authStore.isAdmin ? 'default' : 'secondary'"
class="mb-4 self-start uppercase tracking-[0.45em]"
>
{{ dashboardModeLabel }}
</Badge>
<!-- 主要统计卡片 -->
<div class="grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4">
@@ -956,7 +938,6 @@ import {
Clock,
Database,
Shuffle,
RefreshCw,
} from "lucide-vue-next";
import { formatTokens, formatCurrency } from "@/utils/format";
import { parseDateLike } from "@/utils/date";
@@ -971,16 +952,10 @@ import type {
const authStore = useAuthStore();
const DASHBOARD_AUTO_REFRESH_INTERVAL_MS = 1_000;
type DashboardStatCard = Omit<DashboardStat, "icon"> & {
icon: Component;
};
type DashboardLoadOptions = {
silent?: boolean;
};
const statsPanelRef = ref<HTMLElement | null>(null);
const announcementsHeight = ref<number | null>(null);
const announcementsTimelineRef = ref<HTMLElement | null>(null);
@@ -1005,8 +980,6 @@ function checkScreenSize() {
let statsPanelObserver: ResizeObserver | null = null;
let announcementsTimelineObserver: ResizeObserver | null = null;
let dashboardAutoRefreshTimer: ReturnType<typeof setInterval> | null = null;
let dashboardRefreshPromise: Promise<void> | null = null;
function updateAnnouncementsHeight() {
if (typeof window === "undefined") return;
@@ -1107,14 +1080,6 @@ const getStatIconColor = (_index: number): string => {
// 统计数据
const stats = ref<DashboardStatCard[]>([]);
const autoRefreshEnabled = ref(false);
const autoRefreshLoading = ref(false);
const autoRefreshButtonLabel = computed(() =>
autoRefreshEnabled.value ? "自动刷新中" : "自动刷新",
);
const autoRefreshButtonTitle = computed(() =>
autoRefreshEnabled.value ? "点击关闭自动刷新" : "点击开启自动刷新",
);
const todayStats = ref<{
requests: number;
tokens: number;
@@ -1499,55 +1464,17 @@ const dailyUsageTrendChartOptions = computed<ChartOptions<"line">>(() => {
};
});
async function refreshDashboardContent(options: DashboardLoadOptions = {}) {
if (dashboardRefreshPromise) {
return dashboardRefreshPromise;
}
autoRefreshLoading.value = true;
dashboardRefreshPromise = (async () => {
await Promise.all([loadDashboardData(options), loadDailyStats(options)]);
await nextTick();
updateAnnouncementsHeight();
updateTimelineLine();
})().finally(() => {
autoRefreshLoading.value = false;
dashboardRefreshPromise = null;
});
return dashboardRefreshPromise;
}
function startDashboardAutoRefresh() {
if (typeof window === "undefined") return;
stopDashboardAutoRefresh();
dashboardAutoRefreshTimer = window.setInterval(() => {
void refreshDashboardContent({ silent: true });
}, DASHBOARD_AUTO_REFRESH_INTERVAL_MS);
}
function stopDashboardAutoRefresh() {
if (dashboardAutoRefreshTimer !== null) {
clearInterval(dashboardAutoRefreshTimer);
dashboardAutoRefreshTimer = null;
}
}
function toggleDashboardAutoRefresh() {
autoRefreshEnabled.value = !autoRefreshEnabled.value;
if (autoRefreshEnabled.value) {
startDashboardAutoRefresh();
void refreshDashboardContent({ silent: true });
} else {
stopDashboardAutoRefresh();
}
}
onMounted(async () => {
checkScreenSize();
setupResizeObserver();
if (typeof window !== "undefined") {
window.addEventListener("resize", handleWindowResize);
}
await Promise.all([refreshDashboardContent(), loadAnnouncements()]);
await Promise.all([
loadDashboardData(),
loadDailyStats(),
loadAnnouncements(),
]);
await nextTick();
setupTimelineResizeObserver();
updateAnnouncementsHeight();
@@ -1555,7 +1482,6 @@ onMounted(async () => {
});
onBeforeUnmount(() => {
stopDashboardAutoRefresh();
if (typeof window !== "undefined") {
window.removeEventListener("resize", handleWindowResize);
}
@@ -1575,10 +1501,8 @@ onBeforeUnmount(() => {
dailyStatsRequestId += 1;
});
async function loadDashboardData(options: DashboardLoadOptions = {}) {
if (!options.silent) {
loading.value = true;
}
async function loadDashboardData() {
loading.value = true;
try {
const statsData = await dashboardApi.getStats({
timezone: dailyTimeRange.value.timezone,
@@ -1604,21 +1528,17 @@ async function loadDashboardData(options: DashboardLoadOptions = {}) {
userMonthlyCost.value = statsData.monthly_cost;
}
} finally {
if (!options.silent) {
loading.value = false;
}
loading.value = false;
}
}
async function loadDailyStats(options: DashboardLoadOptions = {}) {
async function loadDailyStats() {
if (dailyStatsLoadPromise) {
hasPendingDailyStatsLoad = true;
return dailyStatsLoadPromise;
}
const requestId = ++dailyStatsRequestId;
if (!options.silent) {
loadingDaily.value = true;
}
loadingDaily.value = true;
dailyStatsLoadPromise = (async () => {
try {
const response = await dashboardApi.getDailyStats(dailyTimeRange.value);
@@ -1630,7 +1550,7 @@ async function loadDailyStats(options: DashboardLoadOptions = {}) {
dailyStats.value = [];
providerSummary.value = [];
} finally {
if (requestId === dailyStatsRequestId && !options.silent) {
if (requestId === dailyStatsRequestId) {
loadingDaily.value = false;
}
}
+2 -2
View File
@@ -817,6 +817,7 @@ onMounted(async () => {
const heatmapPromise = loadHeatmapData().catch(err => {
log.error('加载热力图数据失败:', err)
})
const adminUsersPromise = loadAdminUsers()
await loadRecords(
{ page: currentPage.value, pageSize: pageSize.value },
@@ -825,8 +826,7 @@ onMounted(async () => {
)
void (async () => {
await refreshAdminAnalytics({ force: true, preserveOnFailure: false })
await heatmapPromise
await loadAdminUsers()
await Promise.all([heatmapPromise, adminUsersPromise])
})()
} else {
// 用户页面:loadStats 已包含记录加载,不需要单独调用 loadRecords
@@ -101,7 +101,6 @@ vi.mock('lucide-vue-next', async () => {
Clock: Icon,
Database: Icon,
Shuffle: Icon,
RefreshCw: Icon,
}
})
@@ -168,3 +167,27 @@ describe('Dashboard ordinary user wallet card', () => {
expect(root.textContent).toContain('套餐额度 $100.00 · 钱包余额 $10.00')
})
})
describe('Dashboard refresh controls', () => {
it('does not render or run automatic refresh', async () => {
vi.useFakeTimers()
dashboardApiMocks.getStats.mockResolvedValue({ stats: [] })
try {
const root = mountDashboard()
await settle()
expect(root.textContent).not.toContain('自动刷新')
expect(dashboardApiMocks.getStats).toHaveBeenCalledTimes(1)
expect(dashboardApiMocks.getDailyStats).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(60_000)
await settle()
expect(dashboardApiMocks.getStats).toHaveBeenCalledTimes(1)
expect(dashboardApiMocks.getDailyStats).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
})
@@ -0,0 +1,23 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const source = readFileSync(
resolve(process.cwd(), 'src/views/shared/Usage.vue'),
'utf8',
)
describe('admin usage initial loading', () => {
it('starts the user filter request before analytics completes', () => {
const mountedBlock = source
.split('onMounted(async () => {')[1]
?.split('// 处理时间范围变化')[0]
expect(mountedBlock).toBeTruthy()
expect(mountedBlock).toContain('const adminUsersPromise = loadAdminUsers()')
expect(mountedBlock).toContain('Promise.all([heatmapPromise, adminUsersPromise])')
expect(mountedBlock?.indexOf('const adminUsersPromise = loadAdminUsers()'))
.toBeLessThan(mountedBlock?.indexOf('await loadRecords(') ?? -1)
expect(mountedBlock).not.toContain('await loadAdminUsers()')
})
})
+2 -2
View File
@@ -812,12 +812,12 @@ function handleLanguageChange(value: string) {
}
onMounted(async () => {
await loadProfile()
const profilePromise = loadProfile()
await Promise.all([
loadPreferences(),
loadSessions(),
loadOAuthBindings(),
loadEmailConfigured(),
profilePromise.then(() => loadOAuthBindings()),
])
})
+34 -5
View File
@@ -781,6 +781,9 @@ const refundPage = ref(1)
const refundPageSize = ref(20)
const activeTab = ref('transactions')
const loadedTabs = new Set<string>()
const tabLoadPromises = new Map<string, Promise<void>>()
let refundEligibilityLoaded = false
let todayCostPollTimer: ReturnType<typeof setInterval> | null = null
const rechargeForm = reactive({
@@ -909,10 +912,6 @@ onMounted(async () => {
await Promise.all([
loadBalance(),
loadTransactions(),
loadTodayCost(),
loadOrders(),
loadRefunds(),
loadRefundEligibility(),
loadRechargeOptions(),
])
syncTodayCostPolling()
@@ -926,8 +925,9 @@ onBeforeUnmount(() => {
document.removeEventListener('visibilitychange', handleVisibilityChange)
})
watch(activeTab, () => {
watch(activeTab, (tab) => {
syncTodayCostPolling()
void loadActiveTab(tab)
})
watch(refundableOrders, () => {
@@ -961,6 +961,7 @@ async function loadTransactions() {
flowItems.value = resp.items
txTotal.value = resp.total
todayUsage.value = resp.today_entry
loadedTabs.add('transactions')
} catch (error) {
log.error('加载钱包流水失败:', error)
showError(parseApiError(error, '加载钱包流水失败'))
@@ -1009,6 +1010,7 @@ async function loadOrders() {
const resp = await walletApi.listRechargeOrders({ limit: orderPageSize.value, offset })
rechargeOrders.value = resp.items
orderTotal.value = resp.total
loadedTabs.add('orders')
syncRefundOrderSelection()
} catch (error) {
log.error('加载充值订单失败:', error)
@@ -1027,6 +1029,7 @@ async function loadRefundEligibility() {
.map(item => item.trim().toLowerCase())
.filter(Boolean)
)
refundEligibilityLoaded = true
syncRefundOrderSelection()
} catch (error) {
refundEligiblePaymentMethods.value = new Set()
@@ -1043,6 +1046,7 @@ async function loadRefunds() {
const resp = await walletApi.listRefunds({ limit: refundPageSize.value, offset })
refunds.value = resp.items
refundTotal.value = resp.total
loadedTabs.add('refunds')
} catch (error) {
log.error('加载退款记录失败:', error)
showError(parseApiError(error, '加载退款记录失败'))
@@ -1051,6 +1055,31 @@ async function loadRefunds() {
}
}
function loadActiveTab(tab: string): Promise<void> {
const tabIsLoaded = tab === 'refunds'
? loadedTabs.has('refunds') && loadedTabs.has('orders') && refundEligibilityLoaded
: loadedTabs.has(tab)
if (tabIsLoaded) return Promise.resolve()
const existing = tabLoadPromises.get(tab)
if (existing) return existing
const request = (async () => {
if (tab === 'orders') {
await loadOrders()
} else if (tab === 'refunds') {
const requests: Promise<void>[] = []
if (!loadedTabs.has('refunds')) requests.push(loadRefunds())
if (!refundEligibilityLoaded) requests.push(loadRefundEligibility())
if (!loadedTabs.has('orders')) requests.push(loadOrders())
await Promise.all(requests)
}
})().finally(() => {
if (tabLoadPromises.get(tab) === request) tabLoadPromises.delete(tab)
})
tabLoadPromises.set(tab, request)
return request
}
async function refreshRefundPanel() {
await Promise.all([loadRefunds(), loadRefundEligibility(), loadOrders()])
}