Merge remote-tracking branch 'origin/main' into codex/usage-pending-reasoning-reset-expiry-20260712

# Conflicts:
#	crates/aether-ai-formats/src/formats/openai/responses/mod.rs
#	crates/aether-usage/runtime/src/runtime.rs
#	frontend/src/features/usage/components/UsageRecordsTable.vue
#	frontend/src/features/usage/components/__tests__/UsageRecordsTable.spec.ts
This commit is contained in:
MMEXA
2026-07-16 23:41:58 +08:00
1027 changed files with 48510 additions and 29027 deletions
@@ -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,6 +602,7 @@ import {
EMBEDDING_API_FORMATS,
buildGlobalModelCreatePayload,
buildGlobalModelUpdatePayload,
cloneTieredPricingConfig,
} from './global-model-form-helpers'
import { tieredPricingHasImageOutputPricing } from '../utils/tiered-pricing'
@@ -779,6 +781,7 @@ function enterManualEntryMode() {
}
function reopenPresetPanel() {
clearSelection()
presetPanelCollapsed.value = false
}
@@ -1067,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> = {
@@ -1088,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)
}
@@ -1106,7 +1112,7 @@ function selectModel(model: ModelsDevModelItem) {
loadVideoPricingFromConfig()
tieredPricing.value = model.tieredPricing
? structuredClone(model.tieredPricing)
? cloneTieredPricingConfig(model.tieredPricing)
: null
presetPanelCollapsed.value = true
@@ -1119,6 +1125,7 @@ function clearSelection() {
selectedModel.value = null
form.value = defaultForm()
tieredPricing.value = null
videoResolutionPrices.value = []
billingMode.value = 'token'
}
@@ -1191,6 +1198,10 @@ 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和名称')
@@ -481,9 +481,11 @@ const props = withDefaults(defineProps<{
showCache1h?: boolean
showImagePricing?: boolean
showImageEditor?: boolean
autoFillMissingCachePrices?: boolean
}>(), {
showTokenPricing: true,
showImageEditor: true,
autoFillMissingCachePrices: true,
})
const emit = defineEmits<{
'update:modelValue': [value: TieredPricingConfig | null]
@@ -508,6 +510,7 @@ const activePricingScope = ref(STANDARD_PRICING_SCOPE)
const processingTierKeysEdited = ref(false)
const originalEmptyProcessingTiers = ref<'absent' | 'null' | 'object'>('absent')
const lastEmittedPricingJson = ref<string>('')
let initializedAutoFillMissingCachePrices: boolean | undefined
let imageOutputPriceRowId = 0
let imageOutputPriceRangeRowId = 0
@@ -608,11 +611,17 @@ const customInputValue = reactive<Record<number, string>>({})
// 初始化
watch(
() => props.modelValue,
(newValue) => {
if (lastEmittedPricingJson.value && JSON.stringify(newValue ?? null) === lastEmittedPricingJson.value) {
[() => props.modelValue, () => props.autoFillMissingCachePrices],
([newValue, autoFillMissingCachePrices]) => {
if (
initializedAutoFillMissingCachePrices === autoFillMissingCachePrices
&& lastEmittedPricingJson.value
&& JSON.stringify(newValue ?? null) === lastEmittedPricingJson.value
) {
return
}
lastEmittedPricingJson.value = ''
initializedAutoFillMissingCachePrices = autoFillMissingCachePrices
if (newValue?.tiers) {
const clonedValue = cloneJson(newValue)
basePricingConfig.value = clonedValue
@@ -726,19 +735,28 @@ function initializeScopeCacheState(scope: string, tiers: PricingTier[]) {
function createCacheMultiplierDraft(tier: PricingTier): CacheMultiplierDraft {
return {
creation: String(cacheMultiplierFromPrice(
creation: createCacheMultiplierDraftValue(
tier.input_price_per_1m,
tier.cache_creation_price_per_1m,
1.25,
)),
read: String(cacheMultiplierFromPrice(
),
read: createCacheMultiplierDraftValue(
tier.input_price_per_1m,
tier.cache_read_price_per_1m,
0.1,
)),
),
}
}
function createCacheMultiplierDraftValue(
inputPrice: number,
cachePrice: number | undefined,
fallback: number,
): string {
if (cachePrice == null && !props.autoFillMissingCachePrices) return ''
return String(cacheMultiplierFromPrice(inputPrice, cachePrice, fallback))
}
function getCachePriceMode(index: number): CachePriceMode {
return cachePriceModes.value?.[index] ?? 'multiplier'
}
@@ -756,10 +774,19 @@ function toggleCachePriceMode(index: number) {
const tier = localTiers.value[index]
const modes = cachePriceModes.value
const drafts = cacheMultiplierDrafts.value
const manualState = requireActiveCacheManualState()
if (!tier || !modes || !drafts) return
if (getCachePriceMode(index) === 'multiplier') {
tier.cache_creation_price_per_1m = getResolvedCacheCreationPrice(index)
tier.cache_read_price_per_1m = getResolvedCacheReadPrice(index)
if (props.autoFillMissingCachePrices || manualState[index]?.creation) {
tier.cache_creation_price_per_1m = getResolvedCacheCreationPrice(index)
} else {
delete tier.cache_creation_price_per_1m
}
if (props.autoFillMissingCachePrices || manualState[index]?.read) {
tier.cache_read_price_per_1m = getResolvedCacheReadPrice(index)
} else {
delete tier.cache_read_price_per_1m
}
modes[index] = 'price'
} else {
drafts[index] = createCacheMultiplierDraft(tier)
@@ -1176,18 +1203,26 @@ function buildTiersForScope(scope: string, includeAutomaticCache: boolean): Pric
const tier = cloneJson(sourceTier)
const state = manualState[index]
tier.cache_creation_price_per_1m = resolveCachePriceForScope(
scope,
index,
sourceTier,
'creation',
)
tier.cache_read_price_per_1m = resolveCachePriceForScope(
scope,
index,
sourceTier,
'read',
)
if (props.autoFillMissingCachePrices || state?.creation) {
tier.cache_creation_price_per_1m = resolveCachePriceForScope(
scope,
index,
sourceTier,
'creation',
)
} else {
delete tier.cache_creation_price_per_1m
}
if (props.autoFillMissingCachePrices || state?.read) {
tier.cache_read_price_per_1m = resolveCachePriceForScope(
scope,
index,
sourceTier,
'read',
)
} else {
delete tier.cache_read_price_per_1m
}
if (props.showCache1h) {
if (state?.cache1h && sourceTier.cache_ttl_pricing?.length) {
@@ -1479,23 +1514,33 @@ function confirmCustomInput(index: number) {
}
function updateCacheCreation(index: number, value: string | number) {
const manualState = requireActiveCacheManualState()
const hasValue = value !== '' && value !== null && value !== undefined
manualState[index] = { ...manualState[index], creation: hasValue }
if (getCachePriceMode(index) === 'multiplier') {
getCacheMultiplierDraft(index).creation = String(value ?? '')
} else {
localTiers.value[index].cache_creation_price_per_1m = value === ''
? undefined
: parseFloatInput(value)
if (hasValue) {
localTiers.value[index].cache_creation_price_per_1m = parseFloatInput(value)
} else {
delete localTiers.value[index].cache_creation_price_per_1m
}
}
syncToParent()
}
function updateCacheRead(index: number, value: string | number) {
const manualState = requireActiveCacheManualState()
const hasValue = value !== '' && value !== null && value !== undefined
manualState[index] = { ...manualState[index], read: hasValue }
if (getCachePriceMode(index) === 'multiplier') {
getCacheMultiplierDraft(index).read = String(value ?? '')
} else {
localTiers.value[index].cache_read_price_per_1m = value === ''
? undefined
: parseFloatInput(value)
if (hasValue) {
localTiers.value[index].cache_read_price_per_1m = parseFloatInput(value)
} else {
delete localTiers.value[index].cache_read_price_per_1m
}
}
syncToParent()
}
@@ -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,
},
])
})
})
@@ -1,5 +1,13 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createApp, defineComponent, h, nextTick, type App, type ComponentPublicInstance } from 'vue'
import {
createApp,
defineComponent,
h,
nextTick,
shallowRef,
type App,
type ComponentPublicInstance,
} from 'vue'
import type { TieredPricingConfig } from '@/api/endpoints/types'
import TieredPricingEditor from '../TieredPricingEditor.vue'
@@ -14,6 +22,7 @@ const mountedApps: Array<{ app: App, root: HTMLElement }> = []
function mountEditor(
modelValue: TieredPricingConfig,
options: {
autoFillMissingCachePrices?: boolean
showCache1h?: boolean
showImagePricing?: boolean
showTokenPricing?: boolean
@@ -23,6 +32,7 @@ function mountEditor(
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({
@@ -31,7 +41,8 @@ function mountEditor(
ref: (instance: unknown) => {
editor = instance as TieredPricingEditorExposed | null
},
modelValue,
modelValue: currentModelValue.value,
autoFillMissingCachePrices: options.autoFillMissingCachePrices,
showCache1h: options.showCache1h,
showImagePricing: options.showImagePricing,
showTokenPricing: options.showTokenPricing,
@@ -47,6 +58,9 @@ function mountEditor(
return {
root,
onUpdate,
setModelValue: (value: TieredPricingConfig) => {
currentModelValue.value = value
},
getFinalPricing: () => {
if (!editor) throw new Error('TieredPricingEditor ref was not mounted')
return editor.getFinalPricing()
@@ -280,6 +294,148 @@ describe('TieredPricingEditor processing tiers', () => {
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 }],
@@ -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
}
@@ -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'
@@ -322,6 +539,7 @@ type BatchActionValue =
| 'refresh_quota'
| 'clear_proxy'
| 'set_proxy'
| 'update_settings'
| 'enable'
| 'disable'
@@ -373,6 +591,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: '批量禁用账号,保留数据但停止调度。' },
@@ -394,6 +613,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)
@@ -448,6 +673,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 || '')
@@ -706,14 +933,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) {
@@ -724,6 +970,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
const actionOption = ACTION_OPTIONS.find((item) => item.value === action)
@@ -809,6 +1059,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
@@ -930,7 +1184,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)
@@ -944,12 +1198,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
@@ -1049,6 +1305,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,7 @@ import { useI18n } from '@/i18n'
import AlertDialog from '@/components/common/AlertDialog.vue'
import EndpointConditionEditor from './EndpointConditionEditor.vue'
import ProxyNodeSelect from './ProxyNodeSelect.vue'
import { getDefaultEndpointBaseUrl, getDefaultEndpointPath, normalizeEndpointApiFormat } from './endpoint-default-paths'
import { getDefaultEndpointBaseUrl, getDefaultEndpointPath } from './endpoint-default-paths'
import { fixedEndpointUpstreamStreamPolicy } from './endpoint-protocol-policy'
import { useProxyNodesStore } from '@/stores/proxy-nodes'
import {
@@ -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,
formatCodexResetCreditExpiresAt,
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()
}
// 切换密钥启用状态
@@ -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>
@@ -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,
formatCodexResetCreditExpiresAt,
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,
@@ -90,4 +121,22 @@ describe('codex reset credit display helpers', () => {
expect(getVisibleCodexResetCreditItems(snapshot, 1_700_000_300)[0]?.expiresAt)
.toBe(1_700_000_600)
})
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')
})
})
@@ -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,
@@ -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 }
@@ -261,12 +261,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
@@ -778,12 +780,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>
@@ -810,12 +814,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>
@@ -1638,41 +1644,138 @@ function getReasoningEffortTitle(record: UsageRecord): string {
return effort ? `Reasoning: ${effort}` : ''
}
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 getRequestedServiceTier(record: UsageRecord): string | null {
return normalizeServiceTier(record.service_tier)
}
function getActualServiceTier(record: UsageRecord): string | null {
return normalizeServiceTier(record.actual_service_tier)
}
function getFastBadge(record: UsageRecord): boolean {
return (getActualServiceTier(record) ?? getRequestedServiceTier(record)) === 'priority'
}
function getFastBadgeTitle(record: UsageRecord): string {
const requested = getRequestedServiceTier(record)
const actual = getActualServiceTier(record)
if (requested && actual) {
return requested === actual
? `Requested and actual service tier: ${actual}`
: `Requested service tier: ${requested}\nActual service tier: ${actual}`
function canonicalServiceTier(value: string | null): string | null {
if (value === 'auto' || value === 'default' || value === 'standard') {
return 'standard'
}
if (actual) return `Actual service tier: ${actual}`
return requested ? `Requested service tier: ${requested}` : ''
return value
}
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 serviceTierTitle = getFastBadgeTitle(record)
const requestType = getRequestTypeLabel(record)
const serviceTierTitle = getServiceTierTitle(record)
const tierSuffix = serviceTierTitle ? `\n${serviceTierTitle}` : ''
const suffix = `${requestType ? `\n操作: ${requestType}` : ''}${reasoningEffort ? `\nReasoning: ${reasoningEffort}` : ''}${tierSuffix}`
if (actualModel) {
@@ -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()
@@ -306,27 +313,63 @@ describe('UsageRecordsTable', () => {
expect(root.textContent).toContain('会话压缩')
})
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('uses the actual service tier when the provider changes processing class', () => {
const downgraded = mountUsageRecordsTable([buildRecord({
it('shows fast to standard when the provider downgrades a priority request', () => {
const root = mountUsageRecordsTable([buildRecord({
service_tier: 'priority',
actual_service_tier: 'default',
})])
expect(downgraded.textContent).not.toContain('fast')
expect(downgraded.querySelector('[title*="Requested service tier: priority"]')).not.toBeNull()
expect(downgraded.querySelector('[title*="Actual service tier: default"]')).not.toBeNull()
const upgraded = mountUsageRecordsTable([buildRecord({
service_tier: 'flex',
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',
})])
expect(upgraded.textContent).toContain('fast')
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', () => {
@@ -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()
})
})
@@ -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', () => {
@@ -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
@@ -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)
})
})