Merge remote-tracking branch 'origin/main' into codex/pool-key-bulk-management-20260714

# Conflicts:
#	apps/aether-gateway/src/handlers/admin/request/provider/tasks.rs
#	frontend/src/api/endpoints/pool.ts
This commit is contained in:
MMEXA
2026-07-16 23:43:04 +08:00
1257 changed files with 80521 additions and 35495 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
@@ -0,0 +1,186 @@
import { describe, expect, it } from 'vitest'
import {
buildModelsDevTieredPricing,
resolveModelsDevTieredPricing,
} from '@/api/models-dev-pricing'
describe('buildModelsDevTieredPricing', () => {
it('maps context bands and cache prices without flattening them', () => {
expect(buildModelsDevTieredPricing({
input: 5,
output: 30,
cache_read: 0.5,
cache_write: 6.25,
tiers: [{
input: 10,
output: 45,
cache_read: 1,
cache_write: 12.5,
tier: { type: 'context', size: 272_000 },
}],
})).toEqual({
tiers: [
{
up_to: 271_999,
input_price_per_1m: 5,
output_price_per_1m: 30,
cache_creation_price_per_1m: 6.25,
cache_read_price_per_1m: 0.5,
},
{
up_to: null,
input_price_per_1m: 10,
output_price_per_1m: 45,
cache_creation_price_per_1m: 12.5,
cache_read_price_per_1m: 1,
},
],
})
})
it('sorts multiple context boundaries into contiguous Aether bands', () => {
const cost = {
input: 1,
output: 2,
tiers: [
{ input: 5, output: 6, tier: { type: 'context' as const, size: 200_000 } },
{ input: 3, output: 4, tier: { type: 'context' as const, size: 100_000 } },
],
}
expect(buildModelsDevTieredPricing(cost)?.tiers).toEqual([
{ up_to: 99_999, input_price_per_1m: 1, output_price_per_1m: 2 },
{ up_to: 199_999, input_price_per_1m: 3, output_price_per_1m: 4 },
{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 6 },
])
expect(cost.tiers.map(tier => tier.tier.size)).toEqual([200_000, 100_000])
})
it('keeps flat token pricing as one unbounded band', () => {
expect(buildModelsDevTieredPricing({ input: 0, output: 0.1 })).toEqual({
tiers: [{ up_to: null, input_price_per_1m: 0, output_price_per_1m: 0.1 }],
})
})
it('omits an empty base band when context pricing starts at zero', () => {
expect(buildModelsDevTieredPricing({
input: 1,
output: 2,
tiers: [
{ input: 3, output: 4, tier: { type: 'context', size: 0 } },
{ input: 5, output: 6, tier: { type: 'context', size: 100_000 } },
],
})?.tiers).toEqual([
{ up_to: 99_999, input_price_per_1m: 3, output_price_per_1m: 4 },
{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 6 },
])
})
it.each([
{ input: -1, output: 2 },
{ input: 1, output: Number.POSITIVE_INFINITY },
{
input: 1,
output: 2,
tiers: [{ input: 3, output: 4, tier: { type: 'context', size: Number.MAX_SAFE_INTEGER + 1 } }],
},
{
input: 1,
output: 2,
tiers: [{ input: 3, output: 4, tier: { type: 'context', size: -1 } }],
},
{
input: 1,
output: 2,
tiers: [
{ input: 3, output: 4, tier: { type: 'context', size: 100 } },
{ input: 5, output: 6, tier: { type: 'context', size: 100 } },
],
},
])('fails closed for malformed structured pricing', (cost) => {
expect(buildModelsDevTieredPricing(cost)).toBeNull()
})
})
describe('resolveModelsDevTieredPricing', () => {
it('uses the GPT-5.5 Pro context tier declared by models.dev without inventing cache prices', () => {
expect(resolveModelsDevTieredPricing('openai', 'gpt-5.5-pro', {
input: 30,
output: 180,
tiers: [{
input: 60,
output: 270,
tier: { type: 'context', size: 272_000 },
}],
context_over_200k: {
input: 60,
output: 270,
},
})).toEqual({
tiers: [
{
up_to: 271_999,
input_price_per_1m: 30,
output_price_per_1m: 180,
},
{
up_to: null,
input_price_per_1m: 60,
output_price_per_1m: 270,
},
],
})
})
it.each([
'gpt-5.6-sol',
'gpt-5.6-terra',
'gpt-5.6-luna',
])('uses the fetched models.dev cost for OpenAI model %s', (modelId) => {
const fetchedCost = {
input: 7,
output: 11,
cache_read: 0.7,
cache_write: 8.75,
tiers: [{
input: 13,
output: 17,
cache_read: 1.3,
cache_write: 16.25,
tier: { type: 'context' as const, size: 123_000 },
}],
}
expect(resolveModelsDevTieredPricing('openai', modelId, fetchedCost)).toEqual({
tiers: [
{
up_to: 122_999,
input_price_per_1m: 7,
output_price_per_1m: 11,
cache_creation_price_per_1m: 8.75,
cache_read_price_per_1m: 0.7,
},
{
up_to: null,
input_price_per_1m: 13,
output_price_per_1m: 17,
cache_creation_price_per_1m: 16.25,
cache_read_price_per_1m: 1.3,
},
],
})
})
it('uses the same fetched-cost conversion for every provider and model identity', () => {
expect(resolveModelsDevTieredPricing('openai', 'other-model', {
input: 1,
output: 2,
tiers: [{ input: 3, output: 4, tier: { type: 'context', size: 272_000 } }],
})?.tiers.map(tier => tier.up_to)).toEqual([271_999, null])
})
it('does not synthesize pricing when the fetched cost is absent', () => {
expect(resolveModelsDevTieredPricing('openai', 'gpt-5.6-sol', undefined)).toBeNull()
})
})
+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
},
@@ -1388,13 +1414,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,
@@ -1404,26 +1433,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,
@@ -1433,17 +1466,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,
@@ -1453,7 +1489,7 @@ export const adminApi = {
})
return response.data
},
20 * 1000
options?.skipCache ? 0 : 20 * 1000
)
},
@@ -1543,17 +1579,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,
@@ -1561,7 +1600,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 事件,这里主动广播一次。
+16 -2
View File
@@ -154,6 +154,18 @@ export interface RequestSchedulingFailure {
no_upstream_attempt?: boolean | null
}
export interface RequestSettlementPricingSnapshot {
requested_processing_tier?: string | null
actual_processing_tier?: string | null
billing_processing_tier?: string | null
[key: string]: unknown
}
export interface RequestSettlementSnapshot {
pricing_snapshot?: RequestSettlementPricingSnapshot | null
[key: string]: unknown
}
export interface RequestDetail {
id: string // UUID
request_id: string
@@ -175,6 +187,7 @@ export interface RequestDetail {
target_model?: string | null // 映射后的目标模型名
reasoning_effort?: string | null
service_tier?: string | null
actual_service_tier?: string | null
tokens: {
input: number
output: number
@@ -262,6 +275,7 @@ export interface RequestDetail {
cache_creation_price_per_1m?: number
cache_read_price_per_1m?: number
price_per_request?: number
settlement_snapshot?: RequestSettlementSnapshot | null
} | null
// 阶梯计费信息
tiered_pricing?: {
@@ -399,7 +413,7 @@ export const dashboardApi = {
const response = await apiClient.get<DashboardStatsResponse>('/api/dashboard/stats', { params })
return response.data
},
10 * 1000
30 * 1000
)
},
@@ -462,7 +476,7 @@ export const dashboardApi = {
})
return response.data
},
20 * 1000
60 * 1000
)
},
+46 -8
View File
@@ -337,24 +337,28 @@ export interface PoolBatchAction {
| 'delete'
| 'clear_proxy'
| 'set_proxy'
| 'update_settings'
payload?: Record<string, unknown> | null
}
export interface PoolKeyBatchUpdatePatch {
api_formats?: string[]
auth_type_by_format?: Record<string, 'api_key' | 'bearer'> | null
allow_auth_channel_mismatch_formats?: string[] | null
rate_multipliers?: Record<string, number> | null
export interface PoolKeySharedSettingsPatch {
internal_priority?: number
global_priority_by_format?: Record<string, number> | null
rpm_limit?: number | null
concurrent_limit?: number | null
allowed_models?: AllowedModels
capabilities?: Record<string, boolean> | null
cache_ttl_minutes?: number
max_probe_interval_minutes?: number
is_active?: boolean
note?: string | null
}
export interface PoolKeyBatchUpdatePatch extends PoolKeySharedSettingsPatch {
api_formats?: string[]
auth_type_by_format?: Record<string, 'api_key' | 'bearer'> | null
allow_auth_channel_mismatch_formats?: string[] | null
rate_multipliers?: Record<string, number> | null
global_priority_by_format?: Record<string, number> | null
allowed_models?: AllowedModels
capabilities?: Record<string, boolean> | null
auto_fetch_models?: boolean
locked_models?: string[]
model_include_patterns?: string[]
@@ -382,6 +386,28 @@ export interface PoolKeyBatchUpdateResponse {
model_sync: PoolKeyBatchModelSyncResult | null
}
export interface PoolKeySettingsPatch extends PoolKeySharedSettingsPatch {
proxy_node_id?: string | null
}
export interface PoolBatchImportRequest {
keys: Array<{
name: string
api_key: string
auth_type: 'api_key' | 'bearer'
api_formats?: string[]
settings?: PoolKeySettingsPatch
}>
api_formats?: string[]
settings?: PoolKeySettingsPatch
}
export interface PoolBatchImportResult {
imported: number
skipped: number
errors: Array<{ index: number; reason: string }>
}
interface PoolReadOptions {
cacheTtlMs?: number
}
@@ -496,6 +522,18 @@ export async function batchUpdatePoolKeys(
return response.data
}
export async function batchImportPoolKeys(
providerId: string,
body: PoolBatchImportRequest,
): Promise<PoolBatchImportResult> {
const response = await client.post<PoolBatchImportResult>(
`/api/admin/pool/${providerId}/keys/batch-import`,
body,
{ timeout: POOL_BATCH_ACTION_TIMEOUT_MS },
)
return response.data
}
export interface BatchDeleteTaskStatus {
task_id: string
status: 'pending' | 'running' | 'completed' | 'failed'
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
API_FORMATS,
apiFormatPermissionCovers,
formatApiFormat,
formatApiFormatShort,
groupApiFormats,
@@ -14,6 +15,8 @@ describe('api format display helpers', () => {
expect(normalizeApiFormatAlias('CLAUDE_MESSAGES')).toBe(API_FORMATS.CLAUDE_MESSAGES)
expect(normalizeApiFormatAlias('OPENAI_RESPONSES')).toBe(API_FORMATS.OPENAI_RESPONSES)
expect(normalizeApiFormatAlias('OPENAI_RESPONSES_COMPACT')).toBe(API_FORMATS.OPENAI_RESPONSES_COMPACT)
expect(normalizeApiFormatAlias('OPENAI_SEARCH')).toBe(API_FORMATS.OPENAI_SEARCH)
expect(normalizeApiFormatAlias('SEARCH')).toBe(API_FORMATS.OPENAI_SEARCH)
expect(normalizeApiFormatAlias('GEMINI_GENERATE_CONTENT')).toBe(API_FORMATS.GEMINI_GENERATE_CONTENT)
expect(normalizeApiFormatAlias('OPENAI_EMBEDDING')).toBe(API_FORMATS.OPENAI_EMBEDDING)
expect(normalizeApiFormatAlias('OPENAI_RERANK')).toBe(API_FORMATS.OPENAI_RERANK)
@@ -33,6 +36,25 @@ describe('api format display helpers', () => {
expect(formatApiFormatShort(API_FORMATS.JINA_RERANK)).toBe('JR')
})
it('formats OpenAI Search as a first-class api format', () => {
expect(formatApiFormat(API_FORMATS.OPENAI_SEARCH)).toBe('OpenAI Search')
expect(formatApiFormatShort(API_FORMATS.OPENAI_SEARCH)).toBe('OS')
expect(sortApiFormats([
API_FORMATS.OPENAI_EMBEDDING,
API_FORMATS.OPENAI_SEARCH,
API_FORMATS.OPENAI_RESPONSES,
])).toEqual([
API_FORMATS.OPENAI_RESPONSES,
API_FORMATS.OPENAI_SEARCH,
API_FORMATS.OPENAI_EMBEDDING,
])
})
it('applies Responses to Search permissions in one direction', () => {
expect(apiFormatPermissionCovers('OPENAI_RESPONSES', 'openai:search')).toBe(true)
expect(apiFormatPermissionCovers('openai:search', 'openai:responses')).toBe(false)
})
it('formats embedding api format ids distinctly from chat formats', () => {
expect(formatApiFormat(API_FORMATS.GEMINI_INTERACTIONS)).toBe('Gemini Interactions')
expect(formatApiFormatShort(API_FORMATS.GEMINI_INTERACTIONS)).toBe('GI')
+32 -8
View File
@@ -6,6 +6,7 @@ export const API_FORMATS = {
OPENAI: 'openai:chat',
OPENAI_RESPONSES: 'openai:responses',
OPENAI_RESPONSES_COMPACT: 'openai:responses:compact',
OPENAI_SEARCH: 'openai:search',
OPENAI_IMAGE: 'openai:image',
OPENAI_VIDEO: 'openai:video',
OPENAI_EMBEDDING: 'openai:embedding',
@@ -30,6 +31,7 @@ export const API_FORMAT_LABELS: Record<string, string> = {
[API_FORMATS.OPENAI]: 'OpenAI Chat',
[API_FORMATS.OPENAI_RESPONSES]: 'OpenAI Responses',
[API_FORMATS.OPENAI_RESPONSES_COMPACT]: 'OpenAI Responses Compact',
[API_FORMATS.OPENAI_SEARCH]: 'OpenAI Search',
[API_FORMATS.OPENAI_IMAGE]: 'OpenAI Image',
[API_FORMATS.OPENAI_VIDEO]: 'OpenAI Video',
[API_FORMATS.OPENAI_EMBEDDING]: 'OpenAI Embedding',
@@ -48,6 +50,7 @@ export const API_FORMAT_LABELS: Record<string, string> = {
OPENAI: 'OpenAI Chat',
OPENAI_RESPONSES: 'OpenAI Responses',
OPENAI_RESPONSES_COMPACT: 'OpenAI Responses Compact',
OPENAI_SEARCH: 'OpenAI Search',
OPENAI_IMAGE: 'OpenAI Image',
OPENAI_VIDEO: 'OpenAI Video',
OPENAI_EMBEDDING: 'OpenAI Embedding',
@@ -69,6 +72,7 @@ export const API_FORMAT_SHORT: Record<string, string> = {
[API_FORMATS.OPENAI]: 'O',
[API_FORMATS.OPENAI_RESPONSES]: 'OR',
[API_FORMATS.OPENAI_RESPONSES_COMPACT]: 'ORC',
[API_FORMATS.OPENAI_SEARCH]: 'OS',
[API_FORMATS.OPENAI_IMAGE]: 'OI',
[API_FORMATS.OPENAI_VIDEO]: 'OV',
[API_FORMATS.OPENAI_EMBEDDING]: 'OE',
@@ -86,6 +90,7 @@ export const API_FORMAT_SHORT: Record<string, string> = {
OPENAI: 'O',
OPENAI_RESPONSES: 'OR',
OPENAI_RESPONSES_COMPACT: 'ORC',
OPENAI_SEARCH: 'OS',
OPENAI_IMAGE: 'OI',
OPENAI_VIDEO: 'OV',
OPENAI_EMBEDDING: 'OE',
@@ -109,6 +114,7 @@ export const API_FORMAT_ORDER: string[] = [
API_FORMATS.OPENAI,
API_FORMATS.OPENAI_RESPONSES,
API_FORMATS.OPENAI_RESPONSES_COMPACT,
API_FORMATS.OPENAI_SEARCH,
API_FORMATS.OPENAI_EMBEDDING,
API_FORMATS.OPENAI_RERANK,
API_FORMATS.OPENAI_IMAGE,
@@ -140,6 +146,7 @@ export const API_FORMAT_KIND_LABELS: Record<string, string> = {
chat: 'Chat',
responses: 'Responses',
'responses:compact': 'Responses Compact',
search: 'Search',
messages: 'Messages',
generate_content: 'Generate Content',
interactions: 'Interactions',
@@ -174,6 +181,9 @@ export function normalizeApiFormatAlias(format: string | null | undefined): stri
return API_FORMATS.OPENAI_RESPONSES
case 'OPENAI_RESPONSES_COMPACT':
return API_FORMATS.OPENAI_RESPONSES_COMPACT
case 'OPENAI_SEARCH':
case 'SEARCH':
return API_FORMATS.OPENAI_SEARCH
case 'OPENAI_IMAGE':
return API_FORMATS.OPENAI_IMAGE
case 'OPENAI_VIDEO':
@@ -216,6 +226,18 @@ export function normalizeApiFormatAlias(format: string | null | undefined): stri
}
}
export function apiFormatPermissionCovers(
allowedFormat: string | null | undefined,
requestedFormat: string | null | undefined,
): boolean {
const allowed = normalizeApiFormatAlias(allowedFormat)
const requested = normalizeApiFormatAlias(requestedFormat)
return Boolean(allowed)
&& Boolean(requested)
&& (allowed === requested
|| (allowed === API_FORMATS.OPENAI_RESPONSES && requested === API_FORMATS.OPENAI_SEARCH))
}
// 工具函数:按 family 分组并排序 API 格式数组
export interface ApiFormatGroup {
family: string
@@ -272,14 +294,16 @@ export function formatApiFormatShort(format: string | null | undefined): string
// 工具函数:按标准顺序排序 API 格式数组
export function sortApiFormats(formats: string[]): string[] {
return [...formats].sort((a, b) => {
const aIdx = API_FORMAT_ORDER.indexOf(normalizeApiFormatAlias(a))
const bIdx = API_FORMAT_ORDER.indexOf(normalizeApiFormatAlias(b))
if (aIdx === -1 && bIdx === -1) return 0
if (aIdx === -1) return 1
if (bIdx === -1) return -1
return aIdx - bIdx
})
return [...formats].sort(compareApiFormats)
}
export function compareApiFormats(a: string, b: string): number {
const aIdx = API_FORMAT_ORDER.indexOf(normalizeApiFormatAlias(a))
const bIdx = API_FORMAT_ORDER.indexOf(normalizeApiFormatAlias(b))
if (aIdx === -1 && bIdx === -1) return 0
if (aIdx === -1) return 1
if (bIdx === -1) return -1
return aIdx - bIdx
}
// openai family 格式只支持 bearer(Authorization header),不允许覆盖认证方式
+22 -2
View File
@@ -6,6 +6,7 @@ import type { ProviderModelMapping } from './provider'
export interface CacheTTLPricing {
ttl_minutes: number
cache_creation_price_per_1m: number
[key: string]: unknown
}
/** 单个价格阶梯配置 */
@@ -16,22 +17,39 @@ export interface PricingTier {
cache_creation_price_per_1m?: number
cache_read_price_per_1m?: number
cache_ttl_pricing?: CacheTTLPricing[]
[key: string]: unknown
}
export type ImageOutputQuality = 'low' | 'medium' | 'high'
export interface ImageOutputQualityPricing extends Partial<Record<ImageOutputQuality, number>> {
[quality: string]: unknown
}
export interface ImageOutputPriceRange {
up_to_pixels: number | null
prices: Partial<Record<ImageOutputQuality, number>>
prices: ImageOutputQualityPricing
label?: string | null
[key: string]: unknown
}
/** 按处理层级覆盖的费率配置。允许图像或未来计费字段独立扩展。 */
export interface ProcessingTierPricingConfig {
tiers?: PricingTier[]
image_output_prices?: Record<string, ImageOutputQualityPricing> | null
image_output_price_default?: number | null
image_output_price_ranges?: ImageOutputPriceRange[] | null
[key: string]: unknown
}
/** 阶梯计费配置 */
export interface TieredPricingConfig {
tiers: PricingTier[]
image_output_prices?: Record<string, Record<string, number>> | null
image_output_prices?: Record<string, ImageOutputQualityPricing> | null
image_output_price_default?: number | null
image_output_price_ranges?: ImageOutputPriceRange[] | null
processing_tiers?: Record<string, ProcessingTierPricingConfig> | null
[key: string]: unknown
}
export interface Model {
@@ -270,6 +288,8 @@ export interface UpstreamModel {
id: string
owned_by?: string
display_name?: string
visibility?: string
supported_in_api?: boolean
api_formats: string[] // 该模型支持的所有 API 格式(后端保证返回数组)
model_test_capabilities?: ModelTestCapabilities | null
}
+2
View File
@@ -56,6 +56,7 @@ export interface UsageRecordDetail {
model: string
reasoning_effort?: string | null
service_tier?: string | null
actual_service_tier?: string | null
input_tokens: number
effective_input_tokens?: number
output_tokens: number
@@ -369,6 +370,7 @@ export const meApi = {
target_model?: string | null
reasoning_effort?: string | null
service_tier?: string | null
actual_service_tier?: string | null
}>
}> {
const params = ids ? { ids } : {}
+101
View File
@@ -0,0 +1,101 @@
import type { PricingTier, TieredPricingConfig } from './endpoints/types'
export interface ModelsDevTokenCost {
input: number
output: number
reasoning?: number
cache_read?: number
cache_write?: number
input_audio?: number
output_audio?: number
}
export interface ModelsDevCostTier extends ModelsDevTokenCost {
tier: {
type: 'context'
size: number
}
}
export interface ModelsDevCost extends ModelsDevTokenCost {
tiers?: ModelsDevCostTier[]
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isPrice(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value >= 0
}
function parseTokenPrices(value: unknown): Omit<PricingTier, 'up_to'> | null {
if (!isRecord(value) || !isPrice(value.input) || !isPrice(value.output)) return null
if (value.cache_write !== undefined && !isPrice(value.cache_write)) return null
if (value.cache_read !== undefined && !isPrice(value.cache_read)) return null
return {
input_price_per_1m: value.input,
output_price_per_1m: value.output,
...(value.cache_write === undefined
? {}
: { cache_creation_price_per_1m: value.cache_write }),
...(value.cache_read === undefined
? {}
: { cache_read_price_per_1m: value.cache_read }),
}
}
function parseContextTier(value: unknown): { size: number; prices: Omit<PricingTier, 'up_to'> } | null {
if (!isRecord(value) || !isRecord(value.tier)) return null
if (
value.tier.type !== 'context'
|| typeof value.tier.size !== 'number'
|| !Number.isSafeInteger(value.tier.size)
|| value.tier.size < 0
) {
return null
}
const prices = parseTokenPrices(value)
return prices ? { size: value.tier.size, prices } : null
}
export function buildModelsDevTieredPricing(cost: unknown): TieredPricingConfig | null {
const basePrices = parseTokenPrices(cost)
if (!basePrices || !isRecord(cost)) return null
const rawTiers = cost.tiers
if (rawTiers !== undefined && !Array.isArray(rawTiers)) return null
const contextTiers = (rawTiers ?? []).map(parseContextTier)
if (contextTiers.some(tier => tier === null)) return null
const sortedTiers = contextTiers
.filter((tier): tier is NonNullable<typeof tier> => tier !== null)
.sort((a, b) => a.size - b.size)
if (sortedTiers.some((tier, index) => index > 0 && tier.size === sortedTiers[index - 1].size)) {
return null
}
const tiers: PricingTier[] = []
if (sortedTiers[0]?.size !== 0) {
tiers.push({
...basePrices,
up_to: sortedTiers[0] ? sortedTiers[0].size - 1 : null,
})
}
tiers.push(...sortedTiers.map((tier, index) => ({
...tier.prices,
up_to: sortedTiers[index + 1] ? sortedTiers[index + 1].size - 1 : null,
})))
return { tiers }
}
export function resolveModelsDevTieredPricing(
_providerId: string,
_modelId: string,
cost: unknown,
): TieredPricingConfig | null {
// Provider/model identities must never inject local prices over the fetched catalog.
return buildModelsDevTieredPricing(cost)
}
+13 -9
View File
@@ -4,19 +4,19 @@
*/
import api from './client'
import {
resolveModelsDevTieredPricing,
type ModelsDevCost,
} from './models-dev-pricing'
import type { TieredPricingConfig } from './endpoints/types'
export type { ModelsDevCost, ModelsDevCostTier, ModelsDevTokenCost } from './models-dev-pricing'
// 缓存配置
const CACHE_KEY = 'models_dev_cache'
const CACHE_DURATION = 15 * 60 * 1000 // 15 分钟
// Models.dev API 数据结构
export interface ModelsDevCost {
input?: number
output?: number
reasoning?: number
cache_read?: number
}
export interface ModelsDevLimit {
context?: number
output?: number
@@ -64,6 +64,7 @@ export interface ModelsDevModelItem {
family?: string
inputPrice?: number
outputPrice?: number
tieredPricing?: TieredPricingConfig
contextLimit?: number
outputLimit?: number
supportsVision?: boolean
@@ -165,14 +166,17 @@ export async function getModelsDevList(officialOnly: boolean = true): Promise<Mo
if (!provider.models) continue
for (const [modelId, model] of Object.entries(provider.models)) {
const tieredPricing = resolveModelsDevTieredPricing(providerId, modelId, model.cost)
const basePricingTier = tieredPricing?.tiers[0]
items.push({
providerId,
providerName: provider.name,
modelId,
modelName: model.name || modelId,
family: model.family,
inputPrice: model.cost?.input,
outputPrice: model.cost?.output,
inputPrice: basePricingTier?.input_price_per_1m ?? model.cost?.input,
outputPrice: basePricingTier?.output_price_per_1m ?? model.cost?.output,
tieredPricing: tieredPricing ?? undefined,
contextLimit: model.limit?.context,
outputLimit: model.limit?.output,
supportsVision: model.input?.includes('image'),
+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),
})
},
+24
View File
@@ -332,10 +332,22 @@ export interface GatewayUsageRuntimeMetrics {
workerProcessFailuresTotal: number | null
workerReadFailuresTotal: number | null
workerReclaimFailuresTotal: number | null
terminalSubmissionLimit: number | null
terminalSubmissionInFlight: number | null
terminalSubmissionMaxInFlight: number | null
terminalSubmissionRejectedTotal: number | null
terminalEnqueueInFlight: number | null
terminalEnqueueDeferredTotal: number | null
terminalEnqueueDeferredDirectWriteTotal: number | null
terminalEnqueueDeferredDroppedTotal: number | null
terminalEnqueueDeferredRetryTotal: number | null
terminalEnqueueFailedTotal: number | null
terminalDirectFallbackLimit: number | null
terminalDirectFallbackInFlight: number | null
terminalDirectFallbackMaxInFlight: number | null
terminalDirectFallbackSucceededTotal: number | null
terminalDirectFallbackFailedTotal: number | null
terminalDirectFallbackRejectedTotal: number | null
lifecycleEnqueueInFlight: number | null
lifecycleEnqueueDeferredTotal: number | null
lifecycleEnqueueDeferredDroppedTotal: number | null
@@ -673,10 +685,22 @@ function buildUsageRuntimeMetrics(samples: PrometheusSample[]): GatewayUsageRunt
workerProcessFailuresTotal: findMetricValueNumber(samples, 'usage_runtime_queue_worker_process_failures_total'),
workerReadFailuresTotal: findMetricValueNumber(samples, 'usage_runtime_queue_worker_read_failures_total'),
workerReclaimFailuresTotal: findMetricValueNumber(samples, 'usage_runtime_queue_worker_reclaim_failures_total'),
terminalSubmissionLimit: findMetricValueNumber(samples, 'usage_runtime_terminal_submission_limit'),
terminalSubmissionInFlight: findMetricValueNumber(samples, 'usage_runtime_terminal_submission_in_flight'),
terminalSubmissionMaxInFlight: findMetricValueNumber(samples, 'usage_runtime_terminal_submission_max_in_flight'),
terminalSubmissionRejectedTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_submission_rejected_total'),
terminalEnqueueInFlight: findMetricValueNumber(samples, 'usage_runtime_terminal_enqueue_in_flight'),
terminalEnqueueDeferredTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_enqueue_deferred_total'),
terminalEnqueueDeferredDirectWriteTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_enqueue_deferred_direct_write_total'),
terminalEnqueueDeferredDroppedTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_enqueue_deferred_dropped_total'),
terminalEnqueueDeferredRetryTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_enqueue_deferred_retry_total'),
terminalEnqueueFailedTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_enqueue_failed_total'),
terminalDirectFallbackLimit: findMetricValueNumber(samples, 'usage_runtime_terminal_direct_fallback_limit'),
terminalDirectFallbackInFlight: findMetricValueNumber(samples, 'usage_runtime_terminal_direct_fallback_in_flight'),
terminalDirectFallbackMaxInFlight: findMetricValueNumber(samples, 'usage_runtime_terminal_direct_fallback_max_in_flight'),
terminalDirectFallbackSucceededTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_direct_fallback_succeeded_total'),
terminalDirectFallbackFailedTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_direct_fallback_failed_total'),
terminalDirectFallbackRejectedTotal: findMetricValueNumber(samples, 'usage_runtime_terminal_direct_fallback_rejected_total'),
lifecycleEnqueueInFlight: findMetricValueNumber(samples, 'usage_runtime_lifecycle_enqueue_in_flight'),
lifecycleEnqueueDeferredTotal: findMetricValueNumber(samples, 'usage_runtime_lifecycle_enqueue_deferred_total'),
lifecycleEnqueueDeferredDroppedTotal: findMetricValueNumber(samples, 'usage_runtime_lifecycle_enqueue_deferred_dropped_total'),
+4
View File
@@ -16,6 +16,7 @@ export interface UsageRecord {
model: string
reasoning_effort?: string | null
service_tier?: string | null
actual_service_tier?: string | null
input_tokens: number
effective_input_tokens?: number
output_tokens: number
@@ -43,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
@@ -567,6 +570,7 @@ export const usageApi = {
target_model?: string | null
reasoning_effort?: string | null
service_tier?: string | null
actual_service_tier?: string | null
image_progress?: ImageProgress | null
}>
}> {
+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)
+6 -6
View File
@@ -22,7 +22,7 @@
/>
</Transition>
<div class="relative flex h-full items-end justify-center overflow-hidden px-3 py-4 text-center sm:items-center sm:p-0 pointer-events-none">
<div class="relative flex h-full items-end justify-center overflow-hidden text-center sm:items-center sm:p-0 pointer-events-none">
<!-- 对话框内容 -->
<Transition
enter-active-class="duration-300 ease-out"
@@ -34,7 +34,7 @@
>
<div
v-if="isOpen"
class="relative flex max-h-[calc(100dvh-2rem)] w-full transform flex-col overflow-hidden rounded-lg border border-border bg-background text-left shadow-2xl transition-all pointer-events-auto sm:my-8 sm:w-full sm:max-h-[calc(100dvh-4rem)]"
class="relative flex max-h-[100dvh] w-full transform flex-col overflow-hidden rounded-t-xl border border-x-0 border-b-0 border-border bg-background text-left shadow-2xl transition-all pointer-events-auto sm:my-8 sm:w-full sm:max-h-[calc(100dvh-4rem)] sm:rounded-lg sm:border"
:style="{ zIndex: contentZIndex }"
:class="maxWidthClass"
@click.stop
@@ -43,7 +43,7 @@
<slot name="header">
<div
v-if="title"
class="shrink-0 border-b border-border px-4 py-4 sm:px-6"
class="shrink-0 border-b border-border px-4 pb-3 pt-4 sm:px-6 sm:py-4"
>
<div class="flex items-center gap-3">
<div
@@ -57,12 +57,12 @@
/>
</div>
<div class="flex-1 min-w-0">
<h3 class="text-lg font-semibold text-foreground leading-tight">
<h3 class="text-balance text-base font-semibold leading-tight text-foreground sm:text-lg">
{{ title }}
</h3>
<p
v-if="description"
class="text-xs text-muted-foreground"
class="mt-0.5 text-pretty text-xs leading-4 text-muted-foreground"
>
{{ description }}
</p>
@@ -80,7 +80,7 @@
<!-- Footer 区域:如果有 footer 插槽,自动添加样式 -->
<div
v-if="slots.footer"
class="shrink-0 border-t border-border bg-muted/10 px-4 py-4 sm:px-6 flex flex-row-reverse gap-3"
class="flex shrink-0 flex-col-reverse items-stretch gap-2 border-t border-border bg-background/95 px-4 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-3 backdrop-blur-sm [&>button]:w-full sm:flex-row-reverse sm:items-center sm:gap-3 sm:bg-muted/10 sm:px-6 sm:py-4 sm:[&>button]:w-auto"
>
<slot name="footer" />
</div>
@@ -394,6 +394,7 @@
ref="tieredPricingEditorRef"
v-model="tieredPricing"
class="mt-3"
:auto-fill-missing-cache-prices="autoFillMissingCachePrices"
:show-token-pricing="billingMode === 'token'"
:show-image-pricing="isImageGenerationEnabled"
:show-image-editor="billingMode === 'image'"
@@ -601,7 +602,9 @@ import {
EMBEDDING_API_FORMATS,
buildGlobalModelCreatePayload,
buildGlobalModelUpdatePayload,
cloneTieredPricingConfig,
} from './global-model-form-helpers'
import { tieredPricingHasImageOutputPricing } from '../utils/tiered-pricing'
const props = defineProps<{
open: boolean
@@ -778,6 +781,7 @@ function enterManualEntryMode() {
}
function reopenPresetPanel() {
clearSelection()
presetPanelCollapsed.value = false
}
@@ -1066,8 +1070,6 @@ function selectModel(model: ModelsDevModelItem) {
imageGenerationExplicitOverride.value = null
selectedModel.value = model
expandedProvider.value = model.providerId
form.value.name = model.modelId
form.value.display_name = model.modelName
// 构建 config
const config: Record<string, unknown> = {
@@ -1087,11 +1089,16 @@ function selectModel(model: ModelsDevModelItem) {
if (model.releaseDate) config.release_date = model.releaseDate
if (model.inputModalities?.length) config.input_modalities = model.inputModalities
if (model.outputModalities?.length) config.output_modalities = model.outputModalities
form.value.config = config
const supportedCapabilities = new Set<string>()
if (model.supportsEmbedding) supportedCapabilities.add('embedding')
if (model.outputModalities?.includes('image')) supportedCapabilities.add('image_generation')
form.value.supported_capabilities = [...supportedCapabilities]
form.value = {
...defaultForm(),
name: model.modelId,
display_name: model.modelName,
config,
supported_capabilities: [...supportedCapabilities],
}
if (model.supportsEmbedding) {
setEmbeddingEnabled(true)
}
@@ -1104,17 +1111,9 @@ function selectModel(model: ModelsDevModelItem) {
}
loadVideoPricingFromConfig()
if (model.inputPrice !== undefined || model.outputPrice !== undefined) {
tieredPricing.value = {
tiers: [{
up_to: null,
input_price_per_1m: model.inputPrice || 0,
output_price_per_1m: model.outputPrice || 0,
}]
}
} else {
tieredPricing.value = null
}
tieredPricing.value = model.tieredPricing
? cloneTieredPricingConfig(model.tieredPricing)
: null
presetPanelCollapsed.value = true
scrollToBasicInformation()
@@ -1126,6 +1125,7 @@ function clearSelection() {
selectedModel.value = null
form.value = defaultForm()
tieredPricing.value = null
videoResolutionPrices.value = []
billingMode.value = 'token'
}
@@ -1198,12 +1198,22 @@ const { isEditMode, handleDialogUpdate, handleCancel } = useFormDialog({
resetForm,
})
const autoFillMissingCachePrices = computed(() => (
!isEditMode.value && selectedModel.value === null
))
async function handleSubmit() {
if (!form.value.name || !form.value.display_name) {
showError('请填写模型ID和名称')
return
}
const pricingValidationError = tieredPricingEditorRef.value?.getValidationError()
if (pricingValidationError) {
showError(pricingValidationError, '价格配置错误')
return
}
const finalTieredPricing = tieredPricingEditorRef.value?.getFinalPricing() ?? tieredPricing.value
if (!finalTieredPricing?.tiers?.length) {
@@ -1244,28 +1254,4 @@ async function handleSubmit() {
}
}
function tieredPricingHasImageOutputPricing(pricing: TieredPricingConfig | null | undefined): boolean {
if (!pricing) return false
if (toFinitePrice(pricing.image_output_price_default) !== null) return true
if (Object.values(pricing.image_output_prices || {}).some((prices) => {
if (!prices || typeof prices !== 'object') return false
return Object.values(prices).some((price) => toFinitePrice(price) !== null)
})) return true
return (pricing.image_output_price_ranges || []).some((range) => {
if (!range || typeof range !== 'object') return false
const prices = range.prices && typeof range.prices === 'object'
? range.prices
: range as Record<string, unknown>
return Object.values(prices).some((price) => toFinitePrice(price) !== null)
})
}
function toFinitePrice(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : null
}
return null
}
</script>
@@ -137,6 +137,7 @@
</p>
</div>
</div>
</div>
<!-- 默认定价 -->
@@ -145,6 +146,8 @@
默认定价
</h4>
<ProcessingTierPricingSummary :pricing="model.default_tiered_pricing" />
<!-- 图片输出计费 -->
<div
v-if="hasImagePricing"
@@ -556,6 +559,7 @@ import TableHead from '@/components/ui/table-head.vue'
import TableCell from '@/components/ui/table-cell.vue'
import RoutingTab from './RoutingTab.vue'
import ModelMappingsTab from './ModelMappingsTab.vue'
import ProcessingTierPricingSummary from './ProcessingTierPricingSummary.vue'
import { sortResolutionEntries } from '@/utils/form'
import { parseApiError } from '@/utils/errorParser'
import { formatCompactNumber, formatTokens } from '@/utils/format'
@@ -0,0 +1,390 @@
<template>
<div
v-if="processingTierEntries.length > 0 && activeEntry"
class="space-y-3 border-t border-border/60 pt-4"
data-testid="processing-tier-pricing-summary"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<div>
<h5 class="text-sm font-medium text-foreground">
处理层级定价
</h5>
<p class="text-xs text-muted-foreground">
{{ activeEntry.label }}
</p>
</div>
<div
class="flex max-w-full flex-wrap gap-1"
role="group"
aria-label="处理层级定价"
>
<Button
v-for="entry in processingTierEntries"
:key="entry.key"
type="button"
size="sm"
:variant="activeTierKey === entry.key ? 'secondary' : 'ghost'"
class="h-8 max-w-full px-2.5"
:aria-pressed="activeTierKey === entry.key"
:data-processing-tier="entry.key"
@click="activeTierKey = entry.key"
>
<span class="truncate">{{ entry.label }}</span>
</Button>
</div>
</div>
<div
v-if="activeTokenTiers.length > 0"
class="overflow-x-auto rounded-md border"
>
<Table class="min-w-[680px]">
<TableHeader>
<TableRow class="bg-muted/30">
<TableHead class="h-9 text-xs">
Token 区间
</TableHead>
<TableHead class="h-9 text-right text-xs">
输入 ($/M)
</TableHead>
<TableHead class="h-9 text-right text-xs">
输出 ($/M)
</TableHead>
<TableHead class="h-9 text-right text-xs">
缓存创建
</TableHead>
<TableHead class="h-9 text-right text-xs">
缓存读取
</TableHead>
<TableHead class="h-9 text-right text-xs">
1h 创建
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow
v-for="(tier, index) in activeTokenTiers"
:key="index"
class="text-xs"
data-testid="processing-token-tier-row"
>
<TableCell class="py-2 whitespace-nowrap">
{{ formatTokenRange(activeTokenTiers, index) }}
</TableCell>
<TableCell class="py-2 text-right font-mono">
{{ formatPrice(tier.input_price_per_1m) }}
</TableCell>
<TableCell class="py-2 text-right font-mono">
{{ formatPrice(tier.output_price_per_1m) }}
</TableCell>
<TableCell class="py-2 text-right font-mono text-muted-foreground">
{{ formatPrice(tier.cache_creation_price_per_1m) }}
</TableCell>
<TableCell class="py-2 text-right font-mono text-muted-foreground">
{{ formatPrice(tier.cache_read_price_per_1m) }}
</TableCell>
<TableCell class="py-2 text-right font-mono text-muted-foreground">
{{ formatPrice(cacheCreationPriceForTtl(tier, 60)) }}
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
<div
v-if="hasActiveImagePricing"
class="space-y-2"
data-testid="processing-image-pricing"
>
<div class="flex flex-wrap items-center justify-between gap-2 text-xs">
<span class="font-medium text-foreground">图片输出</span>
<span
v-if="activeImageDefaultPrice !== null"
class="font-mono text-muted-foreground"
>默认 {{ formatPrice(activeImageDefaultPrice) }}/张</span>
</div>
<div
v-if="activeImageRows.length > 0"
class="overflow-x-auto rounded-md border"
>
<Table :class="imageTableMinWidthClass">
<TableHeader>
<TableRow class="bg-muted/30">
<TableHead class="h-9 text-xs">
分辨率
</TableHead>
<TableHead
v-for="quality in activeImageQualities"
:key="quality"
class="h-9 text-right text-xs"
>
{{ quality }}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow
v-for="row in activeImageRows"
:key="row.size"
class="text-xs"
>
<TableCell class="py-2 font-mono whitespace-nowrap">
{{ formatImageSize(row.size) }}
</TableCell>
<TableCell
v-for="quality in activeImageQualities"
:key="`${row.size}-${quality}`"
class="py-2 text-right font-mono"
>
{{ formatPrice(row.prices[quality]) }}
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
<div
v-if="activeImageRangeRows.length > 0"
class="overflow-x-auto rounded-md border"
>
<Table :class="imageTableMinWidthClass">
<TableHeader>
<TableRow class="bg-muted/30">
<TableHead class="h-9 text-xs">
像素区间
</TableHead>
<TableHead
v-for="quality in activeImageQualities"
:key="quality"
class="h-9 text-right text-xs"
>
{{ quality }}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow
v-for="(row, index) in activeImageRangeRows"
:key="`${row.upToPixels ?? 'unbounded'}-${index}`"
class="text-xs"
>
<TableCell class="py-2 whitespace-nowrap">
{{ row.label || formatPixelRange(activeImageRangeRows, index) }}
</TableCell>
<TableCell
v-for="quality in activeImageQualities"
:key="`${index}-${quality}`"
class="py-2 text-right font-mono"
>
{{ formatPrice(row.prices[quality]) }}
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import Button from '@/components/ui/button.vue'
import Table from '@/components/ui/table.vue'
import TableBody from '@/components/ui/table-body.vue'
import TableCell from '@/components/ui/table-cell.vue'
import TableHead from '@/components/ui/table-head.vue'
import TableHeader from '@/components/ui/table-header.vue'
import TableRow from '@/components/ui/table-row.vue'
import { formatTokens } from '@/utils/format'
import type {
PricingTier,
ProcessingTierPricingConfig,
TieredPricingConfig,
} from '@/api/endpoints/types'
import { comparePricingUpperBounds } from '@/features/models/utils/tiered-pricing'
type ProcessingTierEntry = {
key: string
label: string
config: ProcessingTierPricingConfig
}
type ImagePriceRow = {
size: string
prices: Record<string, number>
}
type ImageRangeRow = {
upToPixels: number | null
label: string | null
prices: Record<string, number>
}
const props = defineProps<{
pricing: TieredPricingConfig | null | undefined
}>()
const KNOWN_PROCESSING_TIERS = [
{ key: 'priority', label: 'Priority' },
{ key: 'flex', label: 'Flex' },
{ key: 'batch', label: 'Batch' },
] as const
const KNOWN_IMAGE_QUALITIES = ['low', 'medium', 'high'] as const
const activeTierKey = ref('')
const processingTierEntries = computed<ProcessingTierEntry[]>(() => {
const processingTiers = props.pricing?.processing_tiers
if (!isRecord(processingTiers)) return []
const labels = new Map(KNOWN_PROCESSING_TIERS.map(entry => [entry.key, entry.label]))
const order = new Map(KNOWN_PROCESSING_TIERS.map((entry, index) => [entry.key, index]))
return Object.entries(processingTiers)
.filter((entry): entry is [string, ProcessingTierPricingConfig] => (
isRecord(entry[1]) && processingPricingHasFacts(entry[1])
))
.sort(([left], [right]) => {
const leftOrder = order.get(left) ?? KNOWN_PROCESSING_TIERS.length
const rightOrder = order.get(right) ?? KNOWN_PROCESSING_TIERS.length
return leftOrder - rightOrder || left.localeCompare(right)
})
.map(([key, config]) => ({ key, label: labels.get(key) ?? key, config }))
})
watch(processingTierEntries, (entries) => {
if (!entries.some(entry => entry.key === activeTierKey.value)) {
activeTierKey.value = entries[0]?.key ?? ''
}
}, { immediate: true })
const activeEntry = computed(() =>
processingTierEntries.value.find(entry => entry.key === activeTierKey.value) ?? null,
)
const activeTokenTiers = computed<PricingTier[]>(() =>
Array.isArray(activeEntry.value?.config.tiers)
? activeEntry.value.config.tiers.filter(isRecord) as PricingTier[]
: [],
)
const activeImageDefaultPrice = computed(() =>
toFiniteNumber(activeEntry.value?.config.image_output_price_default),
)
const activeImageRows = computed<ImagePriceRow[]>(() => {
const prices = activeEntry.value?.config.image_output_prices
if (!isRecord(prices)) return []
return Object.entries(prices)
.filter((entry): entry is [string, Record<string, unknown>] => isRecord(entry[1]))
.map(([size, values]) => ({ size, prices: finitePriceRecord(values) }))
.filter(row => Object.keys(row.prices).length > 0)
.sort((left, right) => imageSizeArea(left.size) - imageSizeArea(right.size)
|| left.size.localeCompare(right.size))
})
const activeImageRangeRows = computed<ImageRangeRow[]>(() => {
const ranges = activeEntry.value?.config.image_output_price_ranges
if (!Array.isArray(ranges)) return []
return ranges
.filter(isRecord)
.map(range => ({
upToPixels: range.up_to_pixels === null ? null : toFiniteNumber(range.up_to_pixels),
label: typeof range.label === 'string' && range.label.trim() ? range.label.trim() : null,
prices: isRecord(range.prices) ? finitePriceRecord(range.prices) : {},
}))
.filter(row => Object.keys(row.prices).length > 0)
.sort((left, right) => comparePricingUpperBounds(left.upToPixels, right.upToPixels))
})
const activeImageQualities = computed(() => {
const present = new Set<string>()
for (const row of [...activeImageRows.value, ...activeImageRangeRows.value]) {
Object.keys(row.prices).forEach(quality => present.add(quality))
}
const known = KNOWN_IMAGE_QUALITIES.filter(quality => present.has(quality))
const custom = [...present]
.filter(quality => !KNOWN_IMAGE_QUALITIES.includes(quality as typeof KNOWN_IMAGE_QUALITIES[number]))
.sort((left, right) => left.localeCompare(right))
return [...known, ...custom]
})
const hasActiveImagePricing = computed(() =>
activeImageDefaultPrice.value !== null
|| activeImageRows.value.length > 0
|| activeImageRangeRows.value.length > 0,
)
const imageTableMinWidthClass = computed(() =>
activeImageQualities.value.length > 3 ? 'min-w-[620px]' : 'min-w-[460px]',
)
function processingPricingHasFacts(config: ProcessingTierPricingConfig): boolean {
if (Array.isArray(config.tiers) && config.tiers.length > 0) return true
if (toFiniteNumber(config.image_output_price_default) !== null) return true
if (isRecord(config.image_output_prices)) {
for (const prices of Object.values(config.image_output_prices)) {
if (isRecord(prices) && Object.keys(finitePriceRecord(prices)).length > 0) return true
}
}
return Array.isArray(config.image_output_price_ranges)
&& config.image_output_price_ranges.some(range => (
isRecord(range)
&& isRecord(range.prices)
&& Object.keys(finitePriceRecord(range.prices)).length > 0
))
}
function formatTokenRange(tiers: PricingTier[], index: number): string {
const lower = index === 0 ? 0 : toFiniteNumber(tiers[index - 1]?.up_to)
const upper = tiers[index]?.up_to === null ? null : toFiniteNumber(tiers[index]?.up_to)
if (upper === null) return lower && lower > 0 ? `> ${formatTokens(lower)}` : '所有'
return `${formatTokens(lower ?? 0)} - ${formatTokens(upper)}`
}
function cacheCreationPriceForTtl(tier: PricingTier, ttlMinutes: number): number | null {
const entry = Array.isArray(tier.cache_ttl_pricing)
? tier.cache_ttl_pricing.find(item => item.ttl_minutes === ttlMinutes)
: undefined
return toFiniteNumber(entry?.cache_creation_price_per_1m)
}
function formatPixelRange(rows: ImageRangeRow[], index: number): string {
const lower = index === 0 ? 0 : rows[index - 1]?.upToPixels
const upper = rows[index]?.upToPixels
if (upper === null) return lower && lower > 0 ? `> ${formatTokens(lower)} px` : '所有像素'
return `${formatTokens(lower ?? 0)} - ${formatTokens(upper)} px`
}
function formatPrice(value: unknown): string {
const price = toFiniteNumber(value)
if (price === null) return '-'
return `$${price.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 6,
useGrouping: false,
})}`
}
function formatImageSize(value: string): string {
return value.replace(/\s*[xX×]\s*/g, ' x ')
}
function imageSizeArea(value: string): number {
const match = value.match(/^(\d+)\s*[xX×]\s*(\d+)$/)
return match ? Number(match[1]) * Number(match[2]) : Number.MAX_SAFE_INTEGER
}
function finitePriceRecord(value: Record<string, unknown>): Record<string, number> {
const entries: Array<[string, number]> = []
for (const [key, rawPrice] of Object.entries(value)) {
const price = toFiniteNumber(rawPrice)
if (price !== null) entries.push([key, price])
}
return Object.fromEntries(entries)
}
function toFiniteNumber(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : null
}
return null
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value)
}
</script>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,249 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createApp,
defineComponent,
h,
nextTick,
ref,
type App,
} from 'vue'
import type { ModelsDevModelItem } from '@/api/models-dev'
import GlobalModelFormDialog from '../GlobalModelFormDialog.vue'
const modelsDevMocks = vi.hoisted(() => ({
getModelsDevList: vi.fn(),
}))
const globalModelMocks = vi.hoisted(() => ({
createGlobalModel: vi.fn(),
updateGlobalModel: vi.fn(),
}))
vi.mock('@/api/models-dev', () => ({
getModelsDevList: modelsDevMocks.getModelsDevList,
getProviderLogoUrl: (providerId: string) => `/logos/${providerId}.svg`,
}))
vi.mock('@/api/global-models', () => ({
createGlobalModel: globalModelMocks.createGlobalModel,
updateGlobalModel: globalModelMocks.updateGlobalModel,
}))
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
const stalePreset: ModelsDevModelItem = {
providerId: 'openai',
providerName: 'OpenAI',
modelId: 'stale-model',
modelName: 'Stale Model',
official: true,
supportsReasoning: true,
inputPrice: 1,
outputPrice: 2,
tieredPricing: {
tiers: [{
up_to: null,
input_price_per_1m: 1,
output_price_per_1m: 2,
}],
processing_tiers: {
priority: {
tiers: [{
up_to: null,
input_price_per_1m: 2,
output_price_per_1m: 4,
}],
},
},
},
}
const freshPreset: ModelsDevModelItem = {
providerId: 'openai',
providerName: 'OpenAI',
modelId: 'fresh-model',
modelName: 'Fresh Model',
family: 'fresh-family',
official: true,
supportsTemperature: false,
contextLimit: 128_000,
outputLimit: 4_096,
inputModalities: ['text'],
outputModalities: ['text'],
inputPrice: 3,
outputPrice: 4,
tieredPricing: {
tiers: [
{
up_to: 99_999,
input_price_per_1m: 3,
output_price_per_1m: 4,
},
{
up_to: null,
input_price_per_1m: 5,
output_price_per_1m: 6,
},
],
},
}
function mountDialog() {
const root = document.createElement('div')
document.body.appendChild(root)
const open = ref(false)
const app = createApp(defineComponent({
setup() {
return () => h(GlobalModelFormDialog, {
open: open.value,
model: null,
})
},
}))
app.mount(root)
mountedApps.push({ app, root })
open.value = true
return { root, open }
}
async function settle() {
for (let index = 0; index < 5; index += 1) {
await Promise.resolve()
await nextTick()
}
}
function findButton(text: string): HTMLButtonElement {
const button = [...document.body.querySelectorAll('button')]
.find(candidate => candidate.textContent?.trim().includes(text))
if (!(button instanceof HTMLButtonElement)) {
throw new Error(`Missing button containing: ${text}`)
}
return button
}
function findExactButton(text: string): HTMLButtonElement {
const button = [...document.body.querySelectorAll('button')]
.find(candidate => candidate.textContent?.trim() === text)
if (!(button instanceof HTMLButtonElement)) {
throw new Error(`Missing button: ${text}`)
}
return button
}
async function setInput(input: HTMLInputElement | null, value: string) {
if (!input) throw new Error('Missing input')
input.value = value
input.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
}
beforeEach(() => {
modelsDevMocks.getModelsDevList.mockReset()
modelsDevMocks.getModelsDevList.mockResolvedValue([stalePreset, freshPreset])
globalModelMocks.createGlobalModel.mockReset()
globalModelMocks.createGlobalModel.mockResolvedValue({})
globalModelMocks.updateGlobalModel.mockReset()
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
value: vi.fn(),
configurable: true,
})
})
afterEach(() => {
for (const { app, root } of mountedApps.splice(0)) {
app.unmount()
root.remove()
}
document.body.innerHTML = ''
})
describe('GlobalModelFormDialog preset replacement', () => {
it('drops the previous draft and submits only the newly selected model preset', async () => {
mountDialog()
await settle()
findButton('Stale Model').click()
await settle()
await setInput(
document.body.querySelector<HTMLInputElement>('input[placeholder="如 0.01"]'),
'0.25',
)
await setInput(
document.body.querySelector<HTMLInputElement>('#model-description'),
'must not leak into the next preset',
)
await setInput(
document.body.querySelector<HTMLInputElement>('[data-testid="tier-input-price"]'),
'99',
)
findExactButton('视频').click()
await nextTick()
findExactButton('Sora').click()
await nextTick()
findButton('返回选择模型').click()
await settle()
findButton('Fresh Model').click()
await settle()
expect(document.body.querySelector<HTMLInputElement>('#model-name')?.value).toBe('fresh-model')
expect(document.body.querySelector<HTMLInputElement>('#model-display-name')?.value).toBe('Fresh Model')
expect(document.body.querySelector<HTMLInputElement>('#model-description')?.value).toBe('')
expect(document.body.querySelector<HTMLInputElement>('input[placeholder="如 0.01"]')?.value).toBe('')
expect(
[...document.body.querySelectorAll<HTMLInputElement>('[data-testid="tier-input-price"]')]
.map(input => input.value),
).toEqual(['3', '5'])
findExactButton('添加').click()
await settle()
expect(globalModelMocks.createGlobalModel).toHaveBeenCalledOnce()
const payload = globalModelMocks.createGlobalModel.mock.calls[0][0]
expect(payload).toMatchObject({
name: 'fresh-model',
display_name: 'Fresh Model',
default_price_per_request: undefined,
config: {
streaming: true,
context_limit: 128_000,
output_limit: 4_096,
family: 'fresh-family',
input_modalities: ['text'],
output_modalities: ['text'],
},
default_tiered_pricing: {
tiers: [
{
up_to: 99_999,
input_price_per_1m: 3,
output_price_per_1m: 4,
},
{
up_to: null,
input_price_per_1m: 5,
output_price_per_1m: 6,
},
],
},
})
expect(payload.config).not.toHaveProperty('description')
expect(payload.config).not.toHaveProperty('billing')
expect(payload.default_tiered_pricing).not.toHaveProperty('processing_tiers')
expect(payload.default_tiered_pricing.tiers).toEqual([
{
up_to: 99_999,
input_price_per_1m: 3,
output_price_per_1m: 4,
},
{
up_to: null,
input_price_per_1m: 5,
output_price_per_1m: 6,
},
])
})
})
@@ -0,0 +1,102 @@
import { afterEach, describe, expect, it } from 'vitest'
import { createApp, defineComponent, h, nextTick, type App } from 'vue'
import type { TieredPricingConfig } from '@/api/endpoints/types'
import ProcessingTierPricingSummary from '../ProcessingTierPricingSummary.vue'
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
function mountSummary(pricing: TieredPricingConfig) {
const root = document.createElement('div')
document.body.appendChild(root)
const app = createApp(defineComponent({
setup: () => () => h(ProcessingTierPricingSummary, { pricing }),
}))
app.mount(root)
mountedApps.push({ app, root })
return root
}
function clickTier(root: HTMLElement, tier: string) {
const button = root.querySelector(`[data-processing-tier="${tier}"]`)
if (!(button instanceof HTMLButtonElement)) throw new Error(`Missing ${tier} tier button`)
button.click()
}
afterEach(() => {
for (const { app, root } of mountedApps.splice(0)) {
app.unmount()
root.remove()
}
})
describe('ProcessingTierPricingSummary', () => {
it('shows finite and unbounded token tiers in stable processing-tier order', () => {
const root = mountSummary({
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
hyperlane: {
tiers: [{ up_to: 128_000, input_price_per_1m: 7, output_price_per_1m: 35 }],
},
priority: {
tiers: [
{
up_to: 272_000,
input_price_per_1m: 10,
output_price_per_1m: 60,
cache_creation_price_per_1m: 12.5,
cache_read_price_per_1m: 1,
cache_ttl_pricing: [{ ttl_minutes: 60, cache_creation_price_per_1m: 20 }],
},
{ up_to: null, input_price_per_1m: 20, output_price_per_1m: 120 },
],
},
empty: {},
},
})
expect([...root.querySelectorAll('[data-processing-tier]')].map(element => (
element.getAttribute('data-processing-tier')
))).toEqual(['priority', 'hyperlane'])
expect(root.querySelectorAll('[data-testid="processing-token-tier-row"]')).toHaveLength(2)
expect(root.textContent).toContain('0 - 272K')
expect(root.textContent).toContain('> 272K')
expect(root.textContent).toContain('$20.00')
})
it('renders image-only overlays, zero prices and future qualities', async () => {
const root = mountSummary({
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
flex: {
image_output_price_default: 0,
image_output_prices: {
'1024x1024': { low: 0, high: 0.04 },
},
},
hyperlane: {
image_output_price_ranges: [
{ up_to_pixels: null, prices: { ultra: 0.05 } },
{ up_to_pixels: 1_048_576, prices: { ultra: 0.03 } },
],
},
},
})
expect(root.querySelectorAll('[data-testid="processing-token-tier-row"]')).toHaveLength(0)
expect(root.textContent).toContain('默认 $0.00/张')
expect(root.textContent).toContain('1024 x 1024')
expect(root.textContent).toContain('$0.04')
clickTier(root, 'hyperlane')
await nextTick()
expect(root.textContent).toContain('ultra')
expect(root.textContent).toContain('0 - 1.05M px')
expect(root.textContent).toContain('> 1.05M px')
expect(root.textContent).toContain('$0.03')
expect(root.textContent!.indexOf('0 - 1.05M px')).toBeLessThan(
root.textContent!.indexOf('> 1.05M px'),
)
})
})
@@ -0,0 +1,771 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
createApp,
defineComponent,
h,
nextTick,
shallowRef,
type App,
type ComponentPublicInstance,
} from 'vue'
import type { TieredPricingConfig } from '@/api/endpoints/types'
import TieredPricingEditor from '../TieredPricingEditor.vue'
interface TieredPricingEditorExposed extends ComponentPublicInstance {
getFinalPricing: () => TieredPricingConfig
getValidationError: () => string | null
}
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
function mountEditor(
modelValue: TieredPricingConfig,
options: {
autoFillMissingCachePrices?: boolean
showCache1h?: boolean
showImagePricing?: boolean
showTokenPricing?: boolean
showImageEditor?: boolean
} = {},
) {
const root = document.createElement('div')
document.body.appendChild(root)
const onUpdate = vi.fn()
const currentModelValue = shallowRef(modelValue)
let editor: TieredPricingEditorExposed | null = null
const app = createApp(defineComponent({
setup() {
return () => h(TieredPricingEditor, {
ref: (instance: unknown) => {
editor = instance as TieredPricingEditorExposed | null
},
modelValue: currentModelValue.value,
autoFillMissingCachePrices: options.autoFillMissingCachePrices,
showCache1h: options.showCache1h,
showImagePricing: options.showImagePricing,
showTokenPricing: options.showTokenPricing,
showImageEditor: options.showImageEditor,
'onUpdate:modelValue': onUpdate,
})
},
}))
app.mount(root)
mountedApps.push({ app, root })
return {
root,
onUpdate,
setModelValue: (value: TieredPricingConfig) => {
currentModelValue.value = value
},
getFinalPricing: () => {
if (!editor) throw new Error('TieredPricingEditor ref was not mounted')
return editor.getFinalPricing()
},
getValidationError: () => {
if (!editor) throw new Error('TieredPricingEditor ref was not mounted')
return editor.getValidationError()
},
}
}
function click(element: Element | null) {
if (!(element instanceof HTMLButtonElement)) {
throw new Error('Expected a button')
}
element.click()
}
afterEach(() => {
for (const { app, root } of mountedApps.splice(0)) {
app.unmount()
root.remove()
}
})
describe('TieredPricingEditor processing tiers', () => {
it('round-trips root, overlay and pricing-tier extension fields', () => {
const pricing = {
tiers: [{
up_to: null,
input_price_per_1m: 5,
output_price_per_1m: 30,
vendor_tier_note: 'keep-standard-tier',
}],
future_root_option: { enabled: true },
processing_tiers: {
priority: {
tiers: [{
up_to: null,
input_price_per_1m: 10,
output_price_per_1m: 60,
vendor_tier_note: 'keep-priority-tier',
}],
contract_reference: 'priority-2026',
},
hyperlane: {
tiers: [{
up_to: null,
input_price_per_1m: 7.5,
output_price_per_1m: 42,
}],
future_overlay_option: { mode: 'reserved' },
},
},
} as TieredPricingConfig
const { getFinalPricing } = mountEditor(pricing)
const result = getFinalPricing()
expect(result.future_root_option).toEqual({ enabled: true })
expect(result.tiers[0].vendor_tier_note).toBe('keep-standard-tier')
expect(result.processing_tiers?.priority.contract_reference).toBe('priority-2026')
expect(result.processing_tiers?.priority.tiers?.[0].vendor_tier_note).toBe('keep-priority-tier')
expect(result.processing_tiers?.hyperlane.future_overlay_option).toEqual({ mode: 'reserved' })
})
it('shows known and discovered tiers and edits a discovered tier through the shared rate controls', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
future_root_option: 'keep-root',
processing_tiers: {
hyperlane: {
tiers: [{ up_to: null, input_price_per_1m: 7.5, output_price_per_1m: 42 }],
future_overlay_option: 'keep-overlay',
},
},
} as TieredPricingConfig
const { root, onUpdate } = mountEditor(pricing)
expect(root.querySelectorAll('[data-processing-tier]')).toHaveLength(5)
expect(root.textContent).toContain('Standard')
expect(root.textContent).toContain('Priority')
expect(root.textContent).toContain('Flex')
expect(root.textContent).toContain('Batch')
expect(root.textContent).toContain('hyperlane')
click(root.querySelector('[data-processing-tier="hyperlane"]'))
await nextTick()
const input = root.querySelector('[data-testid="tier-input-price"]') as HTMLInputElement | null
if (!input) throw new Error('Expected the shared input-price control')
input.value = '9.75'
input.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
const emitted = onUpdate.mock.lastCall?.[0] as TieredPricingConfig
expect(emitted.processing_tiers?.hyperlane.tiers?.[0].input_price_per_1m).toBe(9.75)
expect(emitted.processing_tiers?.hyperlane.future_overlay_option).toBe('keep-overlay')
expect(emitted.future_root_option).toBe('keep-root')
})
it('adds and removes an explicit known-tier overlay without changing Standard', async () => {
const pricing = {
tiers: [{
up_to: null,
input_price_per_1m: 5,
output_price_per_1m: 30,
future_tier_option: 'keep-on-clone',
}],
} as TieredPricingConfig
const { root, onUpdate } = mountEditor(pricing)
click(root.querySelector('[data-processing-tier="priority"]'))
await nextTick()
expect(root.querySelector('[data-testid="processing-tier-empty"]')).not.toBeNull()
click(root.querySelector('[data-testid="processing-tier-add"]'))
await nextTick()
let emitted = onUpdate.mock.lastCall?.[0] as TieredPricingConfig
expect(emitted.tiers[0].input_price_per_1m).toBe(5)
expect(emitted.processing_tiers?.priority.tiers?.[0]).toMatchObject(pricing.tiers[0])
expect(emitted.processing_tiers?.priority.tiers?.[0].cache_creation_price_per_1m).toBe(6.25)
expect(emitted.processing_tiers?.priority.tiers?.[0].cache_read_price_per_1m).toBe(0.5)
expect(root.querySelector('[data-testid="processing-tier-remove"]'), root.innerHTML).not.toBeNull()
click(root.querySelector('[data-testid="processing-tier-remove"]'))
await nextTick()
emitted = onUpdate.mock.lastCall?.[0] as TieredPricingConfig
expect(emitted.processing_tiers).toBeUndefined()
expect(emitted.tiers[0]).toMatchObject(pricing.tiers[0])
expect(emitted.tiers[0].cache_creation_price_per_1m).toBe(6.25)
expect(emitted.tiers[0].cache_read_price_per_1m).toBe(0.5)
})
it('keeps an unconfigured tier tab outside the persisted pricing contract', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
image_output_price_default: 0.01,
} as TieredPricingConfig
const { getFinalPricing, getValidationError, root } = mountEditor(pricing, {
showImagePricing: true,
})
click(root.querySelector('[data-processing-tier="priority"]'))
await nextTick()
expect(root.querySelector('[data-testid="processing-tier-empty"]')).not.toBeNull()
expect(getValidationError()).toBeNull()
const result = getFinalPricing()
expect(result.tiers[0].input_price_per_1m).toBe(5)
expect(result.image_output_price_default).toBe(0.01)
expect(result.processing_tiers).toBeUndefined()
})
it.each([
['absent', undefined],
['null', null],
['empty object', {}],
] as const)('preserves an unedited %s processing_tiers value', (_, processingTiers) => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
...(processingTiers === undefined ? {} : { processing_tiers: processingTiers }),
} as TieredPricingConfig
const { getFinalPricing } = mountEditor(pricing)
const result = getFinalPricing()
expect(Object.prototype.hasOwnProperty.call(result, 'processing_tiers'))
.toBe(processingTiers !== undefined)
expect(result.processing_tiers).toEqual(processingTiers)
})
it('edits every configured official processing tier through the same controls', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: Object.fromEntries(['priority', 'flex', 'batch'].map((key, index) => [
key,
{
tiers: [{
up_to: null,
input_price_per_1m: index + 1,
output_price_per_1m: (index + 1) * 6,
}],
},
])),
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing)
for (const [index, key] of ['priority', 'flex', 'batch'].entries()) {
click(root.querySelector(`[data-processing-tier="${key}"]`))
await nextTick()
const input = root.querySelector('[data-testid="tier-input-price"]') as HTMLInputElement | null
if (!input) throw new Error(`Expected input-price control for ${key}`)
input.value = String(11 + index)
input.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
}
const result = getFinalPricing()
expect(result.tiers[0].input_price_per_1m).toBe(5)
expect(result.processing_tiers?.priority.tiers?.[0].input_price_per_1m).toBe(11)
expect(result.processing_tiers?.flex.tiers?.[0].input_price_per_1m).toBe(12)
expect(result.processing_tiers?.batch.tiers?.[0].input_price_per_1m).toBe(13)
})
it('keeps cache multiplier drafts isolated by processing scope', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
priority: {
tiers: [{ up_to: 272000, input_price_per_1m: 10, output_price_per_1m: 60 }],
},
},
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing)
click(root.querySelector('[data-processing-tier="priority"]'))
await nextTick()
const multiplier = root.querySelector(
'input[aria-label="Priority 阶梯 1 缓存创建倍率"]',
) as HTMLInputElement
multiplier.value = '2'
multiplier.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
const result = getFinalPricing()
expect(result.tiers[0].cache_creation_price_per_1m).toBe(6.25)
expect(result.processing_tiers?.priority.tiers?.[0].cache_creation_price_per_1m).toBe(20)
})
it('keeps absent cache prices empty and absent when automatic cache filling is disabled', () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing, {
autoFillMissingCachePrices: false,
})
const creation = root.querySelector(
'input[aria-label="Standard 阶梯 1 缓存创建倍率"]',
) as HTMLInputElement
const read = root.querySelector(
'input[aria-label="Standard 阶梯 1 缓存读取倍率"]',
) as HTMLInputElement
expect(creation.value).toBe('')
expect(read.value).toBe('')
expect(getFinalPricing().tiers).toEqual([
{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 },
])
})
it('preserves only the explicitly supplied side of cache pricing when automatic filling is disabled', () => {
const pricing = {
tiers: [
{
up_to: 128_000,
input_price_per_1m: 5,
output_price_per_1m: 30,
cache_creation_price_per_1m: 6.25,
},
{
up_to: null,
input_price_per_1m: 7,
output_price_per_1m: 42,
cache_read_price_per_1m: 0.7,
},
],
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing, {
autoFillMissingCachePrices: false,
})
const creationValues = [...root.querySelectorAll<HTMLInputElement>(
'input[aria-label*="缓存创建倍率"]',
)].map(input => input.value)
const readValues = [...root.querySelectorAll<HTMLInputElement>(
'input[aria-label*="缓存读取倍率"]',
)].map(input => input.value)
expect(creationValues).toEqual(['1.25', ''])
expect(readValues).toEqual(['', '0.1'])
expect(getFinalPricing().tiers).toEqual(pricing.tiers)
})
it('adds and removes only the cache price edited by the user when automatic filling is disabled', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing, {
autoFillMissingCachePrices: false,
})
const read = root.querySelector(
'input[aria-label="Standard 阶梯 1 缓存读取倍率"]',
) as HTMLInputElement
read.value = '0.2'
read.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
expect(getFinalPricing().tiers).toEqual([{
up_to: null,
input_price_per_1m: 5,
output_price_per_1m: 30,
cache_read_price_per_1m: 1,
}])
read.value = ''
read.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
expect(getFinalPricing().tiers).toEqual([{
up_to: null,
input_price_per_1m: 5,
output_price_per_1m: 30,
}])
})
it('does not turn absent cache prices into zero when switching editor modes', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing, {
autoFillMissingCachePrices: false,
})
click(root.querySelector(
'button[aria-label="Standard 阶梯 1 切换缓存价格输入方式"]',
))
await nextTick()
expect((root.querySelector(
'input[aria-label="Standard 阶梯 1 缓存创建价格"]',
) as HTMLInputElement).value).toBe('')
expect((root.querySelector(
'input[aria-label="Standard 阶梯 1 缓存读取价格"]',
) as HTMLInputElement).value).toBe('')
expect(getFinalPricing().tiers).toEqual(pricing.tiers)
})
it('rebuilds when an external model later matches an older emitted value', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
} as TieredPricingConfig
const { root, onUpdate, setModelValue } = mountEditor(pricing, {
autoFillMissingCachePrices: false,
})
const read = root.querySelector(
'input[aria-label="Standard 阶梯 1 缓存读取倍率"]',
) as HTMLInputElement
read.value = '0.2'
read.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
const olderEmittedValue = onUpdate.mock.lastCall?.[0] as TieredPricingConfig
setModelValue({
tiers: [{ up_to: null, input_price_per_1m: 7, output_price_per_1m: 42 }],
})
await nextTick()
expect((root.querySelector('[data-testid="tier-input-price"]') as HTMLInputElement).value)
.toBe('7')
setModelValue(olderEmittedValue)
await nextTick()
expect((root.querySelector('[data-testid="tier-input-price"]') as HTMLInputElement).value)
.toBe('5')
expect((root.querySelector(
'input[aria-label="Standard 阶梯 1 缓存读取倍率"]',
) as HTMLInputElement).value).toBe('0.2')
})
it('keeps processing image catalogs editable when token controls are hidden', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
priority: { image_output_price_default: 0.05 },
},
} as TieredPricingConfig
const { root } = mountEditor(pricing, {
showTokenPricing: false,
showImagePricing: true,
showImageEditor: true,
})
click(root.querySelector('[data-processing-tier="priority"]'))
await nextTick()
expect(root.querySelector('[data-testid="tier-input-price"]')).toBeNull()
expect(root.querySelector('input[aria-label="Priority 图像输出默认价格"]')).not.toBeNull()
})
it('accepts a finite terminal tier for any processing overlay', () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
priority: {
tiers: [{ up_to: 272000, input_price_per_1m: 10, output_price_per_1m: 60 }],
},
hyperlane: {
tiers: [{ up_to: 180000, input_price_per_1m: 7, output_price_per_1m: 42 }],
},
},
} as TieredPricingConfig
const { getFinalPricing, getValidationError } = mountEditor(pricing)
expect(getValidationError()).toBeNull()
expect(getFinalPricing().processing_tiers?.priority.tiers?.[0].up_to).toBe(272000)
expect(getFinalPricing().processing_tiers?.hyperlane.tiers?.[0].up_to).toBe(180000)
})
it('keeps Standard terminal coverage unbounded', () => {
const pricing = {
tiers: [{ up_to: 272000, input_price_per_1m: 5, output_price_per_1m: 30 }],
} as TieredPricingConfig
const { getValidationError } = mountEditor(pricing)
expect(getValidationError()).toBe('Standard: 最后一个阶梯必须是无上限的')
})
it('switches a processing terminal tier between finite and unbounded coverage', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
priority: {
tiers: [{ up_to: 272000, input_price_per_1m: 10, output_price_per_1m: 60 }],
},
},
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing)
click(root.querySelector('[data-processing-tier="priority"]'))
await nextTick()
const terminal = root.querySelector(
'select[aria-label="Priority 阶梯 1 上限"]',
) as HTMLSelectElement
expect(terminal.value).toBe('272000')
terminal.value = '-2'
terminal.dispatchEvent(new Event('change', { bubbles: true }))
await nextTick()
expect(getFinalPricing().processing_tiers?.priority.tiers?.[0].up_to).toBeNull()
terminal.value = '272000'
terminal.dispatchEvent(new Event('change', { bubbles: true }))
await nextTick()
expect(getFinalPricing().processing_tiers?.priority.tiers?.[0].up_to).toBe(272000)
})
it('preserves processing coverage when tiers are added and removed', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
priority: {
tiers: [{ up_to: 272000, input_price_per_1m: 10, output_price_per_1m: 60 }],
},
},
} as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing)
click(root.querySelector('[data-processing-tier="priority"]'))
await nextTick()
const addButton = [...root.querySelectorAll('button')]
.find(button => button.textContent?.includes('添加价格阶梯'))
click(addButton ?? null)
await nextTick()
expect(getFinalPricing().processing_tiers?.priority.tiers?.map(tier => tier.up_to))
.toEqual([272000, null])
click(root.querySelector('button[aria-label="删除 Priority 阶梯 2"]'))
await nextTick()
expect(getFinalPricing().processing_tiers?.priority.tiers?.map(tier => tier.up_to))
.toEqual([272000])
})
it('preserves a special unknown processing tier key without prototype coercion', () => {
const pricing = JSON.parse(`{
"tiers": [{"up_to": null, "input_price_per_1m": 5, "output_price_per_1m": 30}],
"processing_tiers": {
"__proto__": {
"tiers": [{"up_to": null, "input_price_per_1m": 7, "output_price_per_1m": 42}],
"future_overlay_option": "keep"
}
}
}`) as TieredPricingConfig
const { root, getFinalPricing } = mountEditor(pricing)
expect(root.textContent).toContain('__proto__')
const result = getFinalPricing()
expect(Object.prototype.hasOwnProperty.call(result.processing_tiers, '__proto__')).toBe(true)
expect(result.processing_tiers?.__proto__.future_overlay_option).toBe('keep')
expect(result.processing_tiers?.__proto__.tiers?.[0].input_price_per_1m).toBe(7)
})
it('preserves future image pricing fields when image pricing is enabled', () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
image_output_prices: {
'1024x1024': { low: 0.01, ultra: 0.09 },
},
image_output_price_ranges: [{
up_to_pixels: 1_048_576,
prices: { low: 0.01, ultra: 0.09 },
future_range_option: { billing_unit: 'image' },
}],
} as TieredPricingConfig
const { getFinalPricing } = mountEditor(pricing, { showImagePricing: true })
const result = getFinalPricing()
expect(result.image_output_prices?.['1024x1024'].ultra).toBe(0.09)
expect(result.image_output_price_ranges?.[0].prices.ultra).toBe(0.09)
expect(result.image_output_price_ranges?.[0].future_range_option)
.toEqual({ billing_unit: 'image' })
})
it('rejects fractional image pixel limits without coercing them to integers', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
image_output_price_ranges: [{
up_to_pixels: 1_048_576,
prices: { high: 0.07 },
}],
} as TieredPricingConfig
const { getValidationError, root } = mountEditor(pricing, { showImagePricing: true })
const limit = root.querySelector(
'input[aria-label="图像像素区间 1 上限"]',
) as HTMLInputElement
limit.value = '1.5'
limit.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
expect(getValidationError()).toBe('Standard: 图像像素区间 1 的上限必须是正整数')
})
it('treats an image-only processing overlay as a valid tier configuration', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
hyperlane: {
image_output_price_default: 0.08,
future_overlay_option: { billing_unit: 'image' },
},
},
} as TieredPricingConfig
const { getFinalPricing, root } = mountEditor(pricing, { showImagePricing: true })
click(root.querySelector('[data-processing-tier="hyperlane"]'))
await nextTick()
expect(root.textContent).not.toContain('至少需要一个价格阶梯')
expect(getFinalPricing().processing_tiers?.hyperlane).toEqual(
pricing.processing_tiers?.hyperlane,
)
})
it('edits image pricing through the active processing-tier scope', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
image_output_price_default: 0.01,
processing_tiers: {
priority: {
image_output_price_default: 0.05,
image_output_prices: {
'1024x1024': { high: 0.08, ultra: 0.12 },
},
image_output_price_ranges: [{
up_to_pixels: 1_048_576,
prices: { high: 0.07, ultra: 0.11 },
future_range_option: 'keep-priority',
}],
},
flex: {
image_output_price_default: 0.02,
},
},
} as TieredPricingConfig
const { getFinalPricing, root } = mountEditor(pricing, { showImagePricing: true })
click(root.querySelector('[data-processing-tier="priority"]'))
await nextTick()
const priorityDefault = root.querySelector(
'input[aria-label="Priority 图像输出默认价格"]',
) as HTMLInputElement
const priorityHigh = root.querySelector(
'input[aria-label="1024x1024 high 图像输出价格"]',
) as HTMLInputElement
expect(priorityDefault.value).toBe('0.05')
expect(priorityHigh.value).toBe('0.08')
priorityDefault.value = '0.06'
priorityDefault.dispatchEvent(new Event('input', { bubbles: true }))
priorityHigh.value = '0.09'
priorityHigh.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
click(root.querySelector('[data-processing-tier="flex"]'))
await nextTick()
const flexDefault = root.querySelector(
'input[aria-label="Flex 图像输出默认价格"]',
) as HTMLInputElement
expect(flexDefault.value).toBe('0.02')
const result = getFinalPricing()
expect(result.image_output_price_default).toBe(0.01)
expect(result.processing_tiers?.priority.image_output_price_default).toBe(0.06)
expect(result.processing_tiers?.priority.image_output_prices?.['1024x1024'].high).toBe(0.09)
expect(result.processing_tiers?.priority.image_output_prices?.['1024x1024'].ultra).toBe(0.12)
expect(result.processing_tiers?.priority.image_output_price_ranges?.[0].future_range_option)
.toBe('keep-priority')
expect(result.processing_tiers?.flex.image_output_price_default).toBe(0.02)
})
it('clears threshold editing state when removing and then adding tiers', async () => {
const pricing = {
tiers: [
{ up_to: 64_000, input_price_per_1m: 5, output_price_per_1m: 30 },
{ up_to: 128_000, input_price_per_1m: 7, output_price_per_1m: 42 },
{ up_to: null, input_price_per_1m: 9, output_price_per_1m: 54 },
],
} as TieredPricingConfig
const { root } = mountEditor(pricing)
const thresholdSelects = root.querySelectorAll('select')
const secondThreshold = thresholdSelects.item(1) as HTMLSelectElement
secondThreshold.value = '-1'
secondThreshold.dispatchEvent(new Event('change', { bubbles: true }))
await nextTick()
expect(root.querySelectorAll('input[placeholder="K"]')).toHaveLength(1)
const tierRemoveButtons = Array.from(root.querySelectorAll('button'))
.filter(button => button.querySelector('.lucide-x'))
click(tierRemoveButtons[0] ?? null)
await nextTick()
const addTierButton = Array.from(root.querySelectorAll('button'))
.find(button => button.textContent?.includes('添加价格阶梯'))
click(addTierButton ?? null)
await nextTick()
expect(root.querySelectorAll('input[placeholder="K"]')).toHaveLength(0)
})
it('gives every compact pricing control an accessible name', () => {
const pricing = {
tiers: [
{ up_to: 64_000, input_price_per_1m: 5, output_price_per_1m: 30 },
{ up_to: null, input_price_per_1m: 7, output_price_per_1m: 42 },
],
} as TieredPricingConfig
const { root } = mountEditor(pricing, {
showCache1h: true,
showImagePricing: true,
})
for (const control of root.querySelectorAll('input, select')) {
expect(control.getAttribute('aria-label'), control.outerHTML).toBeTruthy()
}
const iconOnlyButtons = Array.from(root.querySelectorAll('button'))
.filter(button => button.textContent?.trim() === '')
for (const button of iconOnlyButtons) {
expect(button.getAttribute('aria-label'), button.outerHTML).toBeTruthy()
}
})
it('blocks serialization when an inactive processing tier is invalid', async () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: 5, output_price_per_1m: 30 }],
processing_tiers: {
priority: {
tiers: [
{ up_to: 128_000, input_price_per_1m: 10, output_price_per_1m: 60 },
{ up_to: 64_000, input_price_per_1m: 11, output_price_per_1m: 66 },
{ up_to: null, input_price_per_1m: 12, output_price_per_1m: 72 },
],
},
},
} as TieredPricingConfig
const { getFinalPricing, getValidationError, onUpdate, root } = mountEditor(pricing)
const standardInput = root.querySelector('[data-testid="tier-input-price"]') as HTMLInputElement
standardInput.value = '6'
standardInput.dispatchEvent(new Event('input', { bubbles: true }))
await nextTick()
expect(onUpdate).not.toHaveBeenCalled()
expect(getValidationError()).toContain('Priority')
expect(getValidationError()).toContain('上限必须大于前一个阶梯')
expect(() => getFinalPricing()).toThrow('Priority')
})
it('rejects negative known prices before they reach the billing contract', () => {
const pricing = {
tiers: [{ up_to: null, input_price_per_1m: -1, output_price_per_1m: 30 }],
} as TieredPricingConfig
const { getFinalPricing, getValidationError } = mountEditor(pricing)
expect(getValidationError()).toBe('Standard: 阶梯 1 的输入价格必须是非负有限数值')
expect(() => getFinalPricing()).toThrow('输入价格必须是非负有限数值')
})
})
@@ -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
}
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest'
import type { TieredPricingConfig } from '@/api/endpoints/types'
import {
tieredPricingHasCacheTtl,
tieredPricingHasImageOutputPricing,
} from '../tiered-pricing'
function pricingWithProcessingTier(
processingTier: NonNullable<TieredPricingConfig['processing_tiers']>[string],
): TieredPricingConfig {
return {
tiers: [{ up_to: null, input_price_per_1m: 1, output_price_per_1m: 2 }],
processing_tiers: { priority: processingTier },
}
}
describe('tiered pricing capabilities', () => {
it('detects image prices in the base and processing-tier catalogs', () => {
expect(tieredPricingHasImageOutputPricing({
tiers: [],
image_output_price_default: 0,
})).toBe(true)
expect(tieredPricingHasImageOutputPricing(pricingWithProcessingTier({
image_output_prices: { '1024x1024': { high: 0.08 } },
}))).toBe(true)
expect(tieredPricingHasImageOutputPricing(pricingWithProcessingTier({
image_output_price_ranges: [{
up_to_pixels: null,
prices: { medium: 0.04 },
}],
}))).toBe(true)
expect(tieredPricingHasImageOutputPricing(pricingWithProcessingTier({}))).toBe(false)
})
it('detects cache TTL prices in the base and processing-tier catalogs', () => {
expect(tieredPricingHasCacheTtl({
tiers: [{
up_to: null,
input_price_per_1m: 1,
output_price_per_1m: 2,
cache_ttl_pricing: [{ ttl_minutes: 60, cache_creation_price_per_1m: 3 }],
}],
}, 60)).toBe(true)
expect(tieredPricingHasCacheTtl(pricingWithProcessingTier({
tiers: [{
up_to: null,
input_price_per_1m: 1,
output_price_per_1m: 2,
cache_ttl_pricing: [{ ttl_minutes: 60, cache_creation_price_per_1m: 3 }],
}],
}), 60)).toBe(true)
expect(tieredPricingHasCacheTtl(pricingWithProcessingTier({}), 60)).toBe(false)
})
})
@@ -0,0 +1,67 @@
import type {
ProcessingTierPricingConfig,
TieredPricingConfig,
} from '@/api/endpoints/types'
type PricingCatalog = TieredPricingConfig | ProcessingTierPricingConfig
export function comparePricingUpperBounds(
left: number | null,
right: number | null,
): number {
if (left === null && right === null) return 0
if (left === null) return 1
if (right === null) return -1
return left - right
}
function pricingCatalogs(pricing: TieredPricingConfig | null | undefined): PricingCatalog[] {
if (!pricing) return []
const processingTiers = pricing.processing_tiers
? Object.values(pricing.processing_tiers).filter(isRecord)
: []
return [pricing, ...processingTiers]
}
export function tieredPricingHasImageOutputPricing(
pricing: TieredPricingConfig | null | undefined,
): boolean {
return pricingCatalogs(pricing).some((catalog) => {
if (toFinitePrice(catalog.image_output_price_default) !== null) return true
if (Object.values(catalog.image_output_prices || {}).some(prices => (
isRecord(prices)
&& Object.values(prices).some(price => toFinitePrice(price) !== null)
))) return true
return (catalog.image_output_price_ranges || []).some(range => (
isRecord(range)
&& isRecord(range.prices)
&& Object.values(range.prices).some(price => toFinitePrice(price) !== null)
))
})
}
export function tieredPricingHasCacheTtl(
pricing: TieredPricingConfig | null | undefined,
ttlMinutes: number,
): boolean {
return pricingCatalogs(pricing).some(catalog => (
Array.isArray(catalog.tiers)
&& catalog.tiers.some(tier => (
Array.isArray(tier.cache_ttl_pricing)
&& tier.cache_ttl_pricing.some(entry => entry.ttl_minutes === ttlMinutes)
))
))
}
function toFinitePrice(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : null
}
return null
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}
@@ -210,30 +210,228 @@
<div class="text-xs font-medium text-foreground">
执行动作
</div>
<div class="text-[11px] text-muted-foreground">
代理节点(仅“配置代理”动作生效)
</div>
<ProxyNodeSelect
:model-value="proxyNodeIdForAction"
trigger-class="h-8"
@update:model-value="(v: string) => proxyNodeIdForAction = v"
/>
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-1">
<Button
v-for="item in ACTION_OPTIONS"
:key="item.value"
class="h-8 w-full px-3 text-xs"
class="h-9 w-full px-3 text-xs"
:variant="getActionButtonVariant(item)"
:disabled="!canExecuteSpecifiedAction(item.value)"
@click="confirmAndExecuteAction(item.value)"
:disabled="!canSelectAction(item.value)"
@click="handleActionButtonClick(item.value)"
>
{{ item.label }}
</Button>
</div>
<div
v-if="selectedAction === 'set_proxy'"
class="space-y-2 border-t border-border/60 pt-3"
>
<div class="text-[11px] text-muted-foreground">选择要绑定的代理节点</div>
<ProxyNodeSelect
:model-value="proxyNodeIdForAction"
trigger-class="h-9"
@update:model-value="(v: string) => proxyNodeIdForAction = v"
/>
<Button
class="h-9 w-full text-xs"
:disabled="!canExecuteSpecifiedAction('set_proxy')"
@click="confirmAndExecuteAction('set_proxy')"
>
应用代理设置
</Button>
</div>
</div>
</div>
</div>
<section
v-if="selectedAction === 'update_settings'"
class="space-y-3 rounded-lg border border-primary/25 bg-primary/5 p-3 sm:p-4"
>
<div class="flex flex-wrap items-start justify-between gap-2">
<div>
<h3 class="text-sm font-semibold">更多设置</h3>
<p class="text-[11px] text-muted-foreground">仅更新已勾选字段,未勾选配置保持不变</p>
</div>
<Badge variant="outline" class="tabular-nums">已选 {{ selectedSettingsCount }} 项</Badge>
</div>
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<div class="space-y-2 rounded-md border bg-background p-3">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.internal_priority"
@update:checked="settingsSelection.internal_priority = $event === true"
/>
<Label class="text-xs">优先级</Label>
</div>
<Input
v-model.number="settingsDraft.internal_priority"
type="number"
min="0"
class="h-9"
:disabled="!settingsSelection.internal_priority"
/>
</div>
<div class="space-y-2 rounded-md border bg-background p-3">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.rpm_limit"
@update:checked="settingsSelection.rpm_limit = $event === true"
/>
<Label class="text-xs">RPM 限制</Label>
</div>
<Input
:model-value="settingsDraft.rpm_limit ?? ''"
type="number"
min="1"
max="10000"
class="h-9"
placeholder="留空为自适应"
:disabled="!settingsSelection.rpm_limit"
@update:model-value="settingsDraft.rpm_limit = parseNullableNumberInput($event, { min: 1, max: 10000 })"
/>
</div>
<div class="space-y-2 rounded-md border bg-background p-3">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.concurrent_limit"
@update:checked="settingsSelection.concurrent_limit = $event === true"
/>
<Label class="text-xs">并发请求上限</Label>
</div>
<Input
:model-value="settingsDraft.concurrent_limit ?? ''"
type="number"
min="0"
class="h-9"
placeholder="留空为不限制"
:disabled="!settingsSelection.concurrent_limit"
@update:model-value="settingsDraft.concurrent_limit = parseNullableNumberInput($event, { min: 0 })"
/>
</div>
<div class="space-y-2 rounded-md border bg-background p-3">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.cache_ttl_minutes"
@update:checked="settingsSelection.cache_ttl_minutes = $event === true"
/>
<Label class="text-xs">缓存 TTL(分钟)</Label>
</div>
<Input
:model-value="settingsDraft.cache_ttl_minutes"
type="number"
min="0"
max="60"
class="h-9"
:disabled="!settingsSelection.cache_ttl_minutes"
@update:model-value="settingsDraft.cache_ttl_minutes = parseNumberInput($event, { min: 0, max: 60 }) ?? 5"
/>
</div>
<div class="space-y-2 rounded-md border bg-background p-3">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.max_probe_interval_minutes"
@update:checked="settingsSelection.max_probe_interval_minutes = $event === true"
/>
<Label class="text-xs">熔断探测(分钟)</Label>
</div>
<Input
:model-value="settingsDraft.max_probe_interval_minutes"
type="number"
min="0"
max="32"
class="h-9"
:disabled="!settingsSelection.max_probe_interval_minutes"
@update:model-value="settingsDraft.max_probe_interval_minutes = parseNumberInput($event, { min: 0, max: 32 }) ?? 32"
/>
</div>
<div class="space-y-2 rounded-md border bg-background p-3">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.is_active"
@update:checked="settingsSelection.is_active = $event === true"
/>
<Label class="text-xs">启用状态</Label>
</div>
<Select v-model="settingsStatus" :disabled="!settingsSelection.is_active">
<SelectTrigger class="h-9"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="enabled">启用</SelectItem>
<SelectItem value="disabled">停用</SelectItem>
</SelectContent>
</Select>
</div>
<div class="space-y-2 rounded-md border bg-background p-3 sm:col-span-2">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.proxy_node_id"
@update:checked="settingsSelection.proxy_node_id = $event === true"
/>
<Label class="text-xs">账号代理</Label>
</div>
<div class="grid gap-2 sm:grid-cols-[9rem_minmax(0,1fr)]">
<Select v-model="settingsDraft.proxy_mode" :disabled="!settingsSelection.proxy_node_id">
<SelectTrigger class="h-9"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="set">设置节点</SelectItem>
<SelectItem value="clear">清除代理</SelectItem>
</SelectContent>
</Select>
<ProxyNodeSelect
v-if="settingsDraft.proxy_mode === 'set'"
:model-value="settingsDraft.proxy_node_id"
trigger-class="h-9"
:class="!settingsSelection.proxy_node_id ? 'pointer-events-none opacity-50' : ''"
@update:model-value="(value: string) => settingsDraft.proxy_node_id = value"
/>
<div
v-else
class="flex h-9 items-center rounded-md border bg-muted/30 px-3 text-xs text-muted-foreground"
>
回退到 Provider 默认代理
</div>
</div>
</div>
<div class="space-y-2 rounded-md border bg-background p-3">
<div class="flex min-h-6 items-center gap-2">
<Checkbox
:checked="settingsSelection.note"
@update:checked="settingsSelection.note = $event === true"
/>
<Label class="text-xs">备注</Label>
</div>
<Input
v-model="settingsDraft.note"
class="h-9"
placeholder="留空清除备注"
:disabled="!settingsSelection.note"
/>
</div>
</div>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<p class="min-h-5 text-xs text-destructive">
{{ settingsErrors[0] || '' }}
</p>
<Button
class="min-h-10 sm:min-w-36"
:disabled="!canExecuteSpecifiedAction('update_settings')"
@click="confirmAndExecuteAction('update_settings')"
>
应用更多设置
</Button>
</div>
</section>
<div
v-if="executing && progressTotal > 0"
class="space-y-1"
@@ -270,8 +468,20 @@
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { Dialog, Button, Input, Checkbox, Badge } from '@/components/ui'
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import {
Badge,
Button,
Checkbox,
Dialog,
Input,
Label,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui'
import ProxyNodeSelect from '@/features/providers/components/ProxyNodeSelect.vue'
import { RefreshCw, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-vue-next'
import { useToast } from '@/composables/useToast'
@@ -302,6 +512,13 @@ import {
} from '@/utils/providerKeyStatus'
import { getQuotaDisplayText } from '@/utils/providerKeyQuota'
import { runChunkedBatchAction } from '@/utils/batchAction'
import { parseNullableNumberInput, parseNumberInput } from '@/utils/form'
import {
buildPoolKeySettingsPatch,
createPoolKeyBatchSettingSelection,
createPoolKeyBatchSettingsDraft,
validatePoolKeyBatchSettings,
} from '@/features/pool/utils/poolKeyBatchSettings'
type QuickSelectorValue =
| 'banned'
@@ -323,6 +540,7 @@ type BatchActionValue =
| 'refresh_quota'
| 'clear_proxy'
| 'set_proxy'
| 'update_settings'
| 'enable'
| 'disable'
@@ -376,6 +594,7 @@ const ACTION_OPTIONS: BatchActionOption[] = [
{ value: 'refresh_quota', label: '刷新额度', hint: '调用额度刷新接口,适合核对最新配额状态。' },
{ value: 'refresh_oauth', label: '刷新 OAuth', hint: '仅对 OAuth 账号有效,非 OAuth 账号会自动跳过。' },
{ value: 'set_proxy', label: '配置代理', hint: '为选中账号绑定独立代理节点。' },
{ value: 'update_settings', label: '更多设置', hint: '选择性修改 RPM、并发、熔断、备注和代理等配置。' },
{ value: 'clear_proxy', label: '清除代理', hint: '移除账号独立代理,回退到提供商默认代理。' },
{ value: 'enable', label: '启用', hint: '批量启用账号,恢复可调度状态。' },
{ value: 'disable', label: '禁用', hint: '批量禁用账号,保留数据但停止调度。' },
@@ -397,6 +616,12 @@ const selectAllFiltered = ref(false)
const searchText = ref('')
const selectedAction = ref<BatchActionValue>('refresh_quota')
const proxyNodeIdForAction = ref('')
const settingsSelection = reactive(createPoolKeyBatchSettingSelection())
const settingsDraft = reactive(createPoolKeyBatchSettingsDraft())
const settingsStatus = computed({
get: () => settingsDraft.is_active ? 'enabled' : 'disabled',
set: (value: string) => { settingsDraft.is_active = value === 'enabled' },
})
const lastResultMessage = ref('')
const progressTotal = ref(0)
const progressDone = ref(0)
@@ -451,6 +676,8 @@ const isCurrentPageFullySelected = computed(() => {
})
const canClearSelection = computed(() => selectAllFiltered.value || selectedKeyIds.value.length > 0)
const activeQuickSelectorSet = computed(() => new Set(activeQuickSelectors.value))
const settingsErrors = computed(() => validatePoolKeyBatchSettings(settingsSelection, settingsDraft))
const selectedSettingsCount = computed(() => Object.values(settingsSelection).filter(Boolean).length)
function sanitizeFileNamePart(value: unknown, fallback: string): string {
const sanitized = String(value || '')
@@ -709,14 +936,33 @@ function toggleQuickSelector(selector: QuickSelectorValue): void {
function canExecuteSpecifiedAction(action: BatchActionValue): boolean {
if (executing.value || loading.value || selectedCount.value === 0) return false
if (action === 'set_proxy') return Boolean(proxyNodeIdForAction.value)
if (action === 'update_settings') return settingsErrors.value.length === 0
return true
}
function canSelectAction(action: BatchActionValue): boolean {
if (executing.value || loading.value) return false
if (action === 'set_proxy' || action === 'update_settings') return true
return selectedCount.value > 0
}
function getActionButtonVariant(option: BatchActionOption): 'default' | 'destructive' | 'outline' {
if (option.destructive) return 'destructive'
if (
option.value === selectedAction.value
&& (option.value === 'set_proxy' || option.value === 'update_settings')
) return 'default'
return 'outline'
}
function handleActionButtonClick(action: BatchActionValue): void {
if (action === 'set_proxy' || action === 'update_settings') {
selectedAction.value = action
return
}
void confirmAndExecuteAction(action)
}
async function confirmAndExecuteAction(action: BatchActionValue): Promise<void> {
selectedAction.value = action
if (selectedCount.value === 0) {
@@ -727,6 +973,10 @@ async function confirmAndExecuteAction(action: BatchActionValue): Promise<void>
warning('请先选择代理节点')
return
}
if (action === 'update_settings' && settingsErrors.value.length > 0) {
warning(settingsErrors.value[0])
return
}
if (!canExecuteSpecifiedAction(action)) return
if (action === 'edit_config') {
@@ -842,6 +1092,10 @@ async function executeAction(actionOverride?: BatchActionValue): Promise<void> {
warning('请先选择代理节点')
return
}
if (selectedAction.value === 'update_settings' && settingsErrors.value.length > 0) {
warning(settingsErrors.value[0])
return
}
executing.value = true
let successCount = 0
@@ -963,7 +1217,7 @@ async function executeAction(actionOverride?: BatchActionValue): Promise<void> {
progressDone.value = Math.min(i + BATCH_SIZE, targetIds.length)
}
} else if (['enable', 'disable', 'clear_proxy', 'set_proxy'].includes(selectedAction.value)) {
} else if (['enable', 'disable', 'clear_proxy', 'set_proxy', 'update_settings'].includes(selectedAction.value)) {
const targetIds = selectedKeys.map((key) => key.key_id)
const BATCH_SIZE = 2000
const totalBatches = Math.ceil(targetIds.length / BATCH_SIZE)
@@ -977,12 +1231,14 @@ async function executeAction(actionOverride?: BatchActionValue): Promise<void> {
const payload = selectedAction.value === 'set_proxy'
? { node_id: proxyNodeIdForAction.value, enabled: true }
: undefined
: selectedAction.value === 'update_settings'
? buildPoolKeySettingsPatch(settingsSelection, settingsDraft)
: undefined
try {
const result = await batchActionPoolKeys(props.providerId, {
key_ids: batch,
action: selectedAction.value as 'enable' | 'disable' | 'clear_proxy' | 'set_proxy',
action: selectedAction.value as 'enable' | 'disable' | 'clear_proxy' | 'set_proxy' | 'update_settings',
...(payload ? { payload } : {}),
})
successCount += result.affected
@@ -1082,6 +1338,8 @@ watch(
activeQuickSelectors.value = []
selectedAction.value = 'refresh_quota'
proxyNodeIdForAction.value = ''
Object.assign(settingsSelection, createPoolKeyBatchSettingSelection())
Object.assign(settingsDraft, createPoolKeyBatchSettingsDraft())
resetSelection(true)
filteredTotal.value = 0
pageKeys.value = []
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import {
buildPoolKeySettingsPatch,
createPoolKeyBatchSettingSelection,
createPoolKeyBatchSettingsDraft,
validatePoolKeyBatchSettings,
} from '../poolKeyBatchSettings'
describe('pool key batch settings', () => {
it('only includes explicitly selected fields', () => {
const selection = createPoolKeyBatchSettingSelection()
const draft = createPoolKeyBatchSettingsDraft()
selection.rpm_limit = true
selection.proxy_node_id = true
draft.rpm_limit = 800
draft.proxy_mode = 'clear'
expect(buildPoolKeySettingsPatch(selection, draft)).toEqual({
rpm_limit: 800,
proxy_node_id: null,
})
})
it('supports adaptive RPM and unlimited concurrency', () => {
const selection = createPoolKeyBatchSettingSelection()
const draft = createPoolKeyBatchSettingsDraft()
selection.rpm_limit = true
selection.concurrent_limit = true
expect(validatePoolKeyBatchSettings(selection, draft)).toEqual([])
expect(buildPoolKeySettingsPatch(selection, draft)).toEqual({
rpm_limit: null,
concurrent_limit: null,
})
})
it('requires a selected field and a proxy node for set mode', () => {
const selection = createPoolKeyBatchSettingSelection()
const draft = createPoolKeyBatchSettingsDraft()
expect(validatePoolKeyBatchSettings(selection, draft)).toEqual(['请至少选择一个要修改的设置'])
selection.proxy_node_id = true
expect(validatePoolKeyBatchSettings(selection, draft)).toEqual(['请选择要设置的代理节点'])
})
})
@@ -0,0 +1,109 @@
import type { PoolKeySettingsPatch } from '@/api/endpoints/pool'
export type PoolKeyBatchSettingField =
| 'internal_priority'
| 'rpm_limit'
| 'concurrent_limit'
| 'cache_ttl_minutes'
| 'max_probe_interval_minutes'
| 'is_active'
| 'note'
| 'proxy_node_id'
export type PoolKeyBatchSettingSelection = Record<PoolKeyBatchSettingField, boolean>
export interface PoolKeyBatchSettingsDraft {
internal_priority: number
rpm_limit: number | null
concurrent_limit: number | null
cache_ttl_minutes: number
max_probe_interval_minutes: number
is_active: boolean
note: string
proxy_mode: 'set' | 'clear'
proxy_node_id: string
}
export function createPoolKeyBatchSettingSelection(): PoolKeyBatchSettingSelection {
return {
internal_priority: false,
rpm_limit: false,
concurrent_limit: false,
cache_ttl_minutes: false,
max_probe_interval_minutes: false,
is_active: false,
note: false,
proxy_node_id: false,
}
}
export function createPoolKeyBatchSettingsDraft(): PoolKeyBatchSettingsDraft {
return {
internal_priority: 50,
rpm_limit: null,
concurrent_limit: null,
cache_ttl_minutes: 5,
max_probe_interval_minutes: 32,
is_active: true,
note: '',
proxy_mode: 'set',
proxy_node_id: '',
}
}
export function validatePoolKeyBatchSettings(
selection: PoolKeyBatchSettingSelection,
draft: PoolKeyBatchSettingsDraft,
): string[] {
const errors: string[] = []
if (!Object.values(selection).some(Boolean)) errors.push('请至少选择一个要修改的设置')
if (selection.internal_priority && (!Number.isInteger(draft.internal_priority) || draft.internal_priority < 0)) {
errors.push('优先级必须是大于等于 0 的整数')
}
if (selection.rpm_limit && draft.rpm_limit !== null && (
!Number.isInteger(draft.rpm_limit) || draft.rpm_limit < 1 || draft.rpm_limit > 10_000
)) {
errors.push('RPM 必须在 1 到 10000 之间,留空表示自适应')
}
if (selection.concurrent_limit && draft.concurrent_limit !== null && (
!Number.isInteger(draft.concurrent_limit) || draft.concurrent_limit < 0
)) {
errors.push('并发上限必须是大于等于 0 的整数')
}
if (selection.cache_ttl_minutes && (
!Number.isInteger(draft.cache_ttl_minutes) || draft.cache_ttl_minutes < 0 || draft.cache_ttl_minutes > 60
)) {
errors.push('缓存 TTL 必须在 0 到 60 分钟之间')
}
if (selection.max_probe_interval_minutes && (
!Number.isInteger(draft.max_probe_interval_minutes)
|| draft.max_probe_interval_minutes < 0
|| draft.max_probe_interval_minutes > 32
)) {
errors.push('熔断探测必须在 0 到 32 分钟之间')
}
if (selection.proxy_node_id && draft.proxy_mode === 'set' && !draft.proxy_node_id.trim()) {
errors.push('请选择要设置的代理节点')
}
return errors
}
export function buildPoolKeySettingsPatch(
selection: PoolKeyBatchSettingSelection,
draft: PoolKeyBatchSettingsDraft,
): PoolKeySettingsPatch {
const patch: PoolKeySettingsPatch = {}
if (selection.internal_priority) patch.internal_priority = draft.internal_priority
if (selection.rpm_limit) patch.rpm_limit = draft.rpm_limit
if (selection.concurrent_limit) patch.concurrent_limit = draft.concurrent_limit
if (selection.cache_ttl_minutes) patch.cache_ttl_minutes = draft.cache_ttl_minutes
if (selection.max_probe_interval_minutes) {
patch.max_probe_interval_minutes = draft.max_probe_interval_minutes
}
if (selection.is_active) patch.is_active = draft.is_active
if (selection.note) patch.note = draft.note.trim() || null
if (selection.proxy_node_id) {
patch.proxy_node_id = draft.proxy_mode === 'clear' ? null : draft.proxy_node_id.trim()
}
return patch
}
@@ -1051,7 +1051,8 @@ 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 {
createEndpoint,
@@ -3378,20 +3379,26 @@ async function handleToggleFormatConversion(endpoint: ProviderEndpoint) {
// 获取上游流式按钮的当前状态(优先使用编辑状态)
function getCurrentUpstreamStreamPolicy(endpoint: ProviderEndpoint): string {
if (isUpstreamStreamPolicyLocked(endpoint)) return 'force_stream'
const fixedPolicy = getFixedUpstreamStreamPolicy(endpoint)
if (fixedPolicy) return fixedPolicy
const state = endpointEditStates.value[endpoint.id]
return state?.upstreamStreamPolicy ?? getEndpointUpstreamStreamPolicy(endpoint)
}
function getFixedUpstreamStreamPolicy(endpoint: ProviderEndpoint) {
return fixedEndpointUpstreamStreamPolicy(props.provider?.provider_type, endpoint.api_format)
}
function isUpstreamStreamPolicyLocked(endpoint: ProviderEndpoint): boolean {
return (props.provider?.provider_type || '').toLowerCase() === 'codex'
&& normalizeEndpointApiFormat(endpoint.api_format) === 'openai:responses'
return getFixedUpstreamStreamPolicy(endpoint) !== null
}
// 获取上游流式按钮的样式类
function getUpstreamStreamButtonClass(endpoint: ProviderEndpoint): string {
if (isUpstreamStreamPolicyLocked(endpoint)) {
return 'h-7 w-7 text-primary/70 cursor-not-allowed'
const fixedPolicy = getFixedUpstreamStreamPolicy(endpoint)
if (fixedPolicy) {
const color = fixedPolicy === 'force_stream' ? 'text-primary/70' : 'text-destructive/70'
return `h-7 w-7 ${color} cursor-not-allowed`
}
const policy = getCurrentUpstreamStreamPolicy(endpoint)
const base = 'h-7 w-7'
@@ -3402,7 +3409,9 @@ function getUpstreamStreamButtonClass(endpoint: ProviderEndpoint): string {
// 获取上游流式按钮的提示文字
function getUpstreamStreamTooltip(endpoint: ProviderEndpoint): string {
if (isUpstreamStreamPolicyLocked(endpoint)) return legacyT('固定流式(Codex OpenAI Responses,已锁定)')
const fixedPolicy = getFixedUpstreamStreamPolicy(endpoint)
if (fixedPolicy === 'force_stream') return legacyT('Codex Responses 固定流式')
if (fixedPolicy === 'force_non_stream') return legacyT('OpenAI Search 固定非流式')
const policy = getCurrentUpstreamStreamPolicy(endpoint)
if (policy === 'force_stream') return legacyT('固定流式(点击切换为固定非流)')
if (policy === 'force_non_stream') return legacyT('固定非流(点击切换为跟随请求)')
@@ -2,7 +2,7 @@
<Dialog
:model-value="isOpen"
title="获取上游模型"
description="从上游获取所有密钥可用的模型列表。导入的模型需要关联全局模型后才能参与路由。"
description="从上游获取所有密钥可用的模型列表。导入时会创建或复用全局模型,并关联到当前提供商。"
:icon="Layers"
size="2xl"
@update:model-value="handleDialogUpdate"
@@ -135,6 +135,14 @@
>
已存在
</Badge>
<Badge
v-if="model.visibility === 'hide'"
variant="outline"
class="text-[10px] px-1.5 py-0 shrink-0 text-muted-foreground"
title="运行时可调用的内部模型"
>
内部
</Badge>
</div>
<div class="text-[11px] text-muted-foreground/60 font-mono truncate mt-0.5">
{{ model.id }}
@@ -631,38 +631,20 @@ async function loadBalances() {
}
}
const LEGACY_API_FORMAT_MAP: Record<string, string> = {
CLAUDE: 'claude:messages',
CLAUDE_MESSAGES: 'claude:messages',
OPENAI: 'openai:chat',
OPENAI_RESPONSES: 'openai:responses',
OPENAI_RESPONSES_COMPACT: 'openai:responses:compact',
OPENAI_VIDEO: 'openai:video',
GEMINI: 'gemini:generate_content',
GEMINI_GENERATE_CONTENT: 'gemini:generate_content',
GEMINI_VIDEO: 'gemini:video',
GEMINI_FILES: 'gemini:files',
}
function normalizeApiFormatKey(value: string | null | undefined): string {
const raw = String(value || '').trim()
if (!raw) return ''
const normalized = normalizeApiFormatAlias(value)
if (!normalized) return ''
if (raw.includes(':')) {
const [family, kind] = raw.split(':', 2)
const familyNorm = family?.trim().toLowerCase()
const kindNorm = kind?.trim().toLowerCase()
if (familyNorm === 'claude' && ['chat', 'cli', 'messages'].includes(kindNorm)) {
if (normalized.includes(':')) {
const { family, kind } = parseApiFormat(normalized)
if (family === 'claude' && ['chat', 'cli', 'messages'].includes(kind)) {
return 'claude:messages'
}
if (familyNorm === 'gemini' && ['chat', 'cli', 'generate_content'].includes(kindNorm)) {
if (family === 'gemini' && ['chat', 'cli', 'generate_content'].includes(kind)) {
return 'gemini:generate_content'
}
if (familyNorm && kindNorm) return `${familyNorm}:${kindNorm}`
}
const legacy = raw.toUpperCase().replace(/-/g, '_')
return LEGACY_API_FORMAT_MAP[legacy] || raw.toLowerCase()
return normalized
}
function normalizePriorityMap(
@@ -60,12 +60,22 @@
<h3 class="text-sm font-semibold">
{{ legacyT(isKeyManagedProviderType(provider.provider_type) ? '密钥管理' : '账号管理') }}
</h3>
<div class="flex items-center gap-2">
<div class="flex flex-wrap items-center justify-end gap-2">
<Button
v-if="endpoints.length > 0 && provider.provider_type === 'custom'"
variant="outline"
size="sm"
class="h-9"
@click="keyBatchImportDialogOpen = true"
>
<ListPlus class="mr-1.5 h-3.5 w-3.5" />
批量导入
</Button>
<Button
v-if="endpoints.length > 0"
variant="outline"
size="sm"
class="h-8"
class="h-9"
@click="handleAddKeyToFirstEndpoint"
>
<Plus class="w-3.5 h-3.5 mr-1.5" />
@@ -279,7 +289,7 @@
</div>
</div>
<div
v-if="getCodexResetCreditsDisplay(key)"
v-if="getCodexResetCreditAvailableCount(key) !== null"
class="mt-3 border-t border-border/60 pt-2"
>
<div class="flex flex-wrap items-center gap-x-1 gap-y-1 text-[10px] leading-4 text-muted-foreground">
@@ -823,6 +833,16 @@
@saved="handleKeyChanged"
/>
<ProviderKeyBatchImportDialog
v-if="open && provider?.provider_type === 'custom'"
:open="keyBatchImportDialogOpen"
:provider-id="provider.id"
:provider-name="provider.name"
:available-api-formats="availableKeyApiFormats"
@close="keyBatchImportDialogOpen = false"
@saved="handleKeyChanged"
/>
<!-- OAuth 账号对话框 -->
<OAuthAccountDialog
v-if="open && provider"
@@ -913,6 +933,7 @@ import { ref, watch, computed, nextTick } from 'vue'
import {
Plus,
Key,
ListPlus,
Loader2,
GripVertical,
ShieldX,
@@ -951,6 +972,7 @@ import AlertDialog from '@/components/common/AlertDialog.vue'
import AntigravityQuotaDialog from '@/features/providers/components/AntigravityQuotaDialog.vue'
import FailoverRulesDialog from '@/features/providers/components/FailoverRulesDialog.vue'
import ProviderDetailHeader from '@/features/providers/components/ProviderDetailHeader.vue'
import ProviderKeyBatchImportDialog from '@/features/providers/components/ProviderKeyBatchImportDialog.vue'
import ProviderKeyActionCluster from '@/features/providers/components/ProviderKeyActionCluster.vue'
import ProviderKeyIdentityBlock from '@/features/providers/components/ProviderKeyIdentityBlock.vue'
import ProviderMonthlyQuotaCard from '@/features/providers/components/ProviderMonthlyQuotaCard.vue'
@@ -993,10 +1015,6 @@ import type {
} from '@/api/endpoints/types'
import { formatApiFormatShort } from '@/api/endpoints/types/api-format'
import { isOAuthAccountProviderType, isKeyManagedProviderType } from '../utils/providerTypeUtils'
import {
isProviderQuotaAutoRefreshCoolingDown,
markProviderQuotaAutoRefreshAttempt,
} from '../utils/quotaAutoRefreshCooldown'
import { getOAuthOrgBadge } from '@/utils/oauthIdentity'
import { getOAuthRefreshFeedback } from '@/utils/oauthRefreshFeedback'
import { formatCompactNumber } from '@/utils/format'
@@ -1018,10 +1036,12 @@ import {
} from '@/utils/providerKeyStatus'
import { getGeminiCliAccountCreditsText } from '@/utils/providerKeyQuota'
import {
createCodexResetCreditIdempotencyKey,
formatCodexResetCreditCount as formatCodexResetCreditCountLabel,
formatCodexResetCreditDays,
getCodexResetCreditAvailableCount as getCodexResetCreditAvailableCountFromSnapshot,
getVisibleCodexResetCreditItems as getVisibleCodexResetCreditItemsFromSnapshot,
mergeCodexQuotaDisplays,
} from './codex-reset-credit-display'
// 扩展端点类型,包含密钥列表
@@ -1085,6 +1105,7 @@ const endpointDialogOpen = ref(false)
// 密钥相关状态
const keyFormDialogOpen = ref(false)
const keyBatchImportDialogOpen = ref(false)
const keyPermissionsDialogOpen = ref(false)
const oauthAccountDialogOpen = ref(false)
const oauthKeyEditDialogOpen = ref(false)
@@ -1173,6 +1194,7 @@ const multiplierSaving = ref(false)
const hasBlockingDialogOpen = computed(() =>
endpointDialogOpen.value ||
keyFormDialogOpen.value ||
keyBatchImportDialogOpen.value ||
keyPermissionsDialogOpen.value ||
oauthAccountDialogOpen.value ||
oauthKeyEditDialogOpen.value ||
@@ -1319,6 +1341,7 @@ watch(
// 重置所有对话框状态
endpointDialogOpen.value = false
keyFormDialogOpen.value = false
keyBatchImportDialogOpen.value = false
keyPermissionsDialogOpen.value = false
oauthAccountDialogOpen.value = false
oauthKeyEditDialogOpen.value = false
@@ -1600,7 +1623,7 @@ async function handleRefreshOAuth(key: EndpointAPIKey) {
}
// Antigravity:token 刷新后可能完成了账号激活,触发配额获取
// (不 emit('refresh'),避免触发全局 provider 余额刷新)
void autoRefreshQuotaInBackground({ ignoreCooldown: true })
void autoRefreshQuotaInBackground()
} catch (err: unknown) {
showError(localizedApiError(err, 'Token 刷新失败'), legacyT('错误'))
} finally {
@@ -1673,13 +1696,6 @@ async function handleClearOAuthInvalid(key: EndpointAPIKey) {
}
}
function createCodexResetCreditIdempotencyKey(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID()
}
throw new Error('浏览器不支持 crypto.randomUUID,无法生成安全幂等 ID')
}
function codexResetCreditOutcomeFeedback(
result: Awaited<ReturnType<typeof consumeCodexResetCredit>>,
): { tone: 'success' | 'warning'; message: string } {
@@ -1951,20 +1967,6 @@ function getCodexQuotaDisplayFromSnapshot(quota: QuotaStatusSnapshot | null | un
return Object.keys(display).length > 0 ? display : null
}
function getCodexQuotaDisplayUpdatedAt(display: CodexUpstreamMetadata | null | undefined): number | null {
const updatedAt = Number(display?.updated_at)
return Number.isFinite(updatedAt) ? updatedAt : null
}
function codexDisplayHasUsage(display: CodexUpstreamMetadata | null | undefined): boolean {
return !!display && (
display.primary_used_percent !== undefined
|| display.secondary_used_percent !== undefined
|| display.spark_primary_used_percent !== undefined
|| display.spark_secondary_used_percent !== undefined
)
}
function codexDisplayHasResetCredits(display: CodexUpstreamMetadata | null | undefined): boolean {
const count = display?.reset_credits?.available_count
return typeof count === 'number' && Number.isFinite(count)
@@ -1973,20 +1975,7 @@ function codexDisplayHasResetCredits(display: CodexUpstreamMetadata | null | und
function getCodexQuotaDisplay(key: EndpointAPIKey): CodexUpstreamMetadata | null {
const snapshotDisplay = getCodexQuotaDisplayFromSnapshot(getQuotaSnapshotForProvider(key, 'codex'))
const metadataDisplay = getCodexQuotaDisplayFromMetadata(key.upstream_metadata?.codex)
if (!snapshotDisplay) return metadataDisplay
if (!metadataDisplay) return snapshotDisplay
if (!codexDisplayHasUsage(snapshotDisplay) && codexDisplayHasUsage(metadataDisplay)) {
return metadataDisplay
}
const snapshotUpdatedAt = getCodexQuotaDisplayUpdatedAt(snapshotDisplay)
const metadataUpdatedAt = getCodexQuotaDisplayUpdatedAt(metadataDisplay)
if (metadataUpdatedAt !== null && (snapshotUpdatedAt === null || metadataUpdatedAt > snapshotUpdatedAt)) {
return metadataDisplay
}
return snapshotDisplay
return mergeCodexQuotaDisplays(snapshotDisplay, metadataDisplay)
}
function hasCodexQuotaDisplayData(key: EndpointAPIKey): boolean {
@@ -2479,7 +2468,7 @@ function shouldAutoRefreshCodexQuota(): boolean {
if (isTokenExpiringSoon(key, now)) return true
// 只要有一个活跃 key 没有配额数据,就刷新一次
// reset-credit 独立于 Token 刷新;这里只按账号配额缓存决定是否后台更新
if (!hasCodexQuotaDisplayData(key)) {
return true
}
@@ -2714,7 +2703,7 @@ function applyQuotaResults(
}
// 通用的自动刷新配额函数(支持 Codex、Gemini CLI、Antigravity、Kiro、Windsurf 和 ChatGPT Web)
async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean } = {}) {
async function autoRefreshQuotaInBackground() {
const providerId = props.providerId
if (!providerId) return
if (refreshingQuota.value) return
@@ -2740,7 +2729,6 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
shouldRefresh = shouldAutoRefreshChatGPTWebQuota()
}
if (!shouldRefresh) return
if (!options.ignoreCooldown && isProviderQuotaAutoRefreshCoolingDown(providerId)) return
let hadCachedQuota = false
if (providerType === 'codex') {
@@ -2760,7 +2748,6 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
}
refreshingQuota.value = true
markProviderQuotaAutoRefreshAttempt(providerId)
try {
const result = await refreshProviderQuota(providerId)
const applied = applyQuotaResults(result.results)
@@ -2804,7 +2791,7 @@ async function handleKeyChanged() {
await Promise.all([loadEndpoints(), loadMappingPreview()])
emit('refresh')
// 添加/修改 key 后自动获取已支持 provider 的配额(新 key 的 upstream_metadata 为空)
void autoRefreshQuotaInBackground({ ignoreCooldown: true })
void autoRefreshQuotaInBackground()
}
// 切换密钥启用状态
@@ -197,7 +197,7 @@
:model-value="form.request_timeout ?? ''"
type="number"
min="1"
max="600"
max="1200"
step="1"
placeholder="300"
@update:model-value="(v) => form.request_timeout = parseNumberInput(v)"
@@ -0,0 +1,585 @@
<template>
<Dialog
:model-value="open"
title="批量导入 Key"
:description="providerName ? `${providerName} · 名称和 Key 均为必填` : '名称和 Key 均为必填'"
:icon="ListPlus"
size="4xl"
persistent
@update:model-value="handleDialogUpdate"
>
<div class="space-y-3.5">
<nav class="grid grid-cols-3 gap-1.5 rounded-xl bg-muted/40 p-1.5" aria-label="批量导入步骤">
<button
v-for="step in steps"
:key="step.id"
type="button"
class="flex min-h-10 items-center justify-center gap-2 rounded-lg px-2 text-xs font-medium transition-[background-color,box-shadow,color,scale] active:scale-[0.96] disabled:cursor-default disabled:opacity-50 sm:text-sm"
:class="currentStep === step.id
? 'bg-background text-foreground shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]'
: 'text-muted-foreground hover:bg-background/60 hover:text-foreground'"
:disabled="!canNavigateToStep(step.id)"
@click="goToStep(step.id)"
>
<span
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md text-[10px] tabular-nums"
:class="currentStep === step.id ? 'bg-foreground text-background' : 'bg-muted text-muted-foreground'"
>{{ step.id }}</span>
<span class="truncate">{{ step.label }}</span>
</button>
</nav>
<section
v-if="currentStep === 1"
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
>
<header class="flex min-h-14 items-center justify-between gap-3 border-b border-border/60 bg-muted/15 px-4 py-3">
<div class="flex min-w-0 items-center gap-3">
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">1</span>
<div class="min-w-0">
<h3 class="text-balance text-sm font-semibold text-foreground">粘贴名称与 Key</h3>
<p class="text-pretty text-[11px] leading-4 text-muted-foreground">每行一条,仅接受四个短横线分隔</p>
</div>
</div>
<Badge
:variant="parsed.errors.length > 0 ? 'destructive' : parsed.items.length > 0 ? 'success' : 'secondary'"
class="shrink-0 tabular-nums"
>
{{ inputStatusText }}
</Badge>
</header>
<div class="min-w-0">
<Label for="provider-key-batch-input" class="sr-only">Key 列表</Label>
<Textarea
id="provider-key-batch-input"
v-model="inputText"
class="h-[280px] min-h-[220px] max-h-[520px] !resize-y !rounded-none !border-0 !bg-transparent !px-4 !py-4 font-mono text-[13px] leading-6 !shadow-none !ring-0 focus-visible:!ring-0"
spellcheck="false"
placeholder="主账号----sk-xxxx&#10;备用账号----sk-yyyy"
/>
<div
v-if="parsed.errors.length > 0"
class="mx-4 mb-3 space-y-1 rounded-lg bg-destructive/5 px-3 py-2 text-[11px] text-destructive ring-1 ring-destructive/20"
>
<div
v-for="(item, index) in parsed.errors.slice(0, 6)"
:key="`${item.lineNumber}-${index}`"
>
{{ item.lineNumber ? `第 ${item.lineNumber} 行:` : '' }}{{ item.message }}
</div>
<div v-if="parsed.errors.length > 6" class="font-medium">
另有 {{ parsed.errors.length - 6 }} 个问题
</div>
</div>
<div class="flex flex-wrap items-center gap-2 border-t border-border/50 bg-muted/10 px-4 py-2.5 text-[11px] text-muted-foreground">
<span class="rounded-md bg-muted px-2 py-1 font-mono text-foreground/80">名称----Key</span>
<span>名称和 Key 都不能为空</span>
<span class="ml-auto hidden tabular-nums sm:inline">已识别 {{ parsed.items.length }} 条</span>
</div>
</div>
</section>
<section
v-else-if="currentStep === 2"
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
>
<header class="flex min-h-[72px] items-center gap-3 px-4 py-3">
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">
2
</span>
<span class="min-w-0 flex-1">
<span class="block text-sm font-semibold">统一配置</span>
<span class="mt-1 flex flex-wrap gap-1.5">
<span
v-for="item in settingsSummaryItems"
:key="item"
class="rounded-md bg-muted px-2 py-0.5 text-[10px] leading-4 text-muted-foreground"
>{{ item }}</span>
</span>
</span>
<Badge :variant="selectedApiFormats.length > 0 ? 'success' : 'destructive'" class="ml-auto shrink-0 tabular-nums">
{{ selectedApiFormats.length }} 种格式
</Badge>
</header>
<div class="border-t border-border/60 bg-muted/10 p-3 sm:p-4">
<ProviderKeyImportSettingsFields
:auth-type="authType"
:api-formats="selectedApiFormats"
:settings="settings"
:available-api-formats="availableApiFormats"
@update:auth-type="authType = $event"
@update:api-formats="selectedApiFormats = $event"
@update:settings="updateGlobalSettings"
/>
</div>
</section>
<section
v-else
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
>
<header class="flex min-h-[72px] items-center gap-3 border-b border-border/60 bg-muted/15 px-4 py-3">
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">3</span>
<div class="min-w-0 flex-1">
<h3 class="text-balance text-sm font-semibold">逐项确认</h3>
<p class="text-pretty text-[11px] leading-4 text-muted-foreground">展开任意 Key 可修改内容或设置单独配置</p>
</div>
<div class="shrink-0 text-right text-[11px] text-muted-foreground">
<div><span class="font-semibold tabular-nums text-foreground">{{ reviewItems.length }}</span> 个 Key</div>
<div v-if="customizedItemCount > 0"><span class="tabular-nums">{{ customizedItemCount }}</span> 个单独配置</div>
</div>
</header>
<div
v-if="reviewErrorItemCount > 0"
class="border-b border-destructive/15 bg-destructive/5 px-4 py-2 text-xs text-destructive"
>
{{ reviewErrorItemCount }} 个 Key 需要修正后才能导入
</div>
<div class="max-h-[min(52vh,520px)] divide-y divide-border/50 overflow-y-auto overscroll-contain">
<article
v-for="entry in pagedReviewItems"
:key="entry.item.lineNumber"
class="bg-background"
>
<div class="flex min-h-14 items-center gap-3 px-3 py-2 sm:px-4">
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-muted text-[10px] tabular-nums text-muted-foreground">
{{ entry.index + 1 }}
</span>
<div class="min-w-0 flex-1">
<div class="flex min-w-0 items-center gap-2">
<span class="truncate text-xs font-semibold">{{ entry.item.name || '未填写名称' }}</span>
<Badge
v-if="reviewErrorsByIndex.has(entry.index)"
variant="destructive"
class="shrink-0 text-[10px]"
>需修正</Badge>
</div>
<div class="mt-0.5 truncate font-mono text-[10px] text-muted-foreground">{{ maskSecret(entry.item.apiKey) }}</div>
</div>
<div class="hidden shrink-0 items-center gap-1.5 sm:flex">
<span class="rounded-md bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">{{ effectiveAuthLabel(entry.item) }}</span>
<span class="rounded-md bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">{{ effectiveFormatCount(entry.item) }} 种格式</span>
<span
class="rounded-md px-2 py-0.5 text-[10px]"
:class="entry.item.customized ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
>{{ entry.item.customized ? '单独配置' : '统一配置' }}</span>
</div>
<button
type="button"
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-[background-color,color,scale] hover:bg-muted hover:text-foreground active:scale-[0.96]"
:aria-label="`编辑 ${entry.item.name || `第 ${entry.index + 1} 项`}`"
:title="editingItemIndex === entry.index ? '收起编辑' : '编辑此 Key'"
@click="toggleItemEditor(entry.index)"
>
<Pencil class="h-4 w-4" />
</button>
</div>
<div
v-if="editingItemIndex === entry.index"
class="space-y-4 border-t border-border/50 bg-muted/10 p-3 sm:p-4"
>
<div class="grid gap-3 sm:grid-cols-2">
<div class="space-y-1.5">
<Label class="text-xs">名称</Label>
<Input v-model="entry.item.name" class="h-10" placeholder="必填" />
</div>
<div class="space-y-1.5">
<Label class="text-xs">Key</Label>
<Input v-model="entry.item.apiKey" class="h-10 font-mono text-xs" placeholder="必填" />
</div>
</div>
<div class="flex min-h-12 items-center justify-between gap-3 rounded-lg bg-background px-3 shadow-[0_0_0_1px_rgb(0_0_0/0.06)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]">
<div>
<div class="text-xs font-medium">单独配置此 Key</div>
<div class="text-[11px] text-muted-foreground">开启后覆盖第二步中的统一配置</div>
</div>
<Switch
:model-value="entry.item.customized"
@update:model-value="setItemCustomized(entry.item, $event)"
/>
</div>
<ProviderKeyImportSettingsFields
v-if="entry.item.customized"
:auth-type="entry.item.authType"
:api-formats="entry.item.apiFormats"
:settings="entry.item.settings"
:available-api-formats="availableApiFormats"
@update:auth-type="entry.item.authType = $event"
@update:api-formats="entry.item.apiFormats = $event"
@update:settings="entry.item.settings = $event"
/>
<div
v-if="reviewErrorsByIndex.has(entry.index)"
class="space-y-1 rounded-lg bg-destructive/5 px-3 py-2 text-[11px] text-destructive"
>
<div v-for="message in reviewErrorsByIndex.get(entry.index)" :key="message">{{ message }}</div>
</div>
</div>
</article>
</div>
<div
v-if="reviewPageCount > 1"
class="flex min-h-12 items-center justify-between gap-3 border-t border-border/60 bg-muted/10 px-3 sm:px-4"
>
<Button variant="ghost" size="sm" class="h-9" :disabled="reviewPage === 1" @click="changeReviewPage(reviewPage - 1)">
<ChevronLeft class="mr-1 h-4 w-4" />
上一页
</Button>
<span class="text-[11px] tabular-nums text-muted-foreground">{{ reviewPage }} / {{ reviewPageCount }}</span>
<Button variant="ghost" size="sm" class="h-9" :disabled="reviewPage === reviewPageCount" @click="changeReviewPage(reviewPage + 1)">
下一页
<ChevronRight class="ml-1 h-4 w-4" />
</Button>
</div>
</section>
</div>
<template #footer>
<div class="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button class="w-full sm:w-auto" variant="outline" :disabled="importing" @click="handleBack">
<ArrowLeft v-if="currentStep > 1" class="mr-2 h-4 w-4" />
{{ currentStep === 1 ? '取消' : '上一步' }}
</Button>
<Button class="w-full sm:w-auto" :disabled="primaryActionDisabled" @click="handlePrimaryAction">
<Loader2 v-if="importing" class="mr-2 h-4 w-4 animate-spin" />
<ListPlus v-else-if="currentStep === 3" class="mr-2 h-4 w-4" />
<ArrowRight v-else class="mr-2 h-4 w-4" />
{{ primaryActionLabel }}
</Button>
</div>
</template>
</Dialog>
</template>
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import {
ArrowLeft,
ArrowRight,
ChevronLeft,
ChevronRight,
ListPlus,
Loader2,
Pencil,
} from 'lucide-vue-next'
import {
Badge,
Button,
Dialog,
Input,
Label,
Switch,
Textarea,
} from '@/components/ui'
import ProviderKeyImportSettingsFields from './ProviderKeyImportSettingsFields.vue'
import { batchImportPoolKeys, type PoolKeySettingsPatch } from '@/api/endpoints/pool'
import { useToast } from '@/composables/useToast'
import { parseApiError } from '@/utils/errorParser'
import { parseProviderKeyBatchImport } from '@/features/providers/utils/providerKeyBatchImport'
type WizardStep = 1 | 2 | 3
type AuthType = 'api_key' | 'bearer'
type ImportSettings = Required<Pick<PoolKeySettingsPatch,
'internal_priority' | 'rpm_limit' | 'concurrent_limit' | 'cache_ttl_minutes'
| 'max_probe_interval_minutes' | 'is_active' | 'note' | 'proxy_node_id'
>>
interface ReviewImportItem {
lineNumber: number
name: string
apiKey: string
customized: boolean
authType: AuthType
apiFormats: string[]
settings: ImportSettings
}
const REVIEW_PAGE_SIZE = 50
const steps: ReadonlyArray<{ id: WizardStep; label: string }> = [
{ id: 1, label: '导入内容' },
{ id: 2, label: '统一配置' },
{ id: 3, label: '逐项确认' },
]
const props = defineProps<{
open: boolean
providerId: string
providerName?: string
availableApiFormats: string[]
}>()
const emit = defineEmits<{
close: []
saved: []
}>()
const { success, warning, error: showError } = useToast()
const currentStep = ref<WizardStep>(1)
const inputText = ref('')
const importing = ref(false)
const authType = ref<AuthType>('api_key')
const selectedApiFormats = ref<string[]>([])
const settings = reactive<ImportSettings>(createDefaultSettings())
const reviewItems = ref<ReviewImportItem[]>([])
const reviewPage = ref(1)
const editingItemIndex = ref<number | null>(null)
const parsed = computed(() => parseProviderKeyBatchImport(inputText.value))
const canContinueInput = computed(() => (
parsed.value.items.length > 0 && parsed.value.errors.length === 0
))
const canContinueSettings = computed(() => selectedApiFormats.value.length > 0)
const inputStatusText = computed(() => {
if (parsed.value.errors.length > 0) return `${parsed.value.errors.length} 个问题`
if (parsed.value.items.length > 0) return `${parsed.value.items.length} 条有效`
return '等待输入'
})
const reviewErrorsByIndex = computed(() => {
const errors = new Map<number, string[]>()
const seenNames = new Set<string>()
const seenKeys = new Set<string>()
reviewItems.value.forEach((item, index) => {
const messages: string[] = []
const name = item.name.trim()
const apiKey = item.apiKey.trim()
if (!name) messages.push('名称不能为空')
else if (name.length > 100) messages.push('名称不能超过 100 个字符')
else if (seenNames.has(name)) messages.push('名称与前面的 Key 重复')
else seenNames.add(name)
if (!apiKey) messages.push('Key 不能为空')
else if (seenKeys.has(apiKey)) messages.push('Key 与前面的 Key 重复')
else seenKeys.add(apiKey)
if (item.customized && item.apiFormats.length === 0) {
messages.push('单独配置时至少选择一种 API 格式')
}
if (messages.length > 0) errors.set(index, messages)
})
return errors
})
const reviewErrorItemCount = computed(() => reviewErrorsByIndex.value.size)
const customizedItemCount = computed(() => (
reviewItems.value.filter(item => item.customized).length
))
const reviewPageCount = computed(() => (
Math.max(1, Math.ceil(reviewItems.value.length / REVIEW_PAGE_SIZE))
))
const pagedReviewItems = computed(() => {
const start = (reviewPage.value - 1) * REVIEW_PAGE_SIZE
return reviewItems.value
.slice(start, start + REVIEW_PAGE_SIZE)
.map((item, offset) => ({ item, index: start + offset }))
})
const canImport = computed(() => (
!importing.value
&& reviewItems.value.length > 0
&& reviewErrorsByIndex.value.size === 0
&& canContinueSettings.value
))
const primaryActionDisabled = computed(() => {
if (importing.value) return true
if (currentStep.value === 1) return !canContinueInput.value
if (currentStep.value === 2) return !canContinueSettings.value
return !canImport.value
})
const primaryActionLabel = computed(() => {
if (importing.value) return '正在导入...'
if (currentStep.value === 1) return '下一步:统一配置'
if (currentStep.value === 2) return '下一步:逐项确认'
return `导入 ${reviewItems.value.length} 个 Key`
})
const settingsSummaryItems = computed(() => {
const rpm = settings.rpm_limit == null ? 'RPM 自适应' : `RPM ${settings.rpm_limit}`
const concurrent = settings.concurrent_limit == null || settings.concurrent_limit === 0
? '不限并发'
: `并发 ${settings.concurrent_limit}`
const proxy = settings.proxy_node_id ? '独立代理' : '沿用 Provider 代理'
return [authType.value === 'bearer' ? 'Bearer' : 'API Key', rpm, concurrent, proxy]
})
watch(
() => props.open,
(open) => {
if (!open) return
currentStep.value = 1
inputText.value = ''
importing.value = false
authType.value = 'api_key'
selectedApiFormats.value = [...props.availableApiFormats]
Object.assign(settings, createDefaultSettings())
reviewItems.value = []
reviewPage.value = 1
editingItemIndex.value = null
},
{ immediate: true },
)
watch(inputText, () => {
reviewItems.value = []
reviewPage.value = 1
editingItemIndex.value = null
})
function createDefaultSettings(): ImportSettings {
return {
internal_priority: 50,
rpm_limit: null,
concurrent_limit: null,
cache_ttl_minutes: 5,
max_probe_interval_minutes: 32,
is_active: true,
note: '',
proxy_node_id: '',
}
}
function copySettings(source: ImportSettings): ImportSettings {
return { ...source }
}
function buildSettingsPayload(
source: ImportSettings,
includeEmptyProxy = false,
): PoolKeySettingsPatch {
return {
internal_priority: source.internal_priority,
rpm_limit: source.rpm_limit,
concurrent_limit: source.concurrent_limit,
cache_ttl_minutes: source.cache_ttl_minutes,
max_probe_interval_minutes: source.max_probe_interval_minutes,
is_active: source.is_active,
note: source.note.trim() || null,
...((source.proxy_node_id || includeEmptyProxy)
? { proxy_node_id: source.proxy_node_id || null }
: {}),
}
}
function handleDialogUpdate(value: boolean): void {
if (!value) emit('close')
}
function canNavigateToStep(step: WizardStep): boolean {
return step <= currentStep.value
}
function goToStep(step: WizardStep): void {
if (canNavigateToStep(step)) currentStep.value = step
}
function handleBack(): void {
if (currentStep.value === 1) {
emit('close')
return
}
currentStep.value = (currentStep.value - 1) as WizardStep
}
function handlePrimaryAction(): void {
if (primaryActionDisabled.value) return
if (currentStep.value === 1) {
currentStep.value = 2
return
}
if (currentStep.value === 2) {
prepareReviewItems()
currentStep.value = 3
return
}
void submitImport()
}
function prepareReviewItems(): void {
if (reviewItems.value.length > 0) return
reviewItems.value = parsed.value.items.map(item => ({
lineNumber: item.lineNumber,
name: item.name,
apiKey: item.apiKey,
customized: false,
authType: authType.value,
apiFormats: [...selectedApiFormats.value],
settings: copySettings(settings),
}))
reviewPage.value = 1
editingItemIndex.value = null
}
function toggleItemEditor(index: number): void {
editingItemIndex.value = editingItemIndex.value === index ? null : index
}
function setItemCustomized(item: ReviewImportItem, customized: boolean): void {
item.customized = customized
if (!customized) return
item.authType = authType.value
item.apiFormats = [...selectedApiFormats.value]
item.settings = copySettings(settings)
}
function changeReviewPage(page: number): void {
reviewPage.value = Math.min(Math.max(page, 1), reviewPageCount.value)
editingItemIndex.value = null
}
function effectiveAuthLabel(item: ReviewImportItem): string {
const resolved = item.customized ? item.authType : authType.value
return resolved === 'bearer' ? 'Bearer' : 'API Key'
}
function effectiveFormatCount(item: ReviewImportItem): number {
return item.customized ? item.apiFormats.length : selectedApiFormats.value.length
}
function updateGlobalSettings(nextSettings: ImportSettings): void {
Object.assign(settings, nextSettings)
}
function maskSecret(secret: string): string {
if (secret.length <= 10) return `${secret.slice(0, 3)}•••`
return `${secret.slice(0, 6)}••••${secret.slice(-4)}`
}
async function submitImport(): Promise<void> {
if (!canImport.value) return
importing.value = true
try {
const result = await batchImportPoolKeys(props.providerId, {
keys: reviewItems.value.map(item => ({
name: item.name.trim(),
api_key: item.apiKey.trim(),
auth_type: item.customized ? item.authType : authType.value,
...(item.customized
? {
api_formats: item.apiFormats,
settings: buildSettingsPayload(item.settings, true),
}
: {}),
})),
api_formats: selectedApiFormats.value,
settings: buildSettingsPayload(settings),
})
if (result.imported > 0) emit('saved')
if (result.errors.length > 0) {
warning(`已导入 ${result.imported} 个,${result.errors.length} 个失败`)
return
}
success(`已导入 ${result.imported} 个 Key`)
emit('close')
} catch (error) {
showError(parseApiError(error, '批量导入 Key 失败'))
} finally {
importing.value = false
}
}
</script>
@@ -0,0 +1,181 @@
<template>
<div class="space-y-4">
<div class="space-y-2">
<Label class="text-xs font-medium">支持的 API 格式</Label>
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
<label
v-for="format in availableApiFormats"
:key="format"
class="flex min-h-10 cursor-pointer items-center gap-2 rounded-lg bg-background px-3 text-xs transition-[box-shadow,background-color]"
:class="apiFormats.includes(format)
? 'bg-primary/5 shadow-[0_0_0_1px_rgb(0_0_0/0.10),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.12)]'
: 'shadow-[0_0_0_1px_rgb(0_0_0/0.06)] hover:bg-muted/30 hover:shadow-[0_0_0_1px_rgb(0_0_0/0.10)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]'"
>
<Checkbox
:checked="apiFormats.includes(format)"
@update:checked="(checked) => toggleApiFormat(format, checked === true)"
/>
<span class="truncate">{{ formatApiFormat(format) }}</span>
</label>
</div>
</div>
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<div class="space-y-1.5">
<Label class="text-xs">认证类型</Label>
<Select v-model="authTypeModel">
<SelectTrigger class="h-10">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="api_key">API Key</SelectItem>
<SelectItem value="bearer">Bearer Token</SelectItem>
</SelectContent>
</Select>
</div>
<div class="space-y-1.5">
<Label class="text-xs">优先级</Label>
<Input
:model-value="settings.internal_priority"
type="number"
min="0"
class="h-10"
@update:model-value="updateSetting('internal_priority', parseNumberInput($event, { min: 0 }) ?? 50)"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">RPM 限制</Label>
<Input
:model-value="settings.rpm_limit ?? ''"
type="number"
min="1"
max="10000"
class="h-10"
placeholder="自适应"
@update:model-value="updateSetting('rpm_limit', parseNullableNumberInput($event, { min: 1, max: 10000 }))"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">并发请求上限</Label>
<Input
:model-value="settings.concurrent_limit ?? ''"
type="number"
min="0"
class="h-10"
placeholder="不限制"
@update:model-value="updateSetting('concurrent_limit', parseNullableNumberInput($event, { min: 0 }))"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">缓存 TTL(分钟)</Label>
<Input
:model-value="settings.cache_ttl_minutes"
type="number"
min="0"
max="60"
class="h-10"
@update:model-value="updateSetting('cache_ttl_minutes', parseNumberInput($event, { min: 0, max: 60 }) ?? 5)"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">熔断探测(分钟)</Label>
<Input
:model-value="settings.max_probe_interval_minutes"
type="number"
min="0"
max="32"
class="h-10"
@update:model-value="updateSetting('max_probe_interval_minutes', parseNumberInput($event, { min: 0, max: 32 }) ?? 32)"
/>
</div>
</div>
<div class="grid gap-3 sm:grid-cols-2">
<div class="space-y-1.5">
<Label class="text-xs">代理节点</Label>
<ProxyNodeSelect
:model-value="settings.proxy_node_id"
trigger-class="h-10"
@update:model-value="updateSetting('proxy_node_id', $event)"
/>
</div>
<div class="space-y-1.5">
<Label class="text-xs">备注</Label>
<Input
:model-value="settings.note"
class="h-10"
placeholder="可选"
@update:model-value="updateSetting('note', String($event))"
/>
</div>
</div>
<div class="flex min-h-12 items-center justify-between gap-3 rounded-lg bg-background px-3 shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]">
<div>
<div class="text-xs font-medium">导入后立即启用</div>
<div class="text-[11px] text-muted-foreground">关闭后仍会创建,但不会进入调度</div>
</div>
<Switch
:model-value="settings.is_active"
@update:model-value="updateSetting('is_active', $event)"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import {
Checkbox,
Input,
Label,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Switch,
} from '@/components/ui'
import type { PoolKeySettingsPatch } from '@/api/endpoints/pool'
import { formatApiFormat } from '@/api/endpoints/types/api-format'
import { parseNullableNumberInput, parseNumberInput } from '@/utils/form'
import ProxyNodeSelect from './ProxyNodeSelect.vue'
type AuthType = 'api_key' | 'bearer'
type ImportSettings = Required<Pick<PoolKeySettingsPatch,
'internal_priority' | 'rpm_limit' | 'concurrent_limit' | 'cache_ttl_minutes'
| 'max_probe_interval_minutes' | 'is_active' | 'note' | 'proxy_node_id'
>>
const props = defineProps<{
authType: AuthType
apiFormats: string[]
settings: ImportSettings
availableApiFormats: string[]
}>()
const emit = defineEmits<{
'update:authType': [value: AuthType]
'update:apiFormats': [value: string[]]
'update:settings': [value: ImportSettings]
}>()
const authTypeModel = computed<AuthType>({
get: () => props.authType,
set: value => emit('update:authType', value),
})
function toggleApiFormat(format: string, checked: boolean): void {
const selected = new Set(props.apiFormats)
if (checked) selected.add(format)
else selected.delete(format)
emit('update:apiFormats', props.availableApiFormats.filter(item => selected.has(item)))
}
function updateSetting<Key extends keyof ImportSettings>(
key: Key,
value: ImportSettings[Key],
): void {
emit('update:settings', { ...props.settings, [key]: value })
}
</script>
@@ -321,6 +321,7 @@ import { parseNumberInput, sortResolutionEntries } from '@/utils/form'
import { createModel, updateModel, getProviderModels } from '@/api/endpoints/models'
import { createGlobalModel, listGlobalModels, type GlobalModelResponse } from '@/api/global-models'
import TieredPricingEditor from '@/features/models/components/TieredPricingEditor.vue'
import { tieredPricingHasImageOutputPricing } from '@/features/models/utils/tiered-pricing'
import type { Model, TieredPricingConfig } from '@/api/endpoints'
import {
buildProviderModelCreatePayload,
@@ -572,31 +573,6 @@ function modelSupportsImageGeneration(model: {
|| tieredPricingHasImageOutputPricing(model.effective_tiered_pricing)
}
function tieredPricingHasImageOutputPricing(pricing: TieredPricingConfig | null | undefined): boolean {
if (!pricing) return false
if (toFinitePrice(pricing.image_output_price_default) !== null) return true
if (Object.values(pricing.image_output_prices || {}).some((prices) => {
if (!prices || typeof prices !== 'object') return false
return Object.values(prices).some((price) => toFinitePrice(price) !== null)
})) return true
return (pricing.image_output_price_ranges || []).some((range) => {
if (!range || typeof range !== 'object') return false
const prices = range.prices && typeof range.prices === 'object'
? range.prices
: range as Record<string, unknown>
return Object.values(prices).some((price) => toFinitePrice(price) !== null)
})
}
function toFinitePrice(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : null
}
return null
}
function setImageGenerationEnabled(value: boolean | 'indeterminate') {
const enabled = value === true
imageGenerationExplicitOverride.value = enabled
@@ -812,6 +788,12 @@ async function handleSubmit() {
return
}
const pricingValidationError = tieredPricingEditorRef.value?.getValidationError()
if (pricingValidationError) {
showError(pricingValidationError, '价格配置错误')
return
}
submitting.value = true
try {
// 获取包含自动计算缓存价格的最终数据
@@ -28,7 +28,7 @@
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { computed, onMounted } from 'vue'
import {
Select,
SelectTrigger,
@@ -67,8 +67,10 @@ const nodeOptions = computed(() => {
/** 供父组件调用:启用代理时懒加载节点列表 */
function ensureLoaded() {
proxyNodesStore.ensureLoaded()
return proxyNodesStore.ensureLoaded()
}
onMounted(ensureLoaded)
defineExpose({ ensureLoaded })
</script>
@@ -0,0 +1,52 @@
import { describe, expect, it, vi } from 'vitest'
import { createApp, defineComponent, h } from 'vue'
import ProxyNodeSelect from '@/features/providers/components/ProxyNodeSelect.vue'
import { createI18n } from '@/i18n'
const proxyNodesStore = vi.hoisted(() => ({
loading: false,
nodes: [],
onlineNodes: [],
ensureLoaded: vi.fn(() => Promise.resolve()),
}))
vi.mock('@/stores/proxy-nodes', () => ({
useProxyNodesStore: () => proxyNodesStore,
}))
vi.mock('@/components/ui', async () => {
const { defineComponent, h } = await import('vue')
const passthrough = (name: string) => defineComponent({
name,
setup(_, { slots }) {
return () => h('div', slots.default?.())
},
})
return {
Select: passthrough('SelectStub'),
SelectTrigger: passthrough('SelectTriggerStub'),
SelectValue: passthrough('SelectValueStub'),
SelectContent: passthrough('SelectContentStub'),
SelectItem: passthrough('SelectItemStub'),
}
})
describe('ProxyNodeSelect', () => {
it('loads proxy nodes when mounted', () => {
const root = document.createElement('div')
const app = createApp(defineComponent({
setup() {
return () => h(ProxyNodeSelect, { modelValue: '' })
},
}))
app.use(createI18n())
app.mount(root)
expect(proxyNodesStore.ensureLoaded).toHaveBeenCalledTimes(1)
app.unmount()
})
})
@@ -1,14 +1,45 @@
import { describe, expect, it } from 'vitest'
import {
createCodexResetCreditIdempotencyKey,
formatCodexResetCreditCount,
formatCodexResetCreditDays,
getCodexResetCreditAvailableCount,
getVisibleCodexResetCreditItems,
mergeCodexQuotaDisplays,
} from '@/features/providers/components/codex-reset-credit-display'
import type { QuotaResetCreditsSnapshot } from '@/api/endpoints/types'
describe('codex reset credit display helpers', () => {
it('keeps reset credits and usage windows when snapshot sources are partially populated', () => {
const merged = mergeCodexQuotaDisplays(
{
updated_at: 1_700_000_100,
primary_used_percent: 25,
reset_credits: {
available_count: 2,
},
},
{
updated_at: 1_700_000_000,
secondary_used_percent: 40,
reset_credits: {
credits: [{ id: 'credit-1', expires_at: 1_700_086_400 }],
},
},
)
expect(merged).toMatchObject({
updated_at: 1_700_000_100,
primary_used_percent: 25,
secondary_used_percent: 40,
reset_credits: {
available_count: 2,
credits: [{ id: 'credit-1', expires_at: 1_700_086_400 }],
},
})
})
it('keeps zero available credits displayable but non-positive detail items hidden', () => {
const snapshot: QuotaResetCreditsSnapshot = {
available_count: 0,
@@ -78,4 +109,22 @@ describe('codex reset credit display helpers', () => {
expect(formatCodexResetCreditDays(1)).toBe('1天')
expect(formatCodexResetCreditDays(86_401)).toBe('2天')
})
it('generates a UUID v4 with secure random bytes when randomUUID is unavailable', () => {
const idempotencyKey = createCodexResetCreditIdempotencyKey({
getRandomValues(array) {
array.set(Array.from({ length: 16 }, (_, index) => index))
return array
},
})
expect(idempotencyKey).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f')
})
it('prefers the browser randomUUID implementation when available', () => {
expect(createCodexResetCreditIdempotencyKey({
randomUUID: () => 'existing-random-uuid',
getRandomValues: array => array,
})).toBe('existing-random-uuid')
})
})
@@ -9,6 +9,7 @@ const apiFormats = [
{ value: 'gemini:embedding', default_path: '/v1beta/models/{model}:embedContent' },
{ value: 'gemini:video', default_path: '/v1beta/models/{model}:predictLongRunning' },
{ value: 'openai:responses', default_path: '/v1/responses' },
{ value: 'openai:search', default_path: '/v1/alpha/search' },
{ value: 'openai:embedding', default_path: '/v1/embeddings' },
{ value: 'openai:rerank', default_path: '/v1/rerank' },
{ value: 'openai:image', default_path: '/v1/images/generations' },
@@ -75,6 +76,30 @@ describe('endpoint default paths', () => {
})).toBe('/responses')
})
it('uses the Search path relative to OpenAI and Codex api roots', () => {
expect(getDefaultEndpointBaseUrl({
apiFormat: 'openai:search',
baseUrl: 'https://api.openai.com',
})).toBe('https://api.openai.com/v1')
expect(getDefaultEndpointPath({
apiFormat: 'openai:search',
providerType: 'openai',
baseUrl: 'https://api.openai.com/v1',
apiFormats,
})).toBe('/alpha/search')
expect(getDefaultEndpointBaseUrl({
apiFormat: 'openai:search',
baseUrl: 'https://chatgpt.com/backend-api/codex',
})).toBe('https://chatgpt.com/backend-api/codex')
expect(getDefaultEndpointPath({
apiFormat: 'openai:search',
providerType: 'codex',
baseUrl: 'https://chatgpt.com/backend-api/codex',
apiFormats,
})).toBe('/alpha/search')
})
it('drops /v1 from API-root defaults because base URL is the API root', () => {
expect(getDefaultEndpointPath({
apiFormat: 'openai:chat',
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest'
import { fixedEndpointUpstreamStreamPolicy } from '../endpoint-protocol-policy'
describe('fixedEndpointUpstreamStreamPolicy', () => {
it('uses the fixed Codex transport mode for each protocol', () => {
expect(fixedEndpointUpstreamStreamPolicy('codex', 'openai:responses')).toBe('force_stream')
expect(fixedEndpointUpstreamStreamPolicy('codex', 'openai:search')).toBe('force_non_stream')
})
it('applies Search synchronization by format and keeps other formats configurable', () => {
expect(fixedEndpointUpstreamStreamPolicy('custom', 'openai:search')).toBe('force_non_stream')
expect(fixedEndpointUpstreamStreamPolicy('codex', 'openai:responses:compact')).toBeNull()
})
})
@@ -0,0 +1,43 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
function readSource(path: string): string {
return readFileSync(resolve(process.cwd(), path), 'utf8')
}
describe('provider key batch import UI contract', () => {
it('shows the entry only for custom providers', () => {
const source = readSource('src/features/providers/components/ProviderDetailDrawer.vue')
expect(source).toContain("provider.provider_type === 'custom'")
expect(source).toContain('<ProviderKeyBatchImportDialog')
expect(source).toContain('keyBatchImportDialogOpen')
})
it('uses a three-step flow with per-key review overrides', () => {
const source = readSource('src/features/providers/components/ProviderKeyBatchImportDialog.vue')
expect(source).toContain('parseProviderKeyBatchImport')
expect(source).toContain("{ id: 3, label: '逐项确认' }")
expect(source).toContain('ProviderKeyImportSettingsFields')
expect(source).toContain('REVIEW_PAGE_SIZE')
expect(source).toContain('item.customized')
expect(source).toContain('api_formats: item.apiFormats')
expect(source).toContain('batchImportPoolKeys')
expect(source).not.toContain('MAX_BATCH_IMPORT_KEYS')
const fieldsSource = readSource('src/features/providers/components/ProviderKeyImportSettingsFields.vue')
expect(fieldsSource).toContain('settings.max_probe_interval_minutes')
expect(fieldsSource).toContain('settings.proxy_node_id')
})
it('uses selective update_settings in pool batch management', () => {
const source = readSource('src/features/pool/components/PoolAccountBatchDialog.vue')
expect(source).toContain("selectedAction === 'update_settings'")
expect(source).toContain('buildPoolKeySettingsPatch')
expect(source).toContain("confirmAndExecuteAction('update_settings')")
expect(source).toContain('仅更新已勾选字段')
})
})
@@ -1,8 +1,41 @@
import type {
CodexUpstreamMetadata,
QuotaResetCreditSnapshot,
QuotaResetCreditsSnapshot,
} from '@/api/endpoints/types'
function codexQuotaUpdatedAt(display: CodexUpstreamMetadata | null | undefined): number | null {
const updatedAt = Number(display?.updated_at)
return Number.isFinite(updatedAt) ? updatedAt : null
}
export function mergeCodexQuotaDisplays(
snapshotDisplay: CodexUpstreamMetadata | null | undefined,
metadataDisplay: CodexUpstreamMetadata | null | undefined,
): CodexUpstreamMetadata | null {
if (!snapshotDisplay) return metadataDisplay ?? null
if (!metadataDisplay) return snapshotDisplay
const snapshotUpdatedAt = codexQuotaUpdatedAt(snapshotDisplay)
const metadataUpdatedAt = codexQuotaUpdatedAt(metadataDisplay)
const metadataIsNewer = metadataUpdatedAt !== null
&& (snapshotUpdatedAt === null || metadataUpdatedAt > snapshotUpdatedAt)
const preferred = metadataIsNewer ? metadataDisplay : snapshotDisplay
const fallback = metadataIsNewer ? snapshotDisplay : metadataDisplay
const resetCredits = preferred.reset_credits || fallback.reset_credits
? {
...fallback.reset_credits,
...preferred.reset_credits,
}
: undefined
return {
...fallback,
...preferred,
...(resetCredits ? { reset_credits: resetCredits } : {}),
}
}
export interface CodexResetCreditDisplayItem {
id?: string | null
displayKey: string
@@ -28,6 +61,27 @@ export function formatCodexResetCreditCount(count: number | null | undefined): s
return `共 ${count ?? 0} 次机会`
}
interface CodexResetCreditCrypto {
randomUUID?: () => string
getRandomValues: (array: Uint8Array) => Uint8Array
}
export function createCodexResetCreditIdempotencyKey(
cryptoSource: CodexResetCreditCrypto | undefined = globalThis.crypto,
): string {
const randomUUID = cryptoSource?.randomUUID?.bind(cryptoSource)
if (randomUUID) return randomUUID()
if (!cryptoSource) {
throw new Error('浏览器不支持安全随机数,无法生成幂等 ID')
}
const bytes = cryptoSource.getRandomValues(new Uint8Array(16))
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
function codexResetCreditRemainingSeconds(
item: QuotaResetCreditSnapshot,
snapshot: QuotaResetCreditsSnapshot,
@@ -90,6 +90,7 @@ function usesVersionedApiRootByDefault(apiFormat: string): boolean {
return apiFormat === 'openai:chat'
|| apiFormat === 'openai:responses'
|| apiFormat === 'openai:responses:compact'
|| apiFormat === 'openai:search'
|| apiFormat === 'openai:embedding'
|| apiFormat === 'openai:rerank'
|| apiFormat === 'openai:image'
@@ -129,6 +130,7 @@ function skipsVersionedApiRootDefault(apiFormat: string, baseUrl: string): boole
return false
}
return isDeepSeekApiRoot(baseUrl)
|| isCodexUrl(baseUrl)
|| isBigModelCodingApiRoot(baseUrl)
|| isGoogleOpenAiCompatApiRoot(baseUrl)
|| isVertexOpenAiCompatApiRoot(baseUrl)
@@ -198,6 +200,9 @@ export function getDefaultEndpointPath(params: {
if (normalizedApiFormat === 'openai:responses' && isCodex) {
return '/responses'
}
if (normalizedApiFormat === 'openai:search' && isCodex) {
return '/alpha/search'
}
if (usesVersionedApiRootByDefault(normalizedApiFormat)) {
return stripVersionPrefixForApiRoot(defaultPath)
}
@@ -0,0 +1,19 @@
import { normalizeEndpointApiFormat } from './endpoint-default-paths'
export type FixedUpstreamStreamPolicy = 'force_stream' | 'force_non_stream'
export function fixedEndpointUpstreamStreamPolicy(
providerType: string | null | undefined,
apiFormat: string,
): FixedUpstreamStreamPolicy | null {
const normalizedApiFormat = normalizeEndpointApiFormat(apiFormat)
if (normalizedApiFormat === 'openai:search') return 'force_non_stream'
if (providerType?.trim().toLowerCase() !== 'codex') return null
switch (normalizedApiFormat) {
case 'openai:responses':
return 'force_stream'
default:
return null
}
}
@@ -366,12 +366,12 @@ import { type EndpointAPIKey } from '@/api/endpoints/keys'
import { updateModel } from '@/api/endpoints/models'
import { parseApiError } from '@/utils/errorParser'
import type { ProviderWithEndpointsSummary } from '@/api/endpoints'
import { normalizeApiFormatAlias } from '@/api/endpoints/types/api-format'
import {
buildDefaultModelTestRequestHeaders,
buildDefaultModelTestRequestBody,
isModelTestableApiFormat,
isModelTestableEndpoint,
modelTestMappingScopeMatchesEndpoint,
parseModelTestRequestHeadersDraft,
parseModelTestRequestBodyDraft,
selectPreferredModelTestEndpoint,
@@ -852,16 +852,11 @@ function scopedMappingEndpoints(item: CombinedMapping): ProviderEndpoint[] {
const group = item.group
if (!group) return activeEndpoints.value
const apiFormats = new Set(normalizeStringList(group.apiFormats).map(normalizeApiFormatAlias))
const endpointIds = new Set(normalizeStringList(group.endpointIds))
const matched = activeEndpoints.value.filter((endpoint) => {
const apiFormatMatched = apiFormats.size === 0
|| apiFormats.has(normalizeApiFormatAlias(endpoint.api_format))
const endpointMatched = endpointIds.size === 0 || endpointIds.has(endpoint.id)
return apiFormatMatched && endpointMatched
})
return matched.length > 0 ? matched : activeEndpoints.value
return activeEndpoints.value.filter(endpoint => modelTestMappingScopeMatchesEndpoint(
group.apiFormats,
group.endpointIds,
endpoint,
))
}
// 测试精确映射
@@ -10,6 +10,7 @@ import {
isModelTestableEndpoint,
isModelTestableApiFormat,
listModelTestMappedModelOptions,
modelTestMappingScopeMatchesEndpoint,
normalizeModelTestMappedModelSelection,
selectPreferredModelTestEndpoint,
setModelTestRequestBodyModel,
@@ -97,6 +98,20 @@ describe('buildDefaultModelTestRequestBody', () => {
expect(body.messages).toBeUndefined()
})
it('uses the synchronous OpenAI Search request contract', () => {
const body = JSON.parse(buildDefaultModelTestRequestBody('gpt-5.6-sol', 'openai:search'))
expect(body).toEqual({
id: expect.stringMatching(/^aether-model-test-/),
model: 'gpt-5.6-sol',
input: 'Hello! This is a test message.',
commands: {
search_query: [{ q: 'Hello! This is a test message.' }],
},
max_output_tokens: 256,
})
})
it('uses image generation tools for image models on OpenAI Responses endpoints', () => {
const body = JSON.parse(buildDefaultModelTestRequestBody(
'gpt-image-2',
@@ -177,6 +192,52 @@ describe('buildDefaultModelTestRequestBody', () => {
expect(options).toEqual([])
})
it('uses one-way format permissions for Search mapping options', () => {
const responsesOptions = listModelTestMappedModelOptions({
provider_model_name: 'gpt-5.6-luna',
provider_model_mappings: [{
name: 'gpt-5.6-luna',
priority: 1,
api_formats: ['openai:responses'],
}],
}, {
id: 'search-endpoint',
api_format: 'openai:search',
})
const searchOptions = listModelTestMappedModelOptions({
provider_model_name: 'gpt-5.6-luna',
provider_model_mappings: [{
name: 'gpt-5.6-luna',
priority: 1,
api_formats: ['openai:search'],
}],
}, {
id: 'responses-endpoint',
api_format: 'openai:responses',
})
expect(responsesOptions).toEqual([{ name: 'gpt-5.6-luna', priority: 1 }])
expect(searchOptions).toEqual([])
})
it('keeps explicit mapping scopes strict when no endpoint matches', () => {
expect(modelTestMappingScopeMatchesEndpoint(
['openai:responses'],
['search-endpoint'],
{ id: 'search-endpoint', api_format: 'openai:search' },
)).toBe(true)
expect(modelTestMappingScopeMatchesEndpoint(
['openai:responses'],
['another-endpoint'],
{ id: 'search-endpoint', api_format: 'openai:search' },
)).toBe(false)
expect(modelTestMappingScopeMatchesEndpoint(
['openai:search'],
undefined,
{ id: 'responses-endpoint', api_format: 'openai:responses' },
)).toBe(false)
})
it('keeps the current model selected by default until a mapped model is chosen', () => {
const options = [
{ name: 'MiniMax-M2.7-highspeed', priority: 1 },
@@ -259,7 +320,7 @@ describe('isModelTestableApiFormat', () => {
'gemini:video',
'gemini:files',
' OPENAI:VIDEO ',
])('excludes task and file endpoint formats from model tests: %s', (apiFormat) => {
])('excludes endpoint formats without a model-test request contract: %s', (apiFormat) => {
expect(isModelTestableApiFormat(apiFormat)).toBe(false)
})
@@ -267,6 +328,7 @@ describe('isModelTestableApiFormat', () => {
'openai:chat',
'openai:responses',
'openai:responses:compact',
'openai:search',
'openai:image',
'claude:messages',
'gemini:generate_content',
@@ -379,6 +441,17 @@ describe('isModelTestableEndpoint', () => {
}, keys)).toBe(true)
})
it('uses one-way format permissions for Search endpoint keys', () => {
expect(isModelTestableEndpoint({
api_format: 'openai:search',
is_active: true,
}, [{ api_formats: ['openai:responses'], is_active: true }])).toBe(true)
expect(isModelTestableEndpoint({
api_format: 'openai:responses',
is_active: true,
}, [{ api_formats: ['openai:search'], is_active: true }])).toBe(false)
})
it('lets fixed provider OAuth keys inherit testable endpoint formats', () => {
const keys = [{
api_formats: ['legacy:mismatch'],
@@ -1,4 +1,7 @@
import { normalizeApiFormatAlias } from '@/api/endpoints/types/api-format'
import {
apiFormatPermissionCovers,
normalizeApiFormatAlias,
} from '@/api/endpoints/types/api-format'
import type { ModelTestCapabilities, OpenAiImageModelTestCapability } from '@/api/endpoints/types'
export type ModelTestEndpointSource = {
@@ -71,7 +74,7 @@ export function modelTestKeySupportsEndpoint(
const keyFormats = normalizeModelTestStringList(key.api_formats)
if (keyFormats.length === 0) return true
return keyFormats.some(format => normalizeApiFormatAlias(format) === endpointFormat)
return keyFormats.some(format => apiFormatPermissionCovers(format, endpointFormat))
}
export function isModelTestableEndpoint(
@@ -1,4 +1,7 @@
import { normalizeApiFormatAlias } from '@/api/endpoints/types/api-format'
import {
apiFormatPermissionCovers,
normalizeApiFormatAlias,
} from '@/api/endpoints/types/api-format'
import type { ProviderModelMapping } from '@/api/endpoints/types'
import type { TestModelRequest } from '@/api/endpoints/providers'
import {
@@ -29,12 +32,18 @@ export type { ModelTestImagePreview } from './model-test-preview'
const DEFAULT_MODEL_TEST_MESSAGE = 'Hello! This is a test message.'
function buildModelTestSearchSessionId(): string {
const id = globalThis.crypto?.randomUUID?.()
?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
return `aether-model-test-${id}`
}
type ModelTestMappingSource = {
provider_model_name: string
provider_model_mappings?: ProviderModelMapping[] | null
}
type ModelTestMappingEndpoint = {
export type ModelTestMappingEndpoint = {
id: string
api_format: string
}
@@ -44,17 +53,19 @@ export type ModelTestMappedModelOption = {
priority: number
}
function mappingApiFormatMatches(mapping: ProviderModelMapping, endpoint: ModelTestMappingEndpoint): boolean {
const apiFormats = normalizeModelTestStringList(mapping.api_formats)
if (apiFormats.length === 0) return true
export function modelTestMappingScopeMatchesEndpoint(
apiFormats: string[] | null | undefined,
endpointIds: string[] | null | undefined,
endpoint: ModelTestMappingEndpoint,
): boolean {
const normalizedApiFormats = normalizeModelTestStringList(apiFormats)
const endpointFormat = normalizeApiFormatAlias(endpoint.api_format)
return apiFormats.some(format => normalizeApiFormatAlias(format) === endpointFormat)
}
function mappingEndpointMatches(mapping: ProviderModelMapping, endpoint: ModelTestMappingEndpoint): boolean {
const endpointIds = normalizeModelTestStringList(mapping.endpoint_ids)
if (endpointIds.length === 0) return true
return endpointIds.includes(endpoint.id)
const apiFormatMatches = normalizedApiFormats.length === 0
|| normalizedApiFormats.some(format => apiFormatPermissionCovers(format, endpointFormat))
const normalizedEndpointIds = normalizeModelTestStringList(endpointIds)
const endpointMatches = normalizedEndpointIds.length === 0
|| normalizedEndpointIds.includes(endpoint.id)
return apiFormatMatches && endpointMatches
}
export function listModelTestMappedModelOptions(
@@ -65,8 +76,11 @@ export function listModelTestMappedModelOptions(
const matchedMappings = model.provider_model_mappings
.filter(mapping => mapping.name.trim())
.filter(mapping => mappingApiFormatMatches(mapping, endpoint))
.filter(mapping => mappingEndpointMatches(mapping, endpoint))
.filter(mapping => modelTestMappingScopeMatchesEndpoint(
mapping.api_formats,
mapping.endpoint_ids,
endpoint,
))
.sort((left, right) => {
const leftPriority = Number.isFinite(left.priority) ? left.priority : 1
const rightPriority = Number.isFinite(right.priority) ? right.priority : 1
@@ -204,6 +218,18 @@ export function buildDefaultModelTestRequestBody(
}, null, 2)
}
if (normalizedApiFormat === 'openai:search') {
return JSON.stringify({
id: buildModelTestSearchSessionId(),
model: modelName,
input: DEFAULT_MODEL_TEST_MESSAGE,
commands: {
search_query: [{ q: DEFAULT_MODEL_TEST_MESSAGE }],
},
max_output_tokens: 256,
}, null, 2)
}
if (normalizedApiFormat === 'openai:responses' && modelSupportsImageGeneration(model)) {
return JSON.stringify({
model: modelName,
@@ -1,35 +1,15 @@
import type { EndpointHealthDetail } from '@/api/endpoints'
import { compareApiFormats } from '@/api/endpoints/types/api-format'
import { defaultLocale, translateLegacyText, type Locale } from '@/i18n/messages'
// 端点状态枚举
export type EndpointStatus = 'disabled' | 'no_keys' | 'keys_disabled' | 'available'
const ENDPOINT_SORT_ORDER = [
'claude:messages',
'openai:chat',
'openai:responses',
'openai:responses:compact',
'openai:embedding',
'openai:rerank',
'gemini:generate_content',
'gemini:interactions',
'gemini:embedding',
'openai:video',
'gemini:video',
'gemini:files',
'jina:embedding',
'jina:rerank',
'doubao:embedding',
'aliyun:multimodal_embedding',
]
/**
* 端点排序
*/
export function sortEndpoints<T extends { api_format: string }>(endpoints: T[]): T[] {
return [...endpoints].sort((a, b) => {
return ENDPOINT_SORT_ORDER.indexOf(a.api_format) - ENDPOINT_SORT_ORDER.indexOf(b.api_format)
})
return [...endpoints].sort((a, b) => compareApiFormats(a.api_format, b.api_format))
}
/**
@@ -1,5 +1,6 @@
import { ref, computed, watch } from 'vue'
import type { ProviderSummaryQuery } from '@/api/endpoints'
import { API_FORMAT_ORDER, formatApiFormat } from '@/api/endpoints/types/api-format'
import { useI18n } from '@/i18n'
export interface FilterOption {
@@ -25,19 +26,7 @@ export function useProviderFilters(
const apiFormatFilters = computed<FilterOption[]>(() => [
{ value: 'all', label: legacyT('全部格式') },
{ value: 'claude:messages', label: 'Claude Messages' },
{ value: 'openai:chat', label: 'OpenAI Chat' },
{ value: 'openai:responses', label: 'OpenAI Responses' },
{ value: 'openai:responses:compact', label: 'OpenAI Responses Compact' },
{ value: 'openai:embedding', label: 'OpenAI Embedding' },
{ value: 'openai:rerank', label: 'OpenAI Rerank' },
{ value: 'gemini:generate_content', label: 'Gemini Generate Content' },
{ value: 'gemini:interactions', label: 'Gemini Interactions' },
{ value: 'gemini:embedding', label: 'Gemini Embedding' },
{ value: 'jina:embedding', label: 'Jina Embedding' },
{ value: 'jina:rerank', label: 'Jina Rerank' },
{ value: 'doubao:embedding', label: 'Doubao Embedding' },
{ value: 'aliyun:multimodal_embedding', label: 'Aliyun Multimodal Embedding' },
...API_FORMAT_ORDER.map(value => ({ value, label: formatApiFormat(value) })),
])
const modelFilters = computed<FilterOption[]>(() => {
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest'
import { parseProviderKeyBatchImport } from '../providerKeyBatchImport'
describe('provider key batch import parser', () => {
it('parses required names and keys separated by four hyphens', () => {
const result = parseProviderKeyBatchImport([
'primary----sk-primary',
'backup----sk-backup',
'night----sk-night----suffix',
'# ignored comment',
].join('\n'))
expect(result.errors).toEqual([])
expect(result.items).toEqual([
{ lineNumber: 1, name: 'primary', apiKey: 'sk-primary' },
{ lineNumber: 2, name: 'backup', apiKey: 'sk-backup' },
{ lineNumber: 3, name: 'night', apiKey: 'sk-night----suffix' },
])
})
it('reports invalid format, missing fields and duplicates', () => {
const result = parseProviderKeyBatchImport([
'one----sk-1',
'two----sk-1',
'one----sk-2',
'----sk-3',
'three----',
'sk-without-name',
].join('\n'))
expect(result.items).toHaveLength(1)
expect(result.errors.map(error => error.message)).toEqual([
'Key 与前面行重复',
'名称与前面行重复',
'名称不能为空',
'Key 不能为空',
'格式应为 名称----Key',
])
})
it('does not impose a client-side item limit', () => {
const input = Array.from({ length: 750 }, (_, index) => `key-${index}----sk-${index}`).join('\n')
const result = parseProviderKeyBatchImport(input)
expect(result.items).toHaveLength(750)
expect(result.errors).toEqual([])
})
})
@@ -1,52 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import {
AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS,
isProviderQuotaAutoRefreshCoolingDown,
markProviderQuotaAutoRefreshAttempt,
resetProviderQuotaAutoRefreshCooldownForTests,
} from '../quotaAutoRefreshCooldown'
describe('quota auto refresh cooldown', () => {
afterEach(() => {
resetProviderQuotaAutoRefreshCooldownForTests()
})
it('starts cooldown after recording an auto refresh attempt', () => {
markProviderQuotaAutoRefreshAttempt('provider-1', 1_000)
expect(isProviderQuotaAutoRefreshCoolingDown('provider-1', 1_000)).toBe(true)
expect(
isProviderQuotaAutoRefreshCoolingDown(
'provider-1',
1_000 + AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS - 1,
),
).toBe(true)
})
it('expires cooldown after the configured window', () => {
markProviderQuotaAutoRefreshAttempt('provider-1', 1_000)
expect(
isProviderQuotaAutoRefreshCoolingDown(
'provider-1',
1_000 + AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS,
),
).toBe(false)
})
it('tracks cooldown independently per provider', () => {
markProviderQuotaAutoRefreshAttempt('provider-1', 1_000)
markProviderQuotaAutoRefreshAttempt('provider-2', 1_200)
expect(isProviderQuotaAutoRefreshCoolingDown('provider-1', 1_301)).toBe(false)
expect(isProviderQuotaAutoRefreshCoolingDown('provider-2', 1_301)).toBe(true)
})
it('ignores empty provider ids', () => {
markProviderQuotaAutoRefreshAttempt('', 1_000)
expect(isProviderQuotaAutoRefreshCoolingDown('', 1_001)).toBe(false)
expect(isProviderQuotaAutoRefreshCoolingDown(null, 1_001)).toBe(false)
})
})
@@ -0,0 +1,73 @@
export interface ProviderKeyBatchImportItem {
lineNumber: number
name: string
apiKey: string
}
export interface ProviderKeyBatchImportError {
lineNumber: number | null
message: string
}
export interface ProviderKeyBatchImportParseResult {
items: ProviderKeyBatchImportItem[]
errors: ProviderKeyBatchImportError[]
}
export const PROVIDER_KEY_BATCH_SEPARATOR = '----'
function splitNamedKey(line: string): { name: string; apiKey: string } | null {
const separatorIndex = line.indexOf(PROVIDER_KEY_BATCH_SEPARATOR)
if (separatorIndex < 0) return null
return {
name: line.slice(0, separatorIndex),
apiKey: line.slice(separatorIndex + PROVIDER_KEY_BATCH_SEPARATOR.length),
}
}
export function parseProviderKeyBatchImport(input: string): ProviderKeyBatchImportParseResult {
const items: ProviderKeyBatchImportItem[] = []
const errors: ProviderKeyBatchImportError[] = []
const seenKeys = new Set<string>()
const seenNames = new Set<string>()
for (const [index, rawLine] of input.split(/\r?\n/).entries()) {
const lineNumber = index + 1
const line = rawLine.trim()
if (!line || line.startsWith('#')) continue
const named = splitNamedKey(line)
if (!named) {
errors.push({ lineNumber, message: `格式应为 名称${PROVIDER_KEY_BATCH_SEPARATOR}Key` })
continue
}
const name = named.name.trim()
const apiKey = named.apiKey.trim()
if (!name) {
errors.push({ lineNumber, message: '名称不能为空' })
continue
}
if (!apiKey) {
errors.push({ lineNumber, message: 'Key 不能为空' })
continue
}
if (name.length > 100) {
errors.push({ lineNumber, message: '名称不能超过 100 个字符' })
continue
}
if (seenKeys.has(apiKey)) {
errors.push({ lineNumber, message: 'Key 与前面行重复' })
continue
}
if (seenNames.has(name)) {
errors.push({ lineNumber, message: '名称与前面行重复' })
continue
}
seenKeys.add(apiKey)
seenNames.add(name)
items.push({ lineNumber, name, apiKey })
}
return { items, errors }
}
@@ -1,36 +0,0 @@
const AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS = 5 * 60
const lastAutoQuotaRefreshAttemptAtByProvider = new Map<string, number>()
function normalizeUnixSeconds(value: number): number {
return Math.max(Math.floor(value), 0)
}
export function isProviderQuotaAutoRefreshCoolingDown(
providerId: string | null | undefined,
nowSeconds = Math.floor(Date.now() / 1000),
): boolean {
const id = String(providerId || '').trim()
if (!id) return false
const lastAttemptAt = lastAutoQuotaRefreshAttemptAtByProvider.get(id)
if (lastAttemptAt == null) return false
return normalizeUnixSeconds(nowSeconds) - lastAttemptAt < AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS
}
export function markProviderQuotaAutoRefreshAttempt(
providerId: string | null | undefined,
nowSeconds = Math.floor(Date.now() / 1000),
): void {
const id = String(providerId || '').trim()
if (!id) return
lastAutoQuotaRefreshAttemptAtByProvider.set(id, normalizeUnixSeconds(nowSeconds))
}
export function resetProviderQuotaAutoRefreshCooldownForTests(): void {
lastAutoQuotaRefreshAttemptAtByProvider.clear()
}
export { AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS }
@@ -249,6 +249,13 @@
<span class="ml-1 font-bold text-primary">{{ formatOutputRateValue(detailOutputRate) }}tps</span>
</span>
</div>
<ServiceTierFacts
v-if="hasServiceTierFacts"
class="mt-3"
:requested="serviceTierFacts.requested"
:actual="serviceTierFacts.actual"
:billing="serviceTierFacts.billing"
/>
</div>
<!-- 分隔线 -->
@@ -907,6 +914,8 @@ import JsonContentPanel from './JsonContentPanel.vue'
import ConversationView from './RequestDetailDrawer/ConversationView.vue'
import HorizontalRequestTimeline from './HorizontalRequestTimeline.vue'
import ReplayDialog from './ReplayDialog.vue'
import ServiceTierFacts from './ServiceTierFacts.vue'
import { hasServiceTierFact, resolveServiceTierFacts } from '../utils/service-tier'
// 对话解析器
import {
@@ -952,6 +961,7 @@ const emit = defineEmits<{
targetModel?: string | null
reasoningEffort?: string | null
serviceTier?: string | null
actualServiceTier?: string | null
imageProgress?: ImageProgress | null
errorMessage?: string | null
}]
@@ -1134,6 +1144,7 @@ function emitDetailRequestState(nextDetail: RequestDetail) {
targetModel: nextDetail.target_model ?? null,
reasoningEffort: nextDetail.reasoning_effort ?? null,
serviceTier: nextDetail.service_tier ?? null,
actualServiceTier: nextDetail.actual_service_tier ?? null,
errorMessage: nextDetail.error_message ?? undefined,
})
}
@@ -1342,6 +1353,9 @@ const metadataPanelData = computed<Record<string, unknown> | null>(() => {
const failureNotice = computed(() => resolveRequestFailureNotice(detail.value))
const serviceTierFacts = computed(() => resolveServiceTierFacts(detail.value))
const hasServiceTierFacts = computed(() => hasServiceTierFact(serviceTierFacts.value))
const settlementInfo = computed<JsonRecord | null>(() =>
asRecord(detail.value?.settlement ?? null),
)
@@ -0,0 +1,48 @@
<template>
<dl
class="grid grid-cols-1 gap-x-4 gap-y-1.5 text-xs sm:grid-cols-3"
data-testid="service-tier-facts"
>
<div class="flex min-w-0 items-baseline justify-between gap-3 sm:block">
<dt class="text-muted-foreground">
请求层级
</dt>
<dd
class="truncate font-mono font-medium text-foreground sm:mt-0.5"
:title="requested || '-'"
>
{{ requested || '-' }}
</dd>
</div>
<div class="flex min-w-0 items-baseline justify-between gap-3 sm:block">
<dt class="text-muted-foreground">
实际层级
</dt>
<dd
class="truncate font-mono font-medium text-foreground sm:mt-0.5"
:title="actual || '-'"
>
{{ actual || '-' }}
</dd>
</div>
<div class="flex min-w-0 items-baseline justify-between gap-3 sm:block">
<dt class="text-muted-foreground">
计费层级
</dt>
<dd
class="truncate font-mono font-medium text-foreground sm:mt-0.5"
:title="billing || '-'"
>
{{ billing || '-' }}
</dd>
</div>
</dl>
</template>
<script setup lang="ts">
defineProps<{
requested: string | null
actual: string | null
billing: string | null
}>()
</script>
@@ -253,12 +253,14 @@
{{ getReasoningEffort(record) }}
</Badge>
<Badge
v-if="getFastBadge(record)"
v-if="getServiceTierBadge(record)"
variant="outline"
class="h-4 rounded-full px-1.5 text-[10px] leading-4 text-foreground flex-shrink-0"
:title="getFastBadgeTitle(record)"
class="h-4 whitespace-nowrap rounded-full px-1.5 text-[10px] leading-4 flex-shrink-0"
:class="getServiceTierBadge(record)?.className"
:title="getServiceTierBadge(record)?.title"
:aria-label="getServiceTierBadge(record)?.ariaLabel"
>
fast
{{ getServiceTierBadge(record)?.label }}
</Badge>
<!-- 状态 Badge -->
<Badge
@@ -762,12 +764,14 @@
{{ getReasoningEffort(record) }}
</Badge>
<Badge
v-if="getFastBadge(record)"
v-if="getServiceTierBadge(record)"
variant="outline"
class="h-4 rounded-full px-1.5 text-[10px] leading-4 text-foreground flex-shrink-0"
:title="getFastBadgeTitle(record)"
class="h-4 whitespace-nowrap rounded-full px-1.5 text-[10px] leading-4 flex-shrink-0"
:class="getServiceTierBadge(record)?.className"
:title="getServiceTierBadge(record)?.title"
:aria-label="getServiceTierBadge(record)?.ariaLabel"
>
fast
{{ getServiceTierBadge(record)?.label }}
</Badge>
</div>
<span class="text-muted-foreground truncate">{{ getActualModel(record) }}</span>
@@ -786,12 +790,14 @@
{{ getReasoningEffort(record) }}
</Badge>
<Badge
v-if="getFastBadge(record)"
v-if="getServiceTierBadge(record)"
variant="outline"
class="h-4 rounded-full px-1.5 text-[10px] leading-4 text-foreground flex-shrink-0"
:title="getFastBadgeTitle(record)"
class="h-4 whitespace-nowrap rounded-full px-1.5 text-[10px] leading-4 flex-shrink-0"
:class="getServiceTierBadge(record)?.className"
:title="getServiceTierBadge(record)?.title"
:aria-label="getServiceTierBadge(record)?.ariaLabel"
>
fast
{{ getServiceTierBadge(record)?.label }}
</Badge>
</span>
</TableCell>
@@ -1610,26 +1616,139 @@ function getReasoningEffortTitle(record: UsageRecord): string {
return effort ? `Reasoning: ${effort}` : ''
}
function getServiceTier(record: UsageRecord): string | null {
const serviceTier = record.service_tier?.trim().toLowerCase()
type ServiceTierBadgeState = 'confirmed' | 'downgraded' | 'upgraded' | 'pending' | 'unconfirmed'
interface ServiceTierBadgePresentation {
label: string
state: ServiceTierBadgeState
className: string
title: string
ariaLabel: string
}
function normalizeServiceTier(value: string | null | undefined): string | null {
const serviceTier = value?.trim().toLowerCase()
return serviceTier || null
}
function getFastBadge(record: UsageRecord): boolean {
return getServiceTier(record) === 'priority'
function canonicalServiceTier(value: string | null): string | null {
if (value === 'auto' || value === 'default' || value === 'standard') {
return 'standard'
}
return value
}
function getFastBadgeTitle(record: UsageRecord): string {
const serviceTier = getServiceTier(record)
return serviceTier ? `Service tier: ${serviceTier}` : ''
function serviceTierBadgeClass(state: ServiceTierBadgeState): string {
switch (state) {
case 'confirmed':
return 'border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'
case 'downgraded':
return 'border-amber-500/50 bg-amber-500/10 text-amber-700 dark:text-amber-300'
case 'upgraded':
return 'border-sky-500/40 bg-sky-500/10 text-sky-700 dark:text-sky-300'
case 'pending':
return 'border-dashed border-muted-foreground/30 bg-muted/30 text-muted-foreground'
case 'unconfirmed':
return 'border-dashed border-amber-500/40 bg-amber-500/5 text-amber-700 dark:text-amber-300'
}
}
function buildServiceTierBadgePresentation(
label: string,
state: ServiceTierBadgeState,
requestedRaw: string | null,
actualRaw: string | null,
billingTier: string | null,
): ServiceTierBadgePresentation {
const titleLines: string[] = []
if (requestedRaw) titleLines.push(`请求档位:${requestedRaw}`)
if (actualRaw) titleLines.push(`实际档位:${actualRaw}`)
if (billingTier) {
titleLines.push(`计费档位:${billingTier}`)
} else {
titleLines.push(`计费档位:${state === 'pending' ? '待上游确认' : '未确认'}`)
}
const title = titleLines.join('\n')
return {
label,
state,
className: serviceTierBadgeClass(state),
title,
ariaLabel: titleLines.join(','),
}
}
function getServiceTierBadge(record: UsageRecord): ServiceTierBadgePresentation | null {
const requestedRaw = normalizeServiceTier(record.service_tier)
const actualRaw = normalizeServiceTier(record.actual_service_tier)
const requested = canonicalServiceTier(requestedRaw)
const actual = canonicalServiceTier(actualRaw)
const requestedFast = requested === 'priority'
const actualFast = actual === 'priority'
if (actual) {
if (requestedFast && !actualFast) {
return buildServiceTierBadgePresentation(
`fast → ${actual}`,
'downgraded',
requestedRaw,
actualRaw,
actual,
)
}
if (!requestedFast && actualFast) {
const requestedLabel = requested ?? 'standard'
return buildServiceTierBadgePresentation(
requested ? `${requestedLabel} → fast` : 'fast',
requested ? 'upgraded' : 'confirmed',
requestedRaw,
actualRaw,
actual,
)
}
if (actualFast) {
return buildServiceTierBadgePresentation(
'fast',
'confirmed',
requestedRaw,
actualRaw,
actual,
)
}
return null
}
if (!requestedFast) return null
const displayStatus = getDisplayStatus(record)
const isActive = displayStatus === 'pending' || displayStatus === 'streaming'
return buildServiceTierBadgePresentation(
isActive ? 'fast · 待确认' : 'fast · 未确认',
isActive ? 'pending' : 'unconfirmed',
requestedRaw,
null,
null,
)
}
function getServiceTierTitle(record: UsageRecord): string {
const badge = getServiceTierBadge(record)
if (badge) return badge.title
const requested = normalizeServiceTier(record.service_tier)
const actual = normalizeServiceTier(record.actual_service_tier)
return [
requested ? `请求档位:${requested}` : null,
actual ? `实际档位:${actual}` : null,
].filter((line): line is string => Boolean(line)).join('\n')
}
// 获取模型列的 tooltip
function getModelTooltip(record: UsageRecord): string {
const actualModel = getActualModel(record)
const reasoningEffort = getReasoningEffort(record)
const fastSuffix = getFastBadge(record) ? '\nService tier: priority' : ''
const suffix = `${reasoningEffort ? `\nReasoning: ${reasoningEffort}` : ''}${fastSuffix}`
const serviceTierTitle = getServiceTierTitle(record)
const tierSuffix = serviceTierTitle ? `\n${serviceTierTitle}` : ''
const suffix = `${reasoningEffort ? `\nReasoning: ${reasoningEffort}` : ''}${tierSuffix}`
if (actualModel) {
return `${record.model} -> ${actualModel}${suffix}`
}
@@ -0,0 +1,41 @@
import { afterEach, describe, expect, it } from 'vitest'
import { createApp, h, type App } from 'vue'
import ServiceTierFacts from '../ServiceTierFacts.vue'
const mountedApps: Array<{ app: App, root: HTMLElement }> = []
afterEach(() => {
for (const { app, root } of mountedApps.splice(0)) {
app.unmount()
root.remove()
}
})
describe('ServiceTierFacts', () => {
it('renders all three facts and marks a missing actual tier explicitly', () => {
const root = document.createElement('div')
document.body.appendChild(root)
const app = createApp({
render: () => h(ServiceTierFacts, {
requested: 'priority',
actual: null,
billing: 'flex',
}),
})
app.mount(root)
mountedApps.push({ app, root })
expect(root.querySelector('[data-testid="service-tier-facts"]')).not.toBeNull()
expect([...root.querySelectorAll('dt')].map(node => node.textContent?.trim())).toEqual([
'请求层级',
'实际层级',
'计费层级',
])
expect([...root.querySelectorAll('dd')].map(node => node.textContent?.trim())).toEqual([
'priority',
'-',
'flex',
])
})
})
@@ -162,6 +162,13 @@ function mountUsageRecordsTable(records: UsageRecord[], overrides: Record<string
return root
}
function expectServiceTierBadge(root: HTMLElement, label: string) {
const labels = [...root.querySelectorAll('span')]
.map((element) => element.textContent?.trim())
expect(labels).toContain(label)
}
afterEach(() => {
for (const { app, root } of mountedApps.splice(0)) {
app.unmount()
@@ -288,11 +295,63 @@ describe('UsageRecordsTable', () => {
expect(root.textContent).toContain('xhigh')
})
it('shows fast badge for priority service tier', () => {
const root = mountUsageRecordsTable([buildRecord({ service_tier: 'priority' })])
it('shows confirmed fast when requested and actual service tiers are priority', () => {
const root = mountUsageRecordsTable([buildRecord({
service_tier: 'priority',
actual_service_tier: 'priority',
})])
expect(root.textContent).toContain('gpt-5')
expect(root.textContent).toContain('fast')
expectServiceTierBadge(root, 'fast')
})
it('shows fast to standard when the provider downgrades a priority request', () => {
const root = mountUsageRecordsTable([buildRecord({
service_tier: 'priority',
actual_service_tier: 'default',
})])
expectServiceTierBadge(root, 'fast → standard')
})
it('shows fast to flex when the provider moves a priority request to flex', () => {
const root = mountUsageRecordsTable([buildRecord({
service_tier: 'priority',
actual_service_tier: 'flex',
})])
expectServiceTierBadge(root, 'fast → flex')
})
it('shows standard to fast when the provider upgrades a default request', () => {
const root = mountUsageRecordsTable([buildRecord({
service_tier: 'default',
actual_service_tier: 'priority',
})])
expectServiceTierBadge(root, 'standard → fast')
})
it.each(['pending', 'streaming'] as const)(
'shows fast as pending confirmation while a priority request is %s',
(status) => {
const root = mountUsageRecordsTable([buildRecord({
service_tier: 'priority',
actual_service_tier: null,
status,
})])
expectServiceTierBadge(root, 'fast · 待确认')
},
)
it('shows fast as unconfirmed when a completed priority request has no actual tier', () => {
const root = mountUsageRecordsTable([buildRecord({
service_tier: 'priority',
actual_service_tier: null,
status: 'completed',
})])
expectServiceTierBadge(root, 'fast · 未确认')
})
it('offers embedding API formats in the usage record filter', () => {
@@ -218,6 +218,7 @@ describe('useUsageData', () => {
target_model: 'gpt-5.5',
reasoning_effort: 'xhigh',
service_tier: 'auto',
actual_service_tier: 'priority',
})
getAllUsageRecordsMock.mockResolvedValueOnce({
@@ -246,6 +247,7 @@ describe('useUsageData', () => {
target_model: null,
reasoning_effort: null,
service_tier: null,
actual_service_tier: null,
})],
total: 1,
limit: 20,
@@ -279,6 +281,7 @@ describe('useUsageData', () => {
target_model: 'gpt-5.5',
reasoning_effort: 'xhigh',
service_tier: 'auto',
actual_service_tier: 'priority',
})
})
@@ -631,7 +631,8 @@ export function useUsageData(options: UseUsageDataOptions) {
rate_multiplier: record.rate_multiplier ?? existing.rate_multiplier,
target_model: record.target_model ?? existing.target_model,
reasoning_effort: record.reasoning_effort ?? existing.reasoning_effort,
service_tier: record.service_tier ?? existing.service_tier
service_tier: record.service_tier ?? existing.service_tier,
actual_service_tier: record.actual_service_tier ?? existing.actual_service_tier
}
})
}
+1
View File
@@ -98,6 +98,7 @@ export interface UsageRecord {
model_version?: string | null // Provider 返回的实际模型版本(列表轻量字段)
reasoning_effort?: string | null // 从发送给 Provider 的请求体提取的 reasoning 级别
service_tier?: string | null // 从发送给 Provider 的请求体提取的服务层级
actual_service_tier?: string | null // Provider 响应确认的实际服务层级
api_format?: string
endpoint_api_format?: string // 端点原生格式
has_format_conversion?: boolean // 是否发生了格式转换
@@ -1,7 +1,10 @@
import { describe, expect, it } from 'vitest'
import type { UsageRecord } from '../../types'
import { syncUsageRecordStreamResolution } from '../recordSync'
import {
mergeUsageRecordFirstByteTimeMs,
syncUsageRecordStreamResolution,
} from '../recordSync'
function buildUsageRecord(overrides: Partial<UsageRecord> = {}): UsageRecord {
return {
@@ -59,3 +62,16 @@ describe('syncUsageRecordStreamResolution', () => {
expect(nextRecords).toBe(records)
})
})
describe('mergeUsageRecordFirstByteTimeMs', () => {
it('does not let a stale active update clear or reduce a resolved first-byte time', () => {
expect(mergeUsageRecordFirstByteTimeMs(500, null)).toBe(500)
expect(mergeUsageRecordFirstByteTimeMs(500, 320)).toBe(500)
expect(mergeUsageRecordFirstByteTimeMs(500, 640)).toBe(640)
expect(mergeUsageRecordFirstByteTimeMs(undefined, 320)).toBe(320)
expect(mergeUsageRecordFirstByteTimeMs(undefined, 0)).toBe(0)
expect(mergeUsageRecordFirstByteTimeMs(0, null)).toBe(0)
expect(mergeUsageRecordFirstByteTimeMs(null, -1)).toBeNull()
expect(mergeUsageRecordFirstByteTimeMs(-1, null)).toBeUndefined()
})
})
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest'
import {
hasServiceTierFact,
normalizeServiceTierFact,
resolveServiceTierFacts,
} from '../service-tier'
describe('service tier facts', () => {
it('keeps requested, actual and billing tiers independent', () => {
const facts = resolveServiceTierFacts({
service_tier: 'priority',
actual_service_tier: 'default',
settlement: {
settlement_snapshot: {
pricing_snapshot: {
requested_processing_tier: 'ignored-requested-snapshot',
actual_processing_tier: 'ignored-actual-snapshot',
billing_processing_tier: 'standard',
},
},
},
})
expect(facts).toEqual({ requested: 'priority', actual: 'default', billing: 'standard' })
expect(hasServiceTierFact(facts)).toBe(true)
})
it('does not infer billing from requested or actual tiers', () => {
expect(resolveServiceTierFacts({
service_tier: 'priority',
actual_service_tier: 'flex',
})).toEqual({ requested: 'priority', actual: 'flex', billing: null })
})
it('normalizes only non-empty string facts', () => {
expect(normalizeServiceTierFact(' Batch ')).toBe('Batch')
expect(normalizeServiceTierFact(' ')).toBeNull()
expect(normalizeServiceTierFact(0)).toBeNull()
})
})
@@ -78,6 +78,11 @@ describe('usage status helpers', () => {
status: 'streaming',
first_byte_time_ms: 320,
}))).toBe('streaming')
expect(resolveDisplayRequestStatus(buildUsageRecord({
status: 'streaming',
first_byte_time_ms: 0,
}))).toBe('streaming')
})
it('treats active lifecycle records with failure signals as failed for display', () => {
@@ -197,6 +202,14 @@ describe('usage status helpers', () => {
client_is_stream: undefined,
}))).toBe('标准->流式')
expect(formatUsageStreamLabel(buildUsageRecord({
api_format: 'openai:search',
is_stream: false,
upstream_is_stream: false,
client_requested_stream: undefined,
client_is_stream: undefined,
}))).toBe('标准')
expect(formatUsageStreamLabel(buildUsageRecord({
api_format: 'claude:messages',
is_stream: false,
@@ -5,6 +5,30 @@ export type UsageRecordStreamResolution = Pick<
'id' | 'is_stream' | 'upstream_is_stream' | 'client_requested_stream' | 'client_is_stream'
>
export function mergeUsageRecordFirstByteTimeMs(
existingValue: number | null | undefined,
nextValue: number | null | undefined
): number | null | undefined {
// Millisecond timing is floored, so 0 still means the first byte was observed.
const existingIsResolved = typeof existingValue === 'number' &&
Number.isFinite(existingValue) &&
existingValue >= 0
const nextIsResolved = typeof nextValue === 'number' &&
Number.isFinite(nextValue) &&
nextValue >= 0
if (existingIsResolved && nextIsResolved) {
return Math.max(existingValue, nextValue)
}
if (existingIsResolved) {
return existingValue
}
if (nextIsResolved) {
return nextValue
}
return existingValue == null ? existingValue : undefined
}
export function syncUsageRecordStreamResolution(
records: UsageRecord[],
resolved: UsageRecordStreamResolution
@@ -0,0 +1,40 @@
export interface ServiceTierFacts {
requested: string | null
actual: string | null
billing: string | null
}
export interface ServiceTierFactSource {
service_tier?: unknown
actual_service_tier?: unknown
settlement?: unknown
}
export function resolveServiceTierFacts(
source: ServiceTierFactSource | null | undefined,
): ServiceTierFacts {
const settlement = asRecord(source?.settlement)
const settlementSnapshot = asRecord(settlement?.settlement_snapshot)
const pricingSnapshot = asRecord(settlementSnapshot?.pricing_snapshot)
return {
requested: normalizeServiceTierFact(source?.service_tier),
actual: normalizeServiceTierFact(source?.actual_service_tier),
billing: normalizeServiceTierFact(pricingSnapshot?.billing_processing_tier),
}
}
export function hasServiceTierFact(facts: ServiceTierFacts): boolean {
return facts.requested !== null || facts.actual !== null || facts.billing !== null
}
export function normalizeServiceTierFact(value: unknown): string | null {
if (typeof value !== 'string') return null
const normalized = value.trim()
return normalized || null
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: null
}
@@ -160,6 +160,7 @@ function usageApiFormatDefaultsToNonStream(apiFormat: string): boolean {
case 'openai:chat':
case 'openai:responses':
case 'openai:responses:compact':
case 'openai:search':
case 'openai:image':
case 'claude:messages':
return true
@@ -1,6 +1,6 @@
<template>
<div class="space-y-4 border-t border-border/60 pt-5">
<div class="flex flex-wrap items-baseline justify-between gap-x-2 gap-y-1 border-b border-border/60 pb-2">
<div class="flex items-center justify-between gap-2 border-b border-border/60 pb-2">
<span class="text-sm font-medium">{{ legacyT('组权限') }}</span>
<span class="flex items-center gap-1 text-[11px] text-muted-foreground">
{{ legacyT('组权限叠加,Key 可再收窄') }}
@@ -9,11 +9,11 @@
<TooltipTrigger as-child>
<button
type="button"
class="inline-flex h-4 w-4 items-center justify-center rounded-full border border-border/70 bg-muted/40 text-muted-foreground outline-none transition-colors hover:border-primary/50 hover:text-primary focus-visible:border-primary/60 focus-visible:text-primary"
class="inline-flex h-10 w-10 items-center justify-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-primary focus-visible:ring-2 focus-visible:ring-ring"
:title="helpText"
:aria-label="legacyT('查看组权限合并规则')"
>
<Info class="h-3 w-3" />
<Info class="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent class="max-w-72 text-xs leading-5">
@@ -27,11 +27,14 @@
<div class="space-y-2">
<Label class="text-sm font-medium">{{ legacyT('允许的提供商') }}</Label>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<div class="flex w-full items-center sm:w-auto sm:shrink-0">
<div class="flex min-h-10 w-full items-center gap-2 sm:w-auto sm:shrink-0">
<Switch
:model-value="form.allowed_providers_mode === 'unrestricted'"
@update:model-value="setProvidersUnrestricted"
/>
<span class="text-xs text-muted-foreground sm:sr-only">
{{ legacyT(form.allowed_providers_mode === 'unrestricted' ? '不限制' : '选择提供商') }}
</span>
</div>
<div class="min-w-0 flex-1">
<MultiSelect
@@ -50,11 +53,14 @@
<div class="space-y-2">
<Label class="text-sm font-medium">{{ legacyT('允许的端点') }}</Label>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<div class="flex w-full items-center sm:w-auto sm:shrink-0">
<div class="flex min-h-10 w-full items-center gap-2 sm:w-auto sm:shrink-0">
<Switch
:model-value="form.allowed_api_formats_mode === 'unrestricted'"
@update:model-value="setApiFormatsUnrestricted"
/>
<span class="text-xs text-muted-foreground sm:sr-only">
{{ legacyT(form.allowed_api_formats_mode === 'unrestricted' ? '不限制' : '选择端点') }}
</span>
</div>
<div class="min-w-0 flex-1">
<MultiSelect
@@ -73,11 +79,14 @@
<div class="space-y-2">
<Label class="text-sm font-medium">{{ legacyT('允许的模型') }}</Label>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<div class="flex w-full items-center sm:w-auto sm:shrink-0">
<div class="flex min-h-10 w-full items-center gap-2 sm:w-auto sm:shrink-0">
<Switch
:model-value="form.allowed_models_mode === 'unrestricted'"
@update:model-value="setModelsUnrestricted"
/>
<span class="text-xs text-muted-foreground sm:sr-only">
{{ legacyT(form.allowed_models_mode === 'unrestricted' ? '不限制' : '选择模型') }}
</span>
</div>
<div class="min-w-0 flex-1">
<MultiSelect
@@ -96,11 +105,14 @@
<div class="space-y-2">
<Label class="text-sm font-medium">{{ legacyT('速率限制 (请求/分钟)') }}</Label>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<div class="flex w-full items-center sm:w-auto sm:shrink-0">
<div class="flex min-h-10 w-full items-center gap-2 sm:w-auto sm:shrink-0">
<Switch
:model-value="form.rate_limit_mode === 'system'"
@update:model-value="setSystemRateLimit"
/>
<span class="text-xs text-muted-foreground sm:sr-only">
{{ legacyT(form.rate_limit_mode === 'system' ? '系统默认' : '自定义') }}
</span>
</div>
<div class="min-w-0 flex-1">
<Input
@@ -1,7 +1,7 @@
<template>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="mb-4 flex items-start justify-between gap-3">
<div class="min-w-0">
<h4 class="truncate text-base font-semibold text-foreground">
<h4 class="text-balance break-words text-base font-semibold text-foreground">
{{ legacyT(editing ? '编辑分组' : '新建分组') }}
</h4>
<p class="text-xs text-muted-foreground">
@@ -15,7 +15,7 @@
<Button
variant="ghost"
size="icon"
class="h-8 w-8"
class="h-10 w-10"
:class="isDefault ? 'text-emerald-500 hover:text-emerald-500' : ''"
:disabled="saving || isDefault"
:title="legacyT(isDefault ? '默认注册组' : '设为默认注册组')"
@@ -26,7 +26,7 @@
<Button
variant="ghost"
size="icon"
class="h-8 w-8"
class="h-10 w-10"
:disabled="saving || isDefault"
:title="legacyT('删除分组')"
@click="$emit('delete')"
@@ -1,11 +1,11 @@
<template>
<div class="rounded-xl border border-border/70 bg-muted/20 p-3">
<div class="mb-3 flex items-center justify-between gap-2">
<div class="rounded-lg border border-border/70 bg-muted/20 p-2.5 sm:rounded-xl sm:p-3">
<div class="mb-2 flex items-center justify-between gap-2 sm:mb-3">
<Label class="text-sm font-semibold">{{ legacyT('分组') }}</Label>
<Button
variant="ghost"
size="icon"
class="h-8 w-8"
class="h-10 w-10"
:title="legacyT('新建分组')"
@click="$emit('create')"
>
@@ -27,7 +27,7 @@
</div>
<div
v-else
class="max-h-60 space-y-1.5 overflow-y-auto lg:max-h-none lg:overflow-visible"
class="flex snap-x snap-mandatory gap-2 overflow-x-auto overscroll-x-contain pb-1 lg:block lg:max-h-none lg:space-y-1.5 lg:overflow-visible lg:pb-0"
>
<button
v-for="group in groups"
@@ -48,7 +48,7 @@
</Badge>
</span>
</span>
<ChevronRight class="h-4 w-4 shrink-0 text-muted-foreground" />
<ChevronRight class="hidden h-4 w-4 shrink-0 text-muted-foreground lg:block" />
</button>
</div>
</div>
@@ -76,7 +76,7 @@ const { legacyT } = useI18n()
function groupButtonClass(groupId: string): string {
return cn(
'flex w-full items-center gap-2 rounded-lg border px-3 py-2 transition-colors',
'flex min-h-10 w-auto min-w-[8.5rem] shrink-0 snap-start items-center gap-2 rounded-lg border px-3 py-2 transition-colors lg:w-full lg:min-w-0',
props.selectedGroupId === groupId
? 'border-primary/50 bg-primary/10'
: 'border-transparent hover:border-border hover:bg-background',
@@ -7,7 +7,7 @@
persistent
@update:model-value="handleDialogUpdate"
>
<div class="grid gap-4 lg:min-h-[560px] lg:grid-cols-[17rem_minmax(0,1fr)]">
<div class="grid gap-3 lg:min-h-[560px] lg:grid-cols-[17rem_minmax(0,1fr)] lg:gap-4">
<UserGroupListPanel
:loading="loading"
:groups="groups"
@@ -16,7 +16,7 @@
@select="selectGroup"
/>
<div class="min-w-0 rounded-xl border border-border/70 bg-background p-3 sm:p-4">
<div class="min-w-0 bg-background sm:rounded-xl sm:border sm:border-border/70 sm:p-4">
<UserGroupEditorHeader
:editing="Boolean(editingGroupId)"
:is-default="Boolean(selectedGroup?.is_default)"
@@ -0,0 +1,39 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
function readSource(path: string): string {
return readFileSync(resolve(process.cwd(), path), 'utf8')
}
describe('mobile dialog layout', () => {
it('uses a full-height mobile sheet with stacked full-width actions', () => {
const source = readSource('src/components/ui/dialog/Dialog.vue')
expect(source).toContain('max-h-[100dvh]')
expect(source).toContain('flex-col-reverse')
expect(source).toContain('[&>button]:w-full')
expect(source).toContain('sm:flex-row-reverse')
expect(source).toContain('sm:[&>button]:w-auto')
})
it('keeps group navigation compact before the editor on mobile', () => {
const dialogSource = readSource('src/features/users/components/UserGroupsDialog.vue')
const listSource = readSource('src/features/users/components/UserGroupListPanel.vue')
expect(dialogSource).toContain('lg:grid-cols-[17rem_minmax(0,1fr)]')
expect(listSource).toContain('snap-x snap-mandatory')
expect(listSource).toContain('overflow-x-auto')
expect(listSource).toContain('min-h-10')
expect(listSource).toContain('lg:w-full')
})
it('provides mobile state labels and 40px icon targets', () => {
const accessSource = readSource('src/features/users/components/UserGroupAccessControlFields.vue')
const headerSource = readSource('src/features/users/components/UserGroupEditorHeader.vue')
expect(accessSource).toContain('sm:sr-only')
expect(accessSource).toContain('h-10 w-10')
expect(headerSource.match(/h-10 w-10/g)).toHaveLength(2)
})
})
+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(() => {
+2
View File
@@ -964,6 +964,7 @@ export const MOCK_SYSTEM_CONFIGS: Array<{ key: string; value: unknown; descripti
{ key: 'backup_s3_scope', value: 'data', description: 'S3 备份范围' },
{ key: 'backup_s3_endpoint', value: null, description: 'S3 Endpoint' },
{ key: 'backup_s3_region', value: 'auto', description: 'S3 Region' },
{ key: 'backup_s3_user_agent', value: 'rclone/v1.68.0', description: 'S3 User-Agent' },
{ key: 'backup_s3_bucket', value: null, description: 'S3 Bucket' },
{ key: 'backup_s3_prefix', value: 'aether/backups/', description: 'S3 备份前缀' },
{ key: 'backup_s3_access_key_id', value: null, description: 'S3 Access Key ID' },
@@ -1187,6 +1188,7 @@ export const MOCK_API_FORMATS = {
{ value: 'openai:chat', label: 'OpenAI Chat', default_path: '/v1/chat/completions', aliases: [] },
{ value: 'openai:responses', label: 'OpenAI Responses', default_path: '/v1/responses', aliases: [] },
{ value: 'openai:responses:compact', label: 'OpenAI Responses Compact', default_path: '/v1/responses/compact', aliases: [] },
{ value: 'openai:search', label: 'OpenAI Search', default_path: '/v1/alpha/search', aliases: ['openai_search', 'search'] },
{ value: 'openai:embedding', label: 'OpenAI Embedding', default_path: '/v1/embeddings', aliases: [] },
{ value: 'openai:rerank', label: 'OpenAI Rerank', default_path: '/v1/rerank', aliases: [] },
{ value: 'openai:image', label: 'OpenAI Image', default_path: '/v1/images/generations', aliases: [] },
@@ -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) {
@@ -1,8 +1,8 @@
<template>
<PageContainer>
<PageHeader
title="模型后缀参数"
description="允许通过模型名后缀覆盖推理参数"
title="模型参数指令"
description="统一管理模型名后缀对应的参数映射"
>
<template #actions>
<Button
@@ -28,7 +28,6 @@
:config="modelDirectivesConfig"
:loading="loading || saving"
@save="saveConfig"
@update:config="modelDirectivesConfig = $event"
/>
</Card>
</div>
@@ -65,27 +64,27 @@ async function loadConfig() {
const normalized = normalizeModelDirectivesConfig(response.value)
modelDirectivesConfig.value = normalized
} catch (err) {
error('获取模型后缀参数配置失败')
log.error('获取模型后缀参数配置失败:', err)
error('获取模型参数指令配置失败')
log.error('获取模型参数指令配置失败:', err)
} finally {
loading.value = false
}
}
async function saveConfig() {
async function saveConfig(nextConfig: ModelDirectivesConfig) {
saving.value = true
try {
const normalized = normalizeModelDirectivesConfig(modelDirectivesConfig.value)
modelDirectivesConfig.value = normalized
const normalized = normalizeModelDirectivesConfig(nextConfig)
await adminApi.updateSystemConfig(
'model_directives',
normalized,
'模型后缀参数配置'
'模型参数指令配置'
)
success('模型后缀参数配置已保存')
modelDirectivesConfig.value = normalized
success('模型参数指令配置已保存')
} catch (err) {
error(getErrorMessage(err, '保存模型后缀参数配置失败'))
log.error('保存模型后缀参数配置失败:', err)
error(getErrorMessage(err, '保存模型参数指令配置失败'))
log.error('保存模型参数指令配置失败:', err)
} finally {
saving.value = false
}
@@ -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(')
})
})

Some files were not shown because too many files have changed in this diff Show More