mirror of
https://github.com/fawney19/Aether.git
synced 2026-10-08 10:27:46 +08:00
Merge remote-tracking branch 'origin/main' into codex/pool-key-bulk-management-20260714
# Conflicts: # apps/aether-gateway/src/handlers/admin/request/provider/tasks.rs # frontend/src/api/endpoints/pool.ts
This commit is contained in:
@@ -1051,7 +1051,8 @@ import { useI18n } from '@/i18n'
|
||||
import AlertDialog from '@/components/common/AlertDialog.vue'
|
||||
import EndpointConditionEditor from './EndpointConditionEditor.vue'
|
||||
import ProxyNodeSelect from './ProxyNodeSelect.vue'
|
||||
import { getDefaultEndpointBaseUrl, getDefaultEndpointPath, normalizeEndpointApiFormat } from './endpoint-default-paths'
|
||||
import { getDefaultEndpointBaseUrl, getDefaultEndpointPath } from './endpoint-default-paths'
|
||||
import { fixedEndpointUpstreamStreamPolicy } from './endpoint-protocol-policy'
|
||||
import { useProxyNodesStore } from '@/stores/proxy-nodes'
|
||||
import {
|
||||
createEndpoint,
|
||||
@@ -3378,20 +3379,26 @@ async function handleToggleFormatConversion(endpoint: ProviderEndpoint) {
|
||||
|
||||
// 获取上游流式按钮的当前状态(优先使用编辑状态)
|
||||
function getCurrentUpstreamStreamPolicy(endpoint: ProviderEndpoint): string {
|
||||
if (isUpstreamStreamPolicyLocked(endpoint)) return 'force_stream'
|
||||
const fixedPolicy = getFixedUpstreamStreamPolicy(endpoint)
|
||||
if (fixedPolicy) return fixedPolicy
|
||||
const state = endpointEditStates.value[endpoint.id]
|
||||
return state?.upstreamStreamPolicy ?? getEndpointUpstreamStreamPolicy(endpoint)
|
||||
}
|
||||
|
||||
function getFixedUpstreamStreamPolicy(endpoint: ProviderEndpoint) {
|
||||
return fixedEndpointUpstreamStreamPolicy(props.provider?.provider_type, endpoint.api_format)
|
||||
}
|
||||
|
||||
function isUpstreamStreamPolicyLocked(endpoint: ProviderEndpoint): boolean {
|
||||
return (props.provider?.provider_type || '').toLowerCase() === 'codex'
|
||||
&& normalizeEndpointApiFormat(endpoint.api_format) === 'openai:responses'
|
||||
return getFixedUpstreamStreamPolicy(endpoint) !== null
|
||||
}
|
||||
|
||||
// 获取上游流式按钮的样式类
|
||||
function getUpstreamStreamButtonClass(endpoint: ProviderEndpoint): string {
|
||||
if (isUpstreamStreamPolicyLocked(endpoint)) {
|
||||
return 'h-7 w-7 text-primary/70 cursor-not-allowed'
|
||||
const fixedPolicy = getFixedUpstreamStreamPolicy(endpoint)
|
||||
if (fixedPolicy) {
|
||||
const color = fixedPolicy === 'force_stream' ? 'text-primary/70' : 'text-destructive/70'
|
||||
return `h-7 w-7 ${color} cursor-not-allowed`
|
||||
}
|
||||
const policy = getCurrentUpstreamStreamPolicy(endpoint)
|
||||
const base = 'h-7 w-7'
|
||||
@@ -3402,7 +3409,9 @@ function getUpstreamStreamButtonClass(endpoint: ProviderEndpoint): string {
|
||||
|
||||
// 获取上游流式按钮的提示文字
|
||||
function getUpstreamStreamTooltip(endpoint: ProviderEndpoint): string {
|
||||
if (isUpstreamStreamPolicyLocked(endpoint)) return legacyT('固定流式(Codex OpenAI Responses,已锁定)')
|
||||
const fixedPolicy = getFixedUpstreamStreamPolicy(endpoint)
|
||||
if (fixedPolicy === 'force_stream') return legacyT('Codex Responses 固定流式')
|
||||
if (fixedPolicy === 'force_non_stream') return legacyT('OpenAI Search 固定非流式')
|
||||
const policy = getCurrentUpstreamStreamPolicy(endpoint)
|
||||
if (policy === 'force_stream') return legacyT('固定流式(点击切换为固定非流)')
|
||||
if (policy === 'force_non_stream') return legacyT('固定非流(点击切换为跟随请求)')
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<Dialog
|
||||
:model-value="isOpen"
|
||||
title="获取上游模型"
|
||||
description="从上游获取所有密钥可用的模型列表。导入的模型需要关联全局模型后才能参与路由。"
|
||||
description="从上游获取所有密钥可用的模型列表。导入时会创建或复用全局模型,并关联到当前提供商。"
|
||||
:icon="Layers"
|
||||
size="2xl"
|
||||
@update:model-value="handleDialogUpdate"
|
||||
@@ -135,6 +135,14 @@
|
||||
>
|
||||
已存在
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="model.visibility === 'hide'"
|
||||
variant="outline"
|
||||
class="text-[10px] px-1.5 py-0 shrink-0 text-muted-foreground"
|
||||
title="运行时可调用的内部模型"
|
||||
>
|
||||
内部
|
||||
</Badge>
|
||||
</div>
|
||||
<div class="text-[11px] text-muted-foreground/60 font-mono truncate mt-0.5">
|
||||
{{ model.id }}
|
||||
|
||||
@@ -631,38 +631,20 @@ async function loadBalances() {
|
||||
}
|
||||
}
|
||||
|
||||
const LEGACY_API_FORMAT_MAP: Record<string, string> = {
|
||||
CLAUDE: 'claude:messages',
|
||||
CLAUDE_MESSAGES: 'claude:messages',
|
||||
OPENAI: 'openai:chat',
|
||||
OPENAI_RESPONSES: 'openai:responses',
|
||||
OPENAI_RESPONSES_COMPACT: 'openai:responses:compact',
|
||||
OPENAI_VIDEO: 'openai:video',
|
||||
GEMINI: 'gemini:generate_content',
|
||||
GEMINI_GENERATE_CONTENT: 'gemini:generate_content',
|
||||
GEMINI_VIDEO: 'gemini:video',
|
||||
GEMINI_FILES: 'gemini:files',
|
||||
}
|
||||
|
||||
function normalizeApiFormatKey(value: string | null | undefined): string {
|
||||
const raw = String(value || '').trim()
|
||||
if (!raw) return ''
|
||||
const normalized = normalizeApiFormatAlias(value)
|
||||
if (!normalized) return ''
|
||||
|
||||
if (raw.includes(':')) {
|
||||
const [family, kind] = raw.split(':', 2)
|
||||
const familyNorm = family?.trim().toLowerCase()
|
||||
const kindNorm = kind?.trim().toLowerCase()
|
||||
if (familyNorm === 'claude' && ['chat', 'cli', 'messages'].includes(kindNorm)) {
|
||||
if (normalized.includes(':')) {
|
||||
const { family, kind } = parseApiFormat(normalized)
|
||||
if (family === 'claude' && ['chat', 'cli', 'messages'].includes(kind)) {
|
||||
return 'claude:messages'
|
||||
}
|
||||
if (familyNorm === 'gemini' && ['chat', 'cli', 'generate_content'].includes(kindNorm)) {
|
||||
if (family === 'gemini' && ['chat', 'cli', 'generate_content'].includes(kind)) {
|
||||
return 'gemini:generate_content'
|
||||
}
|
||||
if (familyNorm && kindNorm) return `${familyNorm}:${kindNorm}`
|
||||
}
|
||||
|
||||
const legacy = raw.toUpperCase().replace(/-/g, '_')
|
||||
return LEGACY_API_FORMAT_MAP[legacy] || raw.toLowerCase()
|
||||
return normalized
|
||||
}
|
||||
|
||||
function normalizePriorityMap(
|
||||
|
||||
@@ -60,12 +60,22 @@
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ legacyT(isKeyManagedProviderType(provider.provider_type) ? '密钥管理' : '账号管理') }}
|
||||
</h3>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<Button
|
||||
v-if="endpoints.length > 0 && provider.provider_type === 'custom'"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-9"
|
||||
@click="keyBatchImportDialogOpen = true"
|
||||
>
|
||||
<ListPlus class="mr-1.5 h-3.5 w-3.5" />
|
||||
批量导入
|
||||
</Button>
|
||||
<Button
|
||||
v-if="endpoints.length > 0"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-8"
|
||||
class="h-9"
|
||||
@click="handleAddKeyToFirstEndpoint"
|
||||
>
|
||||
<Plus class="w-3.5 h-3.5 mr-1.5" />
|
||||
@@ -279,7 +289,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="getCodexResetCreditsDisplay(key)"
|
||||
v-if="getCodexResetCreditAvailableCount(key) !== null"
|
||||
class="mt-3 border-t border-border/60 pt-2"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-x-1 gap-y-1 text-[10px] leading-4 text-muted-foreground">
|
||||
@@ -823,6 +833,16 @@
|
||||
@saved="handleKeyChanged"
|
||||
/>
|
||||
|
||||
<ProviderKeyBatchImportDialog
|
||||
v-if="open && provider?.provider_type === 'custom'"
|
||||
:open="keyBatchImportDialogOpen"
|
||||
:provider-id="provider.id"
|
||||
:provider-name="provider.name"
|
||||
:available-api-formats="availableKeyApiFormats"
|
||||
@close="keyBatchImportDialogOpen = false"
|
||||
@saved="handleKeyChanged"
|
||||
/>
|
||||
|
||||
<!-- OAuth 账号对话框 -->
|
||||
<OAuthAccountDialog
|
||||
v-if="open && provider"
|
||||
@@ -913,6 +933,7 @@ import { ref, watch, computed, nextTick } from 'vue'
|
||||
import {
|
||||
Plus,
|
||||
Key,
|
||||
ListPlus,
|
||||
Loader2,
|
||||
GripVertical,
|
||||
ShieldX,
|
||||
@@ -951,6 +972,7 @@ import AlertDialog from '@/components/common/AlertDialog.vue'
|
||||
import AntigravityQuotaDialog from '@/features/providers/components/AntigravityQuotaDialog.vue'
|
||||
import FailoverRulesDialog from '@/features/providers/components/FailoverRulesDialog.vue'
|
||||
import ProviderDetailHeader from '@/features/providers/components/ProviderDetailHeader.vue'
|
||||
import ProviderKeyBatchImportDialog from '@/features/providers/components/ProviderKeyBatchImportDialog.vue'
|
||||
import ProviderKeyActionCluster from '@/features/providers/components/ProviderKeyActionCluster.vue'
|
||||
import ProviderKeyIdentityBlock from '@/features/providers/components/ProviderKeyIdentityBlock.vue'
|
||||
import ProviderMonthlyQuotaCard from '@/features/providers/components/ProviderMonthlyQuotaCard.vue'
|
||||
@@ -993,10 +1015,6 @@ import type {
|
||||
} from '@/api/endpoints/types'
|
||||
import { formatApiFormatShort } from '@/api/endpoints/types/api-format'
|
||||
import { isOAuthAccountProviderType, isKeyManagedProviderType } from '../utils/providerTypeUtils'
|
||||
import {
|
||||
isProviderQuotaAutoRefreshCoolingDown,
|
||||
markProviderQuotaAutoRefreshAttempt,
|
||||
} from '../utils/quotaAutoRefreshCooldown'
|
||||
import { getOAuthOrgBadge } from '@/utils/oauthIdentity'
|
||||
import { getOAuthRefreshFeedback } from '@/utils/oauthRefreshFeedback'
|
||||
import { formatCompactNumber } from '@/utils/format'
|
||||
@@ -1018,10 +1036,12 @@ import {
|
||||
} from '@/utils/providerKeyStatus'
|
||||
import { getGeminiCliAccountCreditsText } from '@/utils/providerKeyQuota'
|
||||
import {
|
||||
createCodexResetCreditIdempotencyKey,
|
||||
formatCodexResetCreditCount as formatCodexResetCreditCountLabel,
|
||||
formatCodexResetCreditDays,
|
||||
getCodexResetCreditAvailableCount as getCodexResetCreditAvailableCountFromSnapshot,
|
||||
getVisibleCodexResetCreditItems as getVisibleCodexResetCreditItemsFromSnapshot,
|
||||
mergeCodexQuotaDisplays,
|
||||
} from './codex-reset-credit-display'
|
||||
|
||||
// 扩展端点类型,包含密钥列表
|
||||
@@ -1085,6 +1105,7 @@ const endpointDialogOpen = ref(false)
|
||||
|
||||
// 密钥相关状态
|
||||
const keyFormDialogOpen = ref(false)
|
||||
const keyBatchImportDialogOpen = ref(false)
|
||||
const keyPermissionsDialogOpen = ref(false)
|
||||
const oauthAccountDialogOpen = ref(false)
|
||||
const oauthKeyEditDialogOpen = ref(false)
|
||||
@@ -1173,6 +1194,7 @@ const multiplierSaving = ref(false)
|
||||
const hasBlockingDialogOpen = computed(() =>
|
||||
endpointDialogOpen.value ||
|
||||
keyFormDialogOpen.value ||
|
||||
keyBatchImportDialogOpen.value ||
|
||||
keyPermissionsDialogOpen.value ||
|
||||
oauthAccountDialogOpen.value ||
|
||||
oauthKeyEditDialogOpen.value ||
|
||||
@@ -1319,6 +1341,7 @@ watch(
|
||||
// 重置所有对话框状态
|
||||
endpointDialogOpen.value = false
|
||||
keyFormDialogOpen.value = false
|
||||
keyBatchImportDialogOpen.value = false
|
||||
keyPermissionsDialogOpen.value = false
|
||||
oauthAccountDialogOpen.value = false
|
||||
oauthKeyEditDialogOpen.value = false
|
||||
@@ -1600,7 +1623,7 @@ async function handleRefreshOAuth(key: EndpointAPIKey) {
|
||||
}
|
||||
// Antigravity:token 刷新后可能完成了账号激活,触发配额获取
|
||||
// (不 emit('refresh'),避免触发全局 provider 余额刷新)
|
||||
void autoRefreshQuotaInBackground({ ignoreCooldown: true })
|
||||
void autoRefreshQuotaInBackground()
|
||||
} catch (err: unknown) {
|
||||
showError(localizedApiError(err, 'Token 刷新失败'), legacyT('错误'))
|
||||
} finally {
|
||||
@@ -1673,13 +1696,6 @@ async function handleClearOAuthInvalid(key: EndpointAPIKey) {
|
||||
}
|
||||
}
|
||||
|
||||
function createCodexResetCreditIdempotencyKey(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
throw new Error('浏览器不支持 crypto.randomUUID,无法生成安全幂等 ID')
|
||||
}
|
||||
|
||||
function codexResetCreditOutcomeFeedback(
|
||||
result: Awaited<ReturnType<typeof consumeCodexResetCredit>>,
|
||||
): { tone: 'success' | 'warning'; message: string } {
|
||||
@@ -1951,20 +1967,6 @@ function getCodexQuotaDisplayFromSnapshot(quota: QuotaStatusSnapshot | null | un
|
||||
return Object.keys(display).length > 0 ? display : null
|
||||
}
|
||||
|
||||
function getCodexQuotaDisplayUpdatedAt(display: CodexUpstreamMetadata | null | undefined): number | null {
|
||||
const updatedAt = Number(display?.updated_at)
|
||||
return Number.isFinite(updatedAt) ? updatedAt : null
|
||||
}
|
||||
|
||||
function codexDisplayHasUsage(display: CodexUpstreamMetadata | null | undefined): boolean {
|
||||
return !!display && (
|
||||
display.primary_used_percent !== undefined
|
||||
|| display.secondary_used_percent !== undefined
|
||||
|| display.spark_primary_used_percent !== undefined
|
||||
|| display.spark_secondary_used_percent !== undefined
|
||||
)
|
||||
}
|
||||
|
||||
function codexDisplayHasResetCredits(display: CodexUpstreamMetadata | null | undefined): boolean {
|
||||
const count = display?.reset_credits?.available_count
|
||||
return typeof count === 'number' && Number.isFinite(count)
|
||||
@@ -1973,20 +1975,7 @@ function codexDisplayHasResetCredits(display: CodexUpstreamMetadata | null | und
|
||||
function getCodexQuotaDisplay(key: EndpointAPIKey): CodexUpstreamMetadata | null {
|
||||
const snapshotDisplay = getCodexQuotaDisplayFromSnapshot(getQuotaSnapshotForProvider(key, 'codex'))
|
||||
const metadataDisplay = getCodexQuotaDisplayFromMetadata(key.upstream_metadata?.codex)
|
||||
|
||||
if (!snapshotDisplay) return metadataDisplay
|
||||
if (!metadataDisplay) return snapshotDisplay
|
||||
if (!codexDisplayHasUsage(snapshotDisplay) && codexDisplayHasUsage(metadataDisplay)) {
|
||||
return metadataDisplay
|
||||
}
|
||||
|
||||
const snapshotUpdatedAt = getCodexQuotaDisplayUpdatedAt(snapshotDisplay)
|
||||
const metadataUpdatedAt = getCodexQuotaDisplayUpdatedAt(metadataDisplay)
|
||||
if (metadataUpdatedAt !== null && (snapshotUpdatedAt === null || metadataUpdatedAt > snapshotUpdatedAt)) {
|
||||
return metadataDisplay
|
||||
}
|
||||
|
||||
return snapshotDisplay
|
||||
return mergeCodexQuotaDisplays(snapshotDisplay, metadataDisplay)
|
||||
}
|
||||
|
||||
function hasCodexQuotaDisplayData(key: EndpointAPIKey): boolean {
|
||||
@@ -2479,7 +2468,7 @@ function shouldAutoRefreshCodexQuota(): boolean {
|
||||
|
||||
if (isTokenExpiringSoon(key, now)) return true
|
||||
|
||||
// 只要有一个活跃 key 没有配额数据,就刷新一次
|
||||
// reset-credit 独立于 Token 刷新;这里只按账号配额缓存决定是否后台更新
|
||||
if (!hasCodexQuotaDisplayData(key)) {
|
||||
return true
|
||||
}
|
||||
@@ -2714,7 +2703,7 @@ function applyQuotaResults(
|
||||
}
|
||||
|
||||
// 通用的自动刷新配额函数(支持 Codex、Gemini CLI、Antigravity、Kiro、Windsurf 和 ChatGPT Web)
|
||||
async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean } = {}) {
|
||||
async function autoRefreshQuotaInBackground() {
|
||||
const providerId = props.providerId
|
||||
if (!providerId) return
|
||||
if (refreshingQuota.value) return
|
||||
@@ -2740,7 +2729,6 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
|
||||
shouldRefresh = shouldAutoRefreshChatGPTWebQuota()
|
||||
}
|
||||
if (!shouldRefresh) return
|
||||
if (!options.ignoreCooldown && isProviderQuotaAutoRefreshCoolingDown(providerId)) return
|
||||
|
||||
let hadCachedQuota = false
|
||||
if (providerType === 'codex') {
|
||||
@@ -2760,7 +2748,6 @@ async function autoRefreshQuotaInBackground(options: { ignoreCooldown?: boolean
|
||||
}
|
||||
|
||||
refreshingQuota.value = true
|
||||
markProviderQuotaAutoRefreshAttempt(providerId)
|
||||
try {
|
||||
const result = await refreshProviderQuota(providerId)
|
||||
const applied = applyQuotaResults(result.results)
|
||||
@@ -2804,7 +2791,7 @@ async function handleKeyChanged() {
|
||||
await Promise.all([loadEndpoints(), loadMappingPreview()])
|
||||
emit('refresh')
|
||||
// 添加/修改 key 后自动获取已支持 provider 的配额(新 key 的 upstream_metadata 为空)
|
||||
void autoRefreshQuotaInBackground({ ignoreCooldown: true })
|
||||
void autoRefreshQuotaInBackground()
|
||||
}
|
||||
|
||||
// 切换密钥启用状态
|
||||
|
||||
@@ -197,7 +197,7 @@
|
||||
:model-value="form.request_timeout ?? ''"
|
||||
type="number"
|
||||
min="1"
|
||||
max="600"
|
||||
max="1200"
|
||||
step="1"
|
||||
placeholder="300"
|
||||
@update:model-value="(v) => form.request_timeout = parseNumberInput(v)"
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
<template>
|
||||
<Dialog
|
||||
:model-value="open"
|
||||
title="批量导入 Key"
|
||||
:description="providerName ? `${providerName} · 名称和 Key 均为必填` : '名称和 Key 均为必填'"
|
||||
:icon="ListPlus"
|
||||
size="4xl"
|
||||
persistent
|
||||
@update:model-value="handleDialogUpdate"
|
||||
>
|
||||
<div class="space-y-3.5">
|
||||
<nav class="grid grid-cols-3 gap-1.5 rounded-xl bg-muted/40 p-1.5" aria-label="批量导入步骤">
|
||||
<button
|
||||
v-for="step in steps"
|
||||
:key="step.id"
|
||||
type="button"
|
||||
class="flex min-h-10 items-center justify-center gap-2 rounded-lg px-2 text-xs font-medium transition-[background-color,box-shadow,color,scale] active:scale-[0.96] disabled:cursor-default disabled:opacity-50 sm:text-sm"
|
||||
:class="currentStep === step.id
|
||||
? 'bg-background text-foreground shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]'
|
||||
: 'text-muted-foreground hover:bg-background/60 hover:text-foreground'"
|
||||
:disabled="!canNavigateToStep(step.id)"
|
||||
@click="goToStep(step.id)"
|
||||
>
|
||||
<span
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md text-[10px] tabular-nums"
|
||||
:class="currentStep === step.id ? 'bg-foreground text-background' : 'bg-muted text-muted-foreground'"
|
||||
>{{ step.id }}</span>
|
||||
<span class="truncate">{{ step.label }}</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<section
|
||||
v-if="currentStep === 1"
|
||||
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
|
||||
>
|
||||
<header class="flex min-h-14 items-center justify-between gap-3 border-b border-border/60 bg-muted/15 px-4 py-3">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">1</span>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-balance text-sm font-semibold text-foreground">粘贴名称与 Key</h3>
|
||||
<p class="text-pretty text-[11px] leading-4 text-muted-foreground">每行一条,仅接受四个短横线分隔</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge
|
||||
:variant="parsed.errors.length > 0 ? 'destructive' : parsed.items.length > 0 ? 'success' : 'secondary'"
|
||||
class="shrink-0 tabular-nums"
|
||||
>
|
||||
{{ inputStatusText }}
|
||||
</Badge>
|
||||
</header>
|
||||
|
||||
<div class="min-w-0">
|
||||
<Label for="provider-key-batch-input" class="sr-only">Key 列表</Label>
|
||||
<Textarea
|
||||
id="provider-key-batch-input"
|
||||
v-model="inputText"
|
||||
class="h-[280px] min-h-[220px] max-h-[520px] !resize-y !rounded-none !border-0 !bg-transparent !px-4 !py-4 font-mono text-[13px] leading-6 !shadow-none !ring-0 focus-visible:!ring-0"
|
||||
spellcheck="false"
|
||||
placeholder="主账号----sk-xxxx 备用账号----sk-yyyy"
|
||||
/>
|
||||
<div
|
||||
v-if="parsed.errors.length > 0"
|
||||
class="mx-4 mb-3 space-y-1 rounded-lg bg-destructive/5 px-3 py-2 text-[11px] text-destructive ring-1 ring-destructive/20"
|
||||
>
|
||||
<div
|
||||
v-for="(item, index) in parsed.errors.slice(0, 6)"
|
||||
:key="`${item.lineNumber}-${index}`"
|
||||
>
|
||||
{{ item.lineNumber ? `第 ${item.lineNumber} 行:` : '' }}{{ item.message }}
|
||||
</div>
|
||||
<div v-if="parsed.errors.length > 6" class="font-medium">
|
||||
另有 {{ parsed.errors.length - 6 }} 个问题
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2 border-t border-border/50 bg-muted/10 px-4 py-2.5 text-[11px] text-muted-foreground">
|
||||
<span class="rounded-md bg-muted px-2 py-1 font-mono text-foreground/80">名称----Key</span>
|
||||
<span>名称和 Key 都不能为空</span>
|
||||
<span class="ml-auto hidden tabular-nums sm:inline">已识别 {{ parsed.items.length }} 条</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else-if="currentStep === 2"
|
||||
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
|
||||
>
|
||||
<header class="flex min-h-[72px] items-center gap-3 px-4 py-3">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">
|
||||
2
|
||||
</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block text-sm font-semibold">统一配置</span>
|
||||
<span class="mt-1 flex flex-wrap gap-1.5">
|
||||
<span
|
||||
v-for="item in settingsSummaryItems"
|
||||
:key="item"
|
||||
class="rounded-md bg-muted px-2 py-0.5 text-[10px] leading-4 text-muted-foreground"
|
||||
>{{ item }}</span>
|
||||
</span>
|
||||
</span>
|
||||
<Badge :variant="selectedApiFormats.length > 0 ? 'success' : 'destructive'" class="ml-auto shrink-0 tabular-nums">
|
||||
{{ selectedApiFormats.length }} 种格式
|
||||
</Badge>
|
||||
</header>
|
||||
|
||||
<div class="border-t border-border/60 bg-muted/10 p-3 sm:p-4">
|
||||
<ProviderKeyImportSettingsFields
|
||||
:auth-type="authType"
|
||||
:api-formats="selectedApiFormats"
|
||||
:settings="settings"
|
||||
:available-api-formats="availableApiFormats"
|
||||
@update:auth-type="authType = $event"
|
||||
@update:api-formats="selectedApiFormats = $event"
|
||||
@update:settings="updateGlobalSettings"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else
|
||||
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
|
||||
>
|
||||
<header class="flex min-h-[72px] items-center gap-3 border-b border-border/60 bg-muted/15 px-4 py-3">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">3</span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h3 class="text-balance text-sm font-semibold">逐项确认</h3>
|
||||
<p class="text-pretty text-[11px] leading-4 text-muted-foreground">展开任意 Key 可修改内容或设置单独配置</p>
|
||||
</div>
|
||||
<div class="shrink-0 text-right text-[11px] text-muted-foreground">
|
||||
<div><span class="font-semibold tabular-nums text-foreground">{{ reviewItems.length }}</span> 个 Key</div>
|
||||
<div v-if="customizedItemCount > 0"><span class="tabular-nums">{{ customizedItemCount }}</span> 个单独配置</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-if="reviewErrorItemCount > 0"
|
||||
class="border-b border-destructive/15 bg-destructive/5 px-4 py-2 text-xs text-destructive"
|
||||
>
|
||||
{{ reviewErrorItemCount }} 个 Key 需要修正后才能导入
|
||||
</div>
|
||||
|
||||
<div class="max-h-[min(52vh,520px)] divide-y divide-border/50 overflow-y-auto overscroll-contain">
|
||||
<article
|
||||
v-for="entry in pagedReviewItems"
|
||||
:key="entry.item.lineNumber"
|
||||
class="bg-background"
|
||||
>
|
||||
<div class="flex min-h-14 items-center gap-3 px-3 py-2 sm:px-4">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-muted text-[10px] tabular-nums text-muted-foreground">
|
||||
{{ entry.index + 1 }}
|
||||
</span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<span class="truncate text-xs font-semibold">{{ entry.item.name || '未填写名称' }}</span>
|
||||
<Badge
|
||||
v-if="reviewErrorsByIndex.has(entry.index)"
|
||||
variant="destructive"
|
||||
class="shrink-0 text-[10px]"
|
||||
>需修正</Badge>
|
||||
</div>
|
||||
<div class="mt-0.5 truncate font-mono text-[10px] text-muted-foreground">{{ maskSecret(entry.item.apiKey) }}</div>
|
||||
</div>
|
||||
<div class="hidden shrink-0 items-center gap-1.5 sm:flex">
|
||||
<span class="rounded-md bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">{{ effectiveAuthLabel(entry.item) }}</span>
|
||||
<span class="rounded-md bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">{{ effectiveFormatCount(entry.item) }} 种格式</span>
|
||||
<span
|
||||
class="rounded-md px-2 py-0.5 text-[10px]"
|
||||
:class="entry.item.customized ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
|
||||
>{{ entry.item.customized ? '单独配置' : '统一配置' }}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-[background-color,color,scale] hover:bg-muted hover:text-foreground active:scale-[0.96]"
|
||||
:aria-label="`编辑 ${entry.item.name || `第 ${entry.index + 1} 项`}`"
|
||||
:title="editingItemIndex === entry.index ? '收起编辑' : '编辑此 Key'"
|
||||
@click="toggleItemEditor(entry.index)"
|
||||
>
|
||||
<Pencil class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="editingItemIndex === entry.index"
|
||||
class="space-y-4 border-t border-border/50 bg-muted/10 p-3 sm:p-4"
|
||||
>
|
||||
<div class="grid gap-3 sm:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">名称</Label>
|
||||
<Input v-model="entry.item.name" class="h-10" placeholder="必填" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">Key</Label>
|
||||
<Input v-model="entry.item.apiKey" class="h-10 font-mono text-xs" placeholder="必填" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-12 items-center justify-between gap-3 rounded-lg bg-background px-3 shadow-[0_0_0_1px_rgb(0_0_0/0.06)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]">
|
||||
<div>
|
||||
<div class="text-xs font-medium">单独配置此 Key</div>
|
||||
<div class="text-[11px] text-muted-foreground">开启后覆盖第二步中的统一配置</div>
|
||||
</div>
|
||||
<Switch
|
||||
:model-value="entry.item.customized"
|
||||
@update:model-value="setItemCustomized(entry.item, $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ProviderKeyImportSettingsFields
|
||||
v-if="entry.item.customized"
|
||||
:auth-type="entry.item.authType"
|
||||
:api-formats="entry.item.apiFormats"
|
||||
:settings="entry.item.settings"
|
||||
:available-api-formats="availableApiFormats"
|
||||
@update:auth-type="entry.item.authType = $event"
|
||||
@update:api-formats="entry.item.apiFormats = $event"
|
||||
@update:settings="entry.item.settings = $event"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="reviewErrorsByIndex.has(entry.index)"
|
||||
class="space-y-1 rounded-lg bg-destructive/5 px-3 py-2 text-[11px] text-destructive"
|
||||
>
|
||||
<div v-for="message in reviewErrorsByIndex.get(entry.index)" :key="message">{{ message }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="reviewPageCount > 1"
|
||||
class="flex min-h-12 items-center justify-between gap-3 border-t border-border/60 bg-muted/10 px-3 sm:px-4"
|
||||
>
|
||||
<Button variant="ghost" size="sm" class="h-9" :disabled="reviewPage === 1" @click="changeReviewPage(reviewPage - 1)">
|
||||
<ChevronLeft class="mr-1 h-4 w-4" />
|
||||
上一页
|
||||
</Button>
|
||||
<span class="text-[11px] tabular-nums text-muted-foreground">{{ reviewPage }} / {{ reviewPageCount }}</span>
|
||||
<Button variant="ghost" size="sm" class="h-9" :disabled="reviewPage === reviewPageCount" @click="changeReviewPage(reviewPage + 1)">
|
||||
下一页
|
||||
<ChevronRight class="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
|
||||
<Button class="w-full sm:w-auto" variant="outline" :disabled="importing" @click="handleBack">
|
||||
<ArrowLeft v-if="currentStep > 1" class="mr-2 h-4 w-4" />
|
||||
{{ currentStep === 1 ? '取消' : '上一步' }}
|
||||
</Button>
|
||||
<Button class="w-full sm:w-auto" :disabled="primaryActionDisabled" @click="handlePrimaryAction">
|
||||
<Loader2 v-if="importing" class="mr-2 h-4 w-4 animate-spin" />
|
||||
<ListPlus v-else-if="currentStep === 3" class="mr-2 h-4 w-4" />
|
||||
<ArrowRight v-else class="mr-2 h-4 w-4" />
|
||||
{{ primaryActionLabel }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ListPlus,
|
||||
Loader2,
|
||||
Pencil,
|
||||
} from 'lucide-vue-next'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Dialog,
|
||||
Input,
|
||||
Label,
|
||||
Switch,
|
||||
Textarea,
|
||||
} from '@/components/ui'
|
||||
import ProviderKeyImportSettingsFields from './ProviderKeyImportSettingsFields.vue'
|
||||
import { batchImportPoolKeys, type PoolKeySettingsPatch } from '@/api/endpoints/pool'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { parseProviderKeyBatchImport } from '@/features/providers/utils/providerKeyBatchImport'
|
||||
|
||||
type WizardStep = 1 | 2 | 3
|
||||
type AuthType = 'api_key' | 'bearer'
|
||||
type ImportSettings = Required<Pick<PoolKeySettingsPatch,
|
||||
'internal_priority' | 'rpm_limit' | 'concurrent_limit' | 'cache_ttl_minutes'
|
||||
| 'max_probe_interval_minutes' | 'is_active' | 'note' | 'proxy_node_id'
|
||||
>>
|
||||
|
||||
interface ReviewImportItem {
|
||||
lineNumber: number
|
||||
name: string
|
||||
apiKey: string
|
||||
customized: boolean
|
||||
authType: AuthType
|
||||
apiFormats: string[]
|
||||
settings: ImportSettings
|
||||
}
|
||||
|
||||
const REVIEW_PAGE_SIZE = 50
|
||||
const steps: ReadonlyArray<{ id: WizardStep; label: string }> = [
|
||||
{ id: 1, label: '导入内容' },
|
||||
{ id: 2, label: '统一配置' },
|
||||
{ id: 3, label: '逐项确认' },
|
||||
]
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
providerId: string
|
||||
providerName?: string
|
||||
availableApiFormats: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
saved: []
|
||||
}>()
|
||||
|
||||
const { success, warning, error: showError } = useToast()
|
||||
const currentStep = ref<WizardStep>(1)
|
||||
const inputText = ref('')
|
||||
const importing = ref(false)
|
||||
const authType = ref<AuthType>('api_key')
|
||||
const selectedApiFormats = ref<string[]>([])
|
||||
const settings = reactive<ImportSettings>(createDefaultSettings())
|
||||
const reviewItems = ref<ReviewImportItem[]>([])
|
||||
const reviewPage = ref(1)
|
||||
const editingItemIndex = ref<number | null>(null)
|
||||
|
||||
const parsed = computed(() => parseProviderKeyBatchImport(inputText.value))
|
||||
const canContinueInput = computed(() => (
|
||||
parsed.value.items.length > 0 && parsed.value.errors.length === 0
|
||||
))
|
||||
const canContinueSettings = computed(() => selectedApiFormats.value.length > 0)
|
||||
const inputStatusText = computed(() => {
|
||||
if (parsed.value.errors.length > 0) return `${parsed.value.errors.length} 个问题`
|
||||
if (parsed.value.items.length > 0) return `${parsed.value.items.length} 条有效`
|
||||
return '等待输入'
|
||||
})
|
||||
const reviewErrorsByIndex = computed(() => {
|
||||
const errors = new Map<number, string[]>()
|
||||
const seenNames = new Set<string>()
|
||||
const seenKeys = new Set<string>()
|
||||
|
||||
reviewItems.value.forEach((item, index) => {
|
||||
const messages: string[] = []
|
||||
const name = item.name.trim()
|
||||
const apiKey = item.apiKey.trim()
|
||||
if (!name) messages.push('名称不能为空')
|
||||
else if (name.length > 100) messages.push('名称不能超过 100 个字符')
|
||||
else if (seenNames.has(name)) messages.push('名称与前面的 Key 重复')
|
||||
else seenNames.add(name)
|
||||
|
||||
if (!apiKey) messages.push('Key 不能为空')
|
||||
else if (seenKeys.has(apiKey)) messages.push('Key 与前面的 Key 重复')
|
||||
else seenKeys.add(apiKey)
|
||||
|
||||
if (item.customized && item.apiFormats.length === 0) {
|
||||
messages.push('单独配置时至少选择一种 API 格式')
|
||||
}
|
||||
if (messages.length > 0) errors.set(index, messages)
|
||||
})
|
||||
return errors
|
||||
})
|
||||
const reviewErrorItemCount = computed(() => reviewErrorsByIndex.value.size)
|
||||
const customizedItemCount = computed(() => (
|
||||
reviewItems.value.filter(item => item.customized).length
|
||||
))
|
||||
const reviewPageCount = computed(() => (
|
||||
Math.max(1, Math.ceil(reviewItems.value.length / REVIEW_PAGE_SIZE))
|
||||
))
|
||||
const pagedReviewItems = computed(() => {
|
||||
const start = (reviewPage.value - 1) * REVIEW_PAGE_SIZE
|
||||
return reviewItems.value
|
||||
.slice(start, start + REVIEW_PAGE_SIZE)
|
||||
.map((item, offset) => ({ item, index: start + offset }))
|
||||
})
|
||||
const canImport = computed(() => (
|
||||
!importing.value
|
||||
&& reviewItems.value.length > 0
|
||||
&& reviewErrorsByIndex.value.size === 0
|
||||
&& canContinueSettings.value
|
||||
))
|
||||
const primaryActionDisabled = computed(() => {
|
||||
if (importing.value) return true
|
||||
if (currentStep.value === 1) return !canContinueInput.value
|
||||
if (currentStep.value === 2) return !canContinueSettings.value
|
||||
return !canImport.value
|
||||
})
|
||||
const primaryActionLabel = computed(() => {
|
||||
if (importing.value) return '正在导入...'
|
||||
if (currentStep.value === 1) return '下一步:统一配置'
|
||||
if (currentStep.value === 2) return '下一步:逐项确认'
|
||||
return `导入 ${reviewItems.value.length} 个 Key`
|
||||
})
|
||||
const settingsSummaryItems = computed(() => {
|
||||
const rpm = settings.rpm_limit == null ? 'RPM 自适应' : `RPM ${settings.rpm_limit}`
|
||||
const concurrent = settings.concurrent_limit == null || settings.concurrent_limit === 0
|
||||
? '不限并发'
|
||||
: `并发 ${settings.concurrent_limit}`
|
||||
const proxy = settings.proxy_node_id ? '独立代理' : '沿用 Provider 代理'
|
||||
return [authType.value === 'bearer' ? 'Bearer' : 'API Key', rpm, concurrent, proxy]
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
currentStep.value = 1
|
||||
inputText.value = ''
|
||||
importing.value = false
|
||||
authType.value = 'api_key'
|
||||
selectedApiFormats.value = [...props.availableApiFormats]
|
||||
Object.assign(settings, createDefaultSettings())
|
||||
reviewItems.value = []
|
||||
reviewPage.value = 1
|
||||
editingItemIndex.value = null
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(inputText, () => {
|
||||
reviewItems.value = []
|
||||
reviewPage.value = 1
|
||||
editingItemIndex.value = null
|
||||
})
|
||||
|
||||
function createDefaultSettings(): ImportSettings {
|
||||
return {
|
||||
internal_priority: 50,
|
||||
rpm_limit: null,
|
||||
concurrent_limit: null,
|
||||
cache_ttl_minutes: 5,
|
||||
max_probe_interval_minutes: 32,
|
||||
is_active: true,
|
||||
note: '',
|
||||
proxy_node_id: '',
|
||||
}
|
||||
}
|
||||
|
||||
function copySettings(source: ImportSettings): ImportSettings {
|
||||
return { ...source }
|
||||
}
|
||||
|
||||
function buildSettingsPayload(
|
||||
source: ImportSettings,
|
||||
includeEmptyProxy = false,
|
||||
): PoolKeySettingsPatch {
|
||||
return {
|
||||
internal_priority: source.internal_priority,
|
||||
rpm_limit: source.rpm_limit,
|
||||
concurrent_limit: source.concurrent_limit,
|
||||
cache_ttl_minutes: source.cache_ttl_minutes,
|
||||
max_probe_interval_minutes: source.max_probe_interval_minutes,
|
||||
is_active: source.is_active,
|
||||
note: source.note.trim() || null,
|
||||
...((source.proxy_node_id || includeEmptyProxy)
|
||||
? { proxy_node_id: source.proxy_node_id || null }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
function handleDialogUpdate(value: boolean): void {
|
||||
if (!value) emit('close')
|
||||
}
|
||||
|
||||
function canNavigateToStep(step: WizardStep): boolean {
|
||||
return step <= currentStep.value
|
||||
}
|
||||
|
||||
function goToStep(step: WizardStep): void {
|
||||
if (canNavigateToStep(step)) currentStep.value = step
|
||||
}
|
||||
|
||||
function handleBack(): void {
|
||||
if (currentStep.value === 1) {
|
||||
emit('close')
|
||||
return
|
||||
}
|
||||
currentStep.value = (currentStep.value - 1) as WizardStep
|
||||
}
|
||||
|
||||
function handlePrimaryAction(): void {
|
||||
if (primaryActionDisabled.value) return
|
||||
if (currentStep.value === 1) {
|
||||
currentStep.value = 2
|
||||
return
|
||||
}
|
||||
if (currentStep.value === 2) {
|
||||
prepareReviewItems()
|
||||
currentStep.value = 3
|
||||
return
|
||||
}
|
||||
void submitImport()
|
||||
}
|
||||
|
||||
function prepareReviewItems(): void {
|
||||
if (reviewItems.value.length > 0) return
|
||||
reviewItems.value = parsed.value.items.map(item => ({
|
||||
lineNumber: item.lineNumber,
|
||||
name: item.name,
|
||||
apiKey: item.apiKey,
|
||||
customized: false,
|
||||
authType: authType.value,
|
||||
apiFormats: [...selectedApiFormats.value],
|
||||
settings: copySettings(settings),
|
||||
}))
|
||||
reviewPage.value = 1
|
||||
editingItemIndex.value = null
|
||||
}
|
||||
|
||||
function toggleItemEditor(index: number): void {
|
||||
editingItemIndex.value = editingItemIndex.value === index ? null : index
|
||||
}
|
||||
|
||||
function setItemCustomized(item: ReviewImportItem, customized: boolean): void {
|
||||
item.customized = customized
|
||||
if (!customized) return
|
||||
item.authType = authType.value
|
||||
item.apiFormats = [...selectedApiFormats.value]
|
||||
item.settings = copySettings(settings)
|
||||
}
|
||||
|
||||
function changeReviewPage(page: number): void {
|
||||
reviewPage.value = Math.min(Math.max(page, 1), reviewPageCount.value)
|
||||
editingItemIndex.value = null
|
||||
}
|
||||
|
||||
function effectiveAuthLabel(item: ReviewImportItem): string {
|
||||
const resolved = item.customized ? item.authType : authType.value
|
||||
return resolved === 'bearer' ? 'Bearer' : 'API Key'
|
||||
}
|
||||
|
||||
function effectiveFormatCount(item: ReviewImportItem): number {
|
||||
return item.customized ? item.apiFormats.length : selectedApiFormats.value.length
|
||||
}
|
||||
|
||||
function updateGlobalSettings(nextSettings: ImportSettings): void {
|
||||
Object.assign(settings, nextSettings)
|
||||
}
|
||||
|
||||
function maskSecret(secret: string): string {
|
||||
if (secret.length <= 10) return `${secret.slice(0, 3)}•••`
|
||||
return `${secret.slice(0, 6)}••••${secret.slice(-4)}`
|
||||
}
|
||||
|
||||
async function submitImport(): Promise<void> {
|
||||
if (!canImport.value) return
|
||||
importing.value = true
|
||||
try {
|
||||
const result = await batchImportPoolKeys(props.providerId, {
|
||||
keys: reviewItems.value.map(item => ({
|
||||
name: item.name.trim(),
|
||||
api_key: item.apiKey.trim(),
|
||||
auth_type: item.customized ? item.authType : authType.value,
|
||||
...(item.customized
|
||||
? {
|
||||
api_formats: item.apiFormats,
|
||||
settings: buildSettingsPayload(item.settings, true),
|
||||
}
|
||||
: {}),
|
||||
})),
|
||||
api_formats: selectedApiFormats.value,
|
||||
settings: buildSettingsPayload(settings),
|
||||
})
|
||||
if (result.imported > 0) emit('saved')
|
||||
if (result.errors.length > 0) {
|
||||
warning(`已导入 ${result.imported} 个,${result.errors.length} 个失败`)
|
||||
return
|
||||
}
|
||||
success(`已导入 ${result.imported} 个 Key`)
|
||||
emit('close')
|
||||
} catch (error) {
|
||||
showError(parseApiError(error, '批量导入 Key 失败'))
|
||||
} finally {
|
||||
importing.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,181 @@
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<Label class="text-xs font-medium">支持的 API 格式</Label>
|
||||
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<label
|
||||
v-for="format in availableApiFormats"
|
||||
:key="format"
|
||||
class="flex min-h-10 cursor-pointer items-center gap-2 rounded-lg bg-background px-3 text-xs transition-[box-shadow,background-color]"
|
||||
:class="apiFormats.includes(format)
|
||||
? 'bg-primary/5 shadow-[0_0_0_1px_rgb(0_0_0/0.10),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.12)]'
|
||||
: 'shadow-[0_0_0_1px_rgb(0_0_0/0.06)] hover:bg-muted/30 hover:shadow-[0_0_0_1px_rgb(0_0_0/0.10)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]'"
|
||||
>
|
||||
<Checkbox
|
||||
:checked="apiFormats.includes(format)"
|
||||
@update:checked="(checked) => toggleApiFormat(format, checked === true)"
|
||||
/>
|
||||
<span class="truncate">{{ formatApiFormat(format) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">认证类型</Label>
|
||||
<Select v-model="authTypeModel">
|
||||
<SelectTrigger class="h-10">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="api_key">API Key</SelectItem>
|
||||
<SelectItem value="bearer">Bearer Token</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">优先级</Label>
|
||||
<Input
|
||||
:model-value="settings.internal_priority"
|
||||
type="number"
|
||||
min="0"
|
||||
class="h-10"
|
||||
@update:model-value="updateSetting('internal_priority', parseNumberInput($event, { min: 0 }) ?? 50)"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">RPM 限制</Label>
|
||||
<Input
|
||||
:model-value="settings.rpm_limit ?? ''"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10000"
|
||||
class="h-10"
|
||||
placeholder="自适应"
|
||||
@update:model-value="updateSetting('rpm_limit', parseNullableNumberInput($event, { min: 1, max: 10000 }))"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">并发请求上限</Label>
|
||||
<Input
|
||||
:model-value="settings.concurrent_limit ?? ''"
|
||||
type="number"
|
||||
min="0"
|
||||
class="h-10"
|
||||
placeholder="不限制"
|
||||
@update:model-value="updateSetting('concurrent_limit', parseNullableNumberInput($event, { min: 0 }))"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">缓存 TTL(分钟)</Label>
|
||||
<Input
|
||||
:model-value="settings.cache_ttl_minutes"
|
||||
type="number"
|
||||
min="0"
|
||||
max="60"
|
||||
class="h-10"
|
||||
@update:model-value="updateSetting('cache_ttl_minutes', parseNumberInput($event, { min: 0, max: 60 }) ?? 5)"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">熔断探测(分钟)</Label>
|
||||
<Input
|
||||
:model-value="settings.max_probe_interval_minutes"
|
||||
type="number"
|
||||
min="0"
|
||||
max="32"
|
||||
class="h-10"
|
||||
@update:model-value="updateSetting('max_probe_interval_minutes', parseNumberInput($event, { min: 0, max: 32 }) ?? 32)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 sm:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">代理节点</Label>
|
||||
<ProxyNodeSelect
|
||||
:model-value="settings.proxy_node_id"
|
||||
trigger-class="h-10"
|
||||
@update:model-value="updateSetting('proxy_node_id', $event)"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">备注</Label>
|
||||
<Input
|
||||
:model-value="settings.note"
|
||||
class="h-10"
|
||||
placeholder="可选"
|
||||
@update:model-value="updateSetting('note', String($event))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-12 items-center justify-between gap-3 rounded-lg bg-background px-3 shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]">
|
||||
<div>
|
||||
<div class="text-xs font-medium">导入后立即启用</div>
|
||||
<div class="text-[11px] text-muted-foreground">关闭后仍会创建,但不会进入调度</div>
|
||||
</div>
|
||||
<Switch
|
||||
:model-value="settings.is_active"
|
||||
@update:model-value="updateSetting('is_active', $event)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
Checkbox,
|
||||
Input,
|
||||
Label,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
Switch,
|
||||
} from '@/components/ui'
|
||||
import type { PoolKeySettingsPatch } from '@/api/endpoints/pool'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
import { parseNullableNumberInput, parseNumberInput } from '@/utils/form'
|
||||
import ProxyNodeSelect from './ProxyNodeSelect.vue'
|
||||
|
||||
type AuthType = 'api_key' | 'bearer'
|
||||
type ImportSettings = Required<Pick<PoolKeySettingsPatch,
|
||||
'internal_priority' | 'rpm_limit' | 'concurrent_limit' | 'cache_ttl_minutes'
|
||||
| 'max_probe_interval_minutes' | 'is_active' | 'note' | 'proxy_node_id'
|
||||
>>
|
||||
|
||||
const props = defineProps<{
|
||||
authType: AuthType
|
||||
apiFormats: string[]
|
||||
settings: ImportSettings
|
||||
availableApiFormats: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:authType': [value: AuthType]
|
||||
'update:apiFormats': [value: string[]]
|
||||
'update:settings': [value: ImportSettings]
|
||||
}>()
|
||||
|
||||
const authTypeModel = computed<AuthType>({
|
||||
get: () => props.authType,
|
||||
set: value => emit('update:authType', value),
|
||||
})
|
||||
|
||||
function toggleApiFormat(format: string, checked: boolean): void {
|
||||
const selected = new Set(props.apiFormats)
|
||||
if (checked) selected.add(format)
|
||||
else selected.delete(format)
|
||||
emit('update:apiFormats', props.availableApiFormats.filter(item => selected.has(item)))
|
||||
}
|
||||
|
||||
function updateSetting<Key extends keyof ImportSettings>(
|
||||
key: Key,
|
||||
value: ImportSettings[Key],
|
||||
): void {
|
||||
emit('update:settings', { ...props.settings, [key]: value })
|
||||
}
|
||||
</script>
|
||||
@@ -321,6 +321,7 @@ import { parseNumberInput, sortResolutionEntries } from '@/utils/form'
|
||||
import { createModel, updateModel, getProviderModels } from '@/api/endpoints/models'
|
||||
import { createGlobalModel, listGlobalModels, type GlobalModelResponse } from '@/api/global-models'
|
||||
import TieredPricingEditor from '@/features/models/components/TieredPricingEditor.vue'
|
||||
import { tieredPricingHasImageOutputPricing } from '@/features/models/utils/tiered-pricing'
|
||||
import type { Model, TieredPricingConfig } from '@/api/endpoints'
|
||||
import {
|
||||
buildProviderModelCreatePayload,
|
||||
@@ -572,31 +573,6 @@ function modelSupportsImageGeneration(model: {
|
||||
|| tieredPricingHasImageOutputPricing(model.effective_tiered_pricing)
|
||||
}
|
||||
|
||||
function tieredPricingHasImageOutputPricing(pricing: TieredPricingConfig | null | undefined): boolean {
|
||||
if (!pricing) return false
|
||||
if (toFinitePrice(pricing.image_output_price_default) !== null) return true
|
||||
if (Object.values(pricing.image_output_prices || {}).some((prices) => {
|
||||
if (!prices || typeof prices !== 'object') return false
|
||||
return Object.values(prices).some((price) => toFinitePrice(price) !== null)
|
||||
})) return true
|
||||
return (pricing.image_output_price_ranges || []).some((range) => {
|
||||
if (!range || typeof range !== 'object') return false
|
||||
const prices = range.prices && typeof range.prices === 'object'
|
||||
? range.prices
|
||||
: range as Record<string, unknown>
|
||||
return Object.values(prices).some((price) => toFinitePrice(price) !== null)
|
||||
})
|
||||
}
|
||||
|
||||
function toFinitePrice(value: unknown): number | null {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function setImageGenerationEnabled(value: boolean | 'indeterminate') {
|
||||
const enabled = value === true
|
||||
imageGenerationExplicitOverride.value = enabled
|
||||
@@ -812,6 +788,12 @@ async function handleSubmit() {
|
||||
return
|
||||
}
|
||||
|
||||
const pricingValidationError = tieredPricingEditorRef.value?.getValidationError()
|
||||
if (pricingValidationError) {
|
||||
showError(pricingValidationError, '价格配置错误')
|
||||
return
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 获取包含自动计算缓存价格的最终数据
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, onMounted } from 'vue'
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
@@ -67,8 +67,10 @@ const nodeOptions = computed(() => {
|
||||
|
||||
/** 供父组件调用:启用代理时懒加载节点列表 */
|
||||
function ensureLoaded() {
|
||||
proxyNodesStore.ensureLoaded()
|
||||
return proxyNodesStore.ensureLoaded()
|
||||
}
|
||||
|
||||
onMounted(ensureLoaded)
|
||||
|
||||
defineExpose({ ensureLoaded })
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createApp, defineComponent, h } from 'vue'
|
||||
|
||||
import ProxyNodeSelect from '@/features/providers/components/ProxyNodeSelect.vue'
|
||||
import { createI18n } from '@/i18n'
|
||||
|
||||
const proxyNodesStore = vi.hoisted(() => ({
|
||||
loading: false,
|
||||
nodes: [],
|
||||
onlineNodes: [],
|
||||
ensureLoaded: vi.fn(() => Promise.resolve()),
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/proxy-nodes', () => ({
|
||||
useProxyNodesStore: () => proxyNodesStore,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui', async () => {
|
||||
const { defineComponent, h } = await import('vue')
|
||||
const passthrough = (name: string) => defineComponent({
|
||||
name,
|
||||
setup(_, { slots }) {
|
||||
return () => h('div', slots.default?.())
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
Select: passthrough('SelectStub'),
|
||||
SelectTrigger: passthrough('SelectTriggerStub'),
|
||||
SelectValue: passthrough('SelectValueStub'),
|
||||
SelectContent: passthrough('SelectContentStub'),
|
||||
SelectItem: passthrough('SelectItemStub'),
|
||||
}
|
||||
})
|
||||
|
||||
describe('ProxyNodeSelect', () => {
|
||||
it('loads proxy nodes when mounted', () => {
|
||||
const root = document.createElement('div')
|
||||
const app = createApp(defineComponent({
|
||||
setup() {
|
||||
return () => h(ProxyNodeSelect, { modelValue: '' })
|
||||
},
|
||||
}))
|
||||
|
||||
app.use(createI18n())
|
||||
app.mount(root)
|
||||
|
||||
expect(proxyNodesStore.ensureLoaded).toHaveBeenCalledTimes(1)
|
||||
|
||||
app.unmount()
|
||||
})
|
||||
})
|
||||
+49
@@ -1,14 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
createCodexResetCreditIdempotencyKey,
|
||||
formatCodexResetCreditCount,
|
||||
formatCodexResetCreditDays,
|
||||
getCodexResetCreditAvailableCount,
|
||||
getVisibleCodexResetCreditItems,
|
||||
mergeCodexQuotaDisplays,
|
||||
} from '@/features/providers/components/codex-reset-credit-display'
|
||||
import type { QuotaResetCreditsSnapshot } from '@/api/endpoints/types'
|
||||
|
||||
describe('codex reset credit display helpers', () => {
|
||||
it('keeps reset credits and usage windows when snapshot sources are partially populated', () => {
|
||||
const merged = mergeCodexQuotaDisplays(
|
||||
{
|
||||
updated_at: 1_700_000_100,
|
||||
primary_used_percent: 25,
|
||||
reset_credits: {
|
||||
available_count: 2,
|
||||
},
|
||||
},
|
||||
{
|
||||
updated_at: 1_700_000_000,
|
||||
secondary_used_percent: 40,
|
||||
reset_credits: {
|
||||
credits: [{ id: 'credit-1', expires_at: 1_700_086_400 }],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(merged).toMatchObject({
|
||||
updated_at: 1_700_000_100,
|
||||
primary_used_percent: 25,
|
||||
secondary_used_percent: 40,
|
||||
reset_credits: {
|
||||
available_count: 2,
|
||||
credits: [{ id: 'credit-1', expires_at: 1_700_086_400 }],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps zero available credits displayable but non-positive detail items hidden', () => {
|
||||
const snapshot: QuotaResetCreditsSnapshot = {
|
||||
available_count: 0,
|
||||
@@ -78,4 +109,22 @@ describe('codex reset credit display helpers', () => {
|
||||
expect(formatCodexResetCreditDays(1)).toBe('1天')
|
||||
expect(formatCodexResetCreditDays(86_401)).toBe('2天')
|
||||
})
|
||||
|
||||
it('generates a UUID v4 with secure random bytes when randomUUID is unavailable', () => {
|
||||
const idempotencyKey = createCodexResetCreditIdempotencyKey({
|
||||
getRandomValues(array) {
|
||||
array.set(Array.from({ length: 16 }, (_, index) => index))
|
||||
return array
|
||||
},
|
||||
})
|
||||
|
||||
expect(idempotencyKey).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f')
|
||||
})
|
||||
|
||||
it('prefers the browser randomUUID implementation when available', () => {
|
||||
expect(createCodexResetCreditIdempotencyKey({
|
||||
randomUUID: () => 'existing-random-uuid',
|
||||
getRandomValues: array => array,
|
||||
})).toBe('existing-random-uuid')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ const apiFormats = [
|
||||
{ value: 'gemini:embedding', default_path: '/v1beta/models/{model}:embedContent' },
|
||||
{ value: 'gemini:video', default_path: '/v1beta/models/{model}:predictLongRunning' },
|
||||
{ value: 'openai:responses', default_path: '/v1/responses' },
|
||||
{ value: 'openai:search', default_path: '/v1/alpha/search' },
|
||||
{ value: 'openai:embedding', default_path: '/v1/embeddings' },
|
||||
{ value: 'openai:rerank', default_path: '/v1/rerank' },
|
||||
{ value: 'openai:image', default_path: '/v1/images/generations' },
|
||||
@@ -75,6 +76,30 @@ describe('endpoint default paths', () => {
|
||||
})).toBe('/responses')
|
||||
})
|
||||
|
||||
it('uses the Search path relative to OpenAI and Codex api roots', () => {
|
||||
expect(getDefaultEndpointBaseUrl({
|
||||
apiFormat: 'openai:search',
|
||||
baseUrl: 'https://api.openai.com',
|
||||
})).toBe('https://api.openai.com/v1')
|
||||
expect(getDefaultEndpointPath({
|
||||
apiFormat: 'openai:search',
|
||||
providerType: 'openai',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
apiFormats,
|
||||
})).toBe('/alpha/search')
|
||||
|
||||
expect(getDefaultEndpointBaseUrl({
|
||||
apiFormat: 'openai:search',
|
||||
baseUrl: 'https://chatgpt.com/backend-api/codex',
|
||||
})).toBe('https://chatgpt.com/backend-api/codex')
|
||||
expect(getDefaultEndpointPath({
|
||||
apiFormat: 'openai:search',
|
||||
providerType: 'codex',
|
||||
baseUrl: 'https://chatgpt.com/backend-api/codex',
|
||||
apiFormats,
|
||||
})).toBe('/alpha/search')
|
||||
})
|
||||
|
||||
it('drops /v1 from API-root defaults because base URL is the API root', () => {
|
||||
expect(getDefaultEndpointPath({
|
||||
apiFormat: 'openai:chat',
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { fixedEndpointUpstreamStreamPolicy } from '../endpoint-protocol-policy'
|
||||
|
||||
describe('fixedEndpointUpstreamStreamPolicy', () => {
|
||||
it('uses the fixed Codex transport mode for each protocol', () => {
|
||||
expect(fixedEndpointUpstreamStreamPolicy('codex', 'openai:responses')).toBe('force_stream')
|
||||
expect(fixedEndpointUpstreamStreamPolicy('codex', 'openai:search')).toBe('force_non_stream')
|
||||
})
|
||||
|
||||
it('applies Search synchronization by format and keeps other formats configurable', () => {
|
||||
expect(fixedEndpointUpstreamStreamPolicy('custom', 'openai:search')).toBe('force_non_stream')
|
||||
expect(fixedEndpointUpstreamStreamPolicy('codex', 'openai:responses:compact')).toBeNull()
|
||||
})
|
||||
})
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
function readSource(path: string): string {
|
||||
return readFileSync(resolve(process.cwd(), path), 'utf8')
|
||||
}
|
||||
|
||||
describe('provider key batch import UI contract', () => {
|
||||
it('shows the entry only for custom providers', () => {
|
||||
const source = readSource('src/features/providers/components/ProviderDetailDrawer.vue')
|
||||
|
||||
expect(source).toContain("provider.provider_type === 'custom'")
|
||||
expect(source).toContain('<ProviderKeyBatchImportDialog')
|
||||
expect(source).toContain('keyBatchImportDialogOpen')
|
||||
})
|
||||
|
||||
it('uses a three-step flow with per-key review overrides', () => {
|
||||
const source = readSource('src/features/providers/components/ProviderKeyBatchImportDialog.vue')
|
||||
|
||||
expect(source).toContain('parseProviderKeyBatchImport')
|
||||
expect(source).toContain("{ id: 3, label: '逐项确认' }")
|
||||
expect(source).toContain('ProviderKeyImportSettingsFields')
|
||||
expect(source).toContain('REVIEW_PAGE_SIZE')
|
||||
expect(source).toContain('item.customized')
|
||||
expect(source).toContain('api_formats: item.apiFormats')
|
||||
expect(source).toContain('batchImportPoolKeys')
|
||||
expect(source).not.toContain('MAX_BATCH_IMPORT_KEYS')
|
||||
|
||||
const fieldsSource = readSource('src/features/providers/components/ProviderKeyImportSettingsFields.vue')
|
||||
expect(fieldsSource).toContain('settings.max_probe_interval_minutes')
|
||||
expect(fieldsSource).toContain('settings.proxy_node_id')
|
||||
})
|
||||
|
||||
it('uses selective update_settings in pool batch management', () => {
|
||||
const source = readSource('src/features/pool/components/PoolAccountBatchDialog.vue')
|
||||
|
||||
expect(source).toContain("selectedAction === 'update_settings'")
|
||||
expect(source).toContain('buildPoolKeySettingsPatch')
|
||||
expect(source).toContain("confirmAndExecuteAction('update_settings')")
|
||||
expect(source).toContain('仅更新已勾选字段')
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,41 @@
|
||||
import type {
|
||||
CodexUpstreamMetadata,
|
||||
QuotaResetCreditSnapshot,
|
||||
QuotaResetCreditsSnapshot,
|
||||
} from '@/api/endpoints/types'
|
||||
|
||||
function codexQuotaUpdatedAt(display: CodexUpstreamMetadata | null | undefined): number | null {
|
||||
const updatedAt = Number(display?.updated_at)
|
||||
return Number.isFinite(updatedAt) ? updatedAt : null
|
||||
}
|
||||
|
||||
export function mergeCodexQuotaDisplays(
|
||||
snapshotDisplay: CodexUpstreamMetadata | null | undefined,
|
||||
metadataDisplay: CodexUpstreamMetadata | null | undefined,
|
||||
): CodexUpstreamMetadata | null {
|
||||
if (!snapshotDisplay) return metadataDisplay ?? null
|
||||
if (!metadataDisplay) return snapshotDisplay
|
||||
|
||||
const snapshotUpdatedAt = codexQuotaUpdatedAt(snapshotDisplay)
|
||||
const metadataUpdatedAt = codexQuotaUpdatedAt(metadataDisplay)
|
||||
const metadataIsNewer = metadataUpdatedAt !== null
|
||||
&& (snapshotUpdatedAt === null || metadataUpdatedAt > snapshotUpdatedAt)
|
||||
const preferred = metadataIsNewer ? metadataDisplay : snapshotDisplay
|
||||
const fallback = metadataIsNewer ? snapshotDisplay : metadataDisplay
|
||||
const resetCredits = preferred.reset_credits || fallback.reset_credits
|
||||
? {
|
||||
...fallback.reset_credits,
|
||||
...preferred.reset_credits,
|
||||
}
|
||||
: undefined
|
||||
|
||||
return {
|
||||
...fallback,
|
||||
...preferred,
|
||||
...(resetCredits ? { reset_credits: resetCredits } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export interface CodexResetCreditDisplayItem {
|
||||
id?: string | null
|
||||
displayKey: string
|
||||
@@ -28,6 +61,27 @@ export function formatCodexResetCreditCount(count: number | null | undefined): s
|
||||
return `共 ${count ?? 0} 次机会`
|
||||
}
|
||||
|
||||
interface CodexResetCreditCrypto {
|
||||
randomUUID?: () => string
|
||||
getRandomValues: (array: Uint8Array) => Uint8Array
|
||||
}
|
||||
|
||||
export function createCodexResetCreditIdempotencyKey(
|
||||
cryptoSource: CodexResetCreditCrypto | undefined = globalThis.crypto,
|
||||
): string {
|
||||
const randomUUID = cryptoSource?.randomUUID?.bind(cryptoSource)
|
||||
if (randomUUID) return randomUUID()
|
||||
if (!cryptoSource) {
|
||||
throw new Error('浏览器不支持安全随机数,无法生成幂等 ID')
|
||||
}
|
||||
|
||||
const bytes = cryptoSource.getRandomValues(new Uint8Array(16))
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||||
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||||
}
|
||||
|
||||
function codexResetCreditRemainingSeconds(
|
||||
item: QuotaResetCreditSnapshot,
|
||||
snapshot: QuotaResetCreditsSnapshot,
|
||||
|
||||
@@ -90,6 +90,7 @@ function usesVersionedApiRootByDefault(apiFormat: string): boolean {
|
||||
return apiFormat === 'openai:chat'
|
||||
|| apiFormat === 'openai:responses'
|
||||
|| apiFormat === 'openai:responses:compact'
|
||||
|| apiFormat === 'openai:search'
|
||||
|| apiFormat === 'openai:embedding'
|
||||
|| apiFormat === 'openai:rerank'
|
||||
|| apiFormat === 'openai:image'
|
||||
@@ -129,6 +130,7 @@ function skipsVersionedApiRootDefault(apiFormat: string, baseUrl: string): boole
|
||||
return false
|
||||
}
|
||||
return isDeepSeekApiRoot(baseUrl)
|
||||
|| isCodexUrl(baseUrl)
|
||||
|| isBigModelCodingApiRoot(baseUrl)
|
||||
|| isGoogleOpenAiCompatApiRoot(baseUrl)
|
||||
|| isVertexOpenAiCompatApiRoot(baseUrl)
|
||||
@@ -198,6 +200,9 @@ export function getDefaultEndpointPath(params: {
|
||||
if (normalizedApiFormat === 'openai:responses' && isCodex) {
|
||||
return '/responses'
|
||||
}
|
||||
if (normalizedApiFormat === 'openai:search' && isCodex) {
|
||||
return '/alpha/search'
|
||||
}
|
||||
if (usesVersionedApiRootByDefault(normalizedApiFormat)) {
|
||||
return stripVersionPrefixForApiRoot(defaultPath)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { normalizeEndpointApiFormat } from './endpoint-default-paths'
|
||||
|
||||
export type FixedUpstreamStreamPolicy = 'force_stream' | 'force_non_stream'
|
||||
|
||||
export function fixedEndpointUpstreamStreamPolicy(
|
||||
providerType: string | null | undefined,
|
||||
apiFormat: string,
|
||||
): FixedUpstreamStreamPolicy | null {
|
||||
const normalizedApiFormat = normalizeEndpointApiFormat(apiFormat)
|
||||
if (normalizedApiFormat === 'openai:search') return 'force_non_stream'
|
||||
if (providerType?.trim().toLowerCase() !== 'codex') return null
|
||||
|
||||
switch (normalizedApiFormat) {
|
||||
case 'openai:responses':
|
||||
return 'force_stream'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -366,12 +366,12 @@ import { type EndpointAPIKey } from '@/api/endpoints/keys'
|
||||
import { updateModel } from '@/api/endpoints/models'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import type { ProviderWithEndpointsSummary } from '@/api/endpoints'
|
||||
import { normalizeApiFormatAlias } from '@/api/endpoints/types/api-format'
|
||||
import {
|
||||
buildDefaultModelTestRequestHeaders,
|
||||
buildDefaultModelTestRequestBody,
|
||||
isModelTestableApiFormat,
|
||||
isModelTestableEndpoint,
|
||||
modelTestMappingScopeMatchesEndpoint,
|
||||
parseModelTestRequestHeadersDraft,
|
||||
parseModelTestRequestBodyDraft,
|
||||
selectPreferredModelTestEndpoint,
|
||||
@@ -852,16 +852,11 @@ function scopedMappingEndpoints(item: CombinedMapping): ProviderEndpoint[] {
|
||||
const group = item.group
|
||||
if (!group) return activeEndpoints.value
|
||||
|
||||
const apiFormats = new Set(normalizeStringList(group.apiFormats).map(normalizeApiFormatAlias))
|
||||
const endpointIds = new Set(normalizeStringList(group.endpointIds))
|
||||
const matched = activeEndpoints.value.filter((endpoint) => {
|
||||
const apiFormatMatched = apiFormats.size === 0
|
||||
|| apiFormats.has(normalizeApiFormatAlias(endpoint.api_format))
|
||||
const endpointMatched = endpointIds.size === 0 || endpointIds.has(endpoint.id)
|
||||
return apiFormatMatched && endpointMatched
|
||||
})
|
||||
|
||||
return matched.length > 0 ? matched : activeEndpoints.value
|
||||
return activeEndpoints.value.filter(endpoint => modelTestMappingScopeMatchesEndpoint(
|
||||
group.apiFormats,
|
||||
group.endpointIds,
|
||||
endpoint,
|
||||
))
|
||||
}
|
||||
|
||||
// 测试精确映射
|
||||
|
||||
+74
-1
@@ -10,6 +10,7 @@ import {
|
||||
isModelTestableEndpoint,
|
||||
isModelTestableApiFormat,
|
||||
listModelTestMappedModelOptions,
|
||||
modelTestMappingScopeMatchesEndpoint,
|
||||
normalizeModelTestMappedModelSelection,
|
||||
selectPreferredModelTestEndpoint,
|
||||
setModelTestRequestBodyModel,
|
||||
@@ -97,6 +98,20 @@ describe('buildDefaultModelTestRequestBody', () => {
|
||||
expect(body.messages).toBeUndefined()
|
||||
})
|
||||
|
||||
it('uses the synchronous OpenAI Search request contract', () => {
|
||||
const body = JSON.parse(buildDefaultModelTestRequestBody('gpt-5.6-sol', 'openai:search'))
|
||||
|
||||
expect(body).toEqual({
|
||||
id: expect.stringMatching(/^aether-model-test-/),
|
||||
model: 'gpt-5.6-sol',
|
||||
input: 'Hello! This is a test message.',
|
||||
commands: {
|
||||
search_query: [{ q: 'Hello! This is a test message.' }],
|
||||
},
|
||||
max_output_tokens: 256,
|
||||
})
|
||||
})
|
||||
|
||||
it('uses image generation tools for image models on OpenAI Responses endpoints', () => {
|
||||
const body = JSON.parse(buildDefaultModelTestRequestBody(
|
||||
'gpt-image-2',
|
||||
@@ -177,6 +192,52 @@ describe('buildDefaultModelTestRequestBody', () => {
|
||||
expect(options).toEqual([])
|
||||
})
|
||||
|
||||
it('uses one-way format permissions for Search mapping options', () => {
|
||||
const responsesOptions = listModelTestMappedModelOptions({
|
||||
provider_model_name: 'gpt-5.6-luna',
|
||||
provider_model_mappings: [{
|
||||
name: 'gpt-5.6-luna',
|
||||
priority: 1,
|
||||
api_formats: ['openai:responses'],
|
||||
}],
|
||||
}, {
|
||||
id: 'search-endpoint',
|
||||
api_format: 'openai:search',
|
||||
})
|
||||
const searchOptions = listModelTestMappedModelOptions({
|
||||
provider_model_name: 'gpt-5.6-luna',
|
||||
provider_model_mappings: [{
|
||||
name: 'gpt-5.6-luna',
|
||||
priority: 1,
|
||||
api_formats: ['openai:search'],
|
||||
}],
|
||||
}, {
|
||||
id: 'responses-endpoint',
|
||||
api_format: 'openai:responses',
|
||||
})
|
||||
|
||||
expect(responsesOptions).toEqual([{ name: 'gpt-5.6-luna', priority: 1 }])
|
||||
expect(searchOptions).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps explicit mapping scopes strict when no endpoint matches', () => {
|
||||
expect(modelTestMappingScopeMatchesEndpoint(
|
||||
['openai:responses'],
|
||||
['search-endpoint'],
|
||||
{ id: 'search-endpoint', api_format: 'openai:search' },
|
||||
)).toBe(true)
|
||||
expect(modelTestMappingScopeMatchesEndpoint(
|
||||
['openai:responses'],
|
||||
['another-endpoint'],
|
||||
{ id: 'search-endpoint', api_format: 'openai:search' },
|
||||
)).toBe(false)
|
||||
expect(modelTestMappingScopeMatchesEndpoint(
|
||||
['openai:search'],
|
||||
undefined,
|
||||
{ id: 'responses-endpoint', api_format: 'openai:responses' },
|
||||
)).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the current model selected by default until a mapped model is chosen', () => {
|
||||
const options = [
|
||||
{ name: 'MiniMax-M2.7-highspeed', priority: 1 },
|
||||
@@ -259,7 +320,7 @@ describe('isModelTestableApiFormat', () => {
|
||||
'gemini:video',
|
||||
'gemini:files',
|
||||
' OPENAI:VIDEO ',
|
||||
])('excludes task and file endpoint formats from model tests: %s', (apiFormat) => {
|
||||
])('excludes endpoint formats without a model-test request contract: %s', (apiFormat) => {
|
||||
expect(isModelTestableApiFormat(apiFormat)).toBe(false)
|
||||
})
|
||||
|
||||
@@ -267,6 +328,7 @@ describe('isModelTestableApiFormat', () => {
|
||||
'openai:chat',
|
||||
'openai:responses',
|
||||
'openai:responses:compact',
|
||||
'openai:search',
|
||||
'openai:image',
|
||||
'claude:messages',
|
||||
'gemini:generate_content',
|
||||
@@ -379,6 +441,17 @@ describe('isModelTestableEndpoint', () => {
|
||||
}, keys)).toBe(true)
|
||||
})
|
||||
|
||||
it('uses one-way format permissions for Search endpoint keys', () => {
|
||||
expect(isModelTestableEndpoint({
|
||||
api_format: 'openai:search',
|
||||
is_active: true,
|
||||
}, [{ api_formats: ['openai:responses'], is_active: true }])).toBe(true)
|
||||
expect(isModelTestableEndpoint({
|
||||
api_format: 'openai:responses',
|
||||
is_active: true,
|
||||
}, [{ api_formats: ['openai:search'], is_active: true }])).toBe(false)
|
||||
})
|
||||
|
||||
it('lets fixed provider OAuth keys inherit testable endpoint formats', () => {
|
||||
const keys = [{
|
||||
api_formats: ['legacy:mismatch'],
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { normalizeApiFormatAlias } from '@/api/endpoints/types/api-format'
|
||||
import {
|
||||
apiFormatPermissionCovers,
|
||||
normalizeApiFormatAlias,
|
||||
} from '@/api/endpoints/types/api-format'
|
||||
import type { ModelTestCapabilities, OpenAiImageModelTestCapability } from '@/api/endpoints/types'
|
||||
|
||||
export type ModelTestEndpointSource = {
|
||||
@@ -71,7 +74,7 @@ export function modelTestKeySupportsEndpoint(
|
||||
const keyFormats = normalizeModelTestStringList(key.api_formats)
|
||||
if (keyFormats.length === 0) return true
|
||||
|
||||
return keyFormats.some(format => normalizeApiFormatAlias(format) === endpointFormat)
|
||||
return keyFormats.some(format => apiFormatPermissionCovers(format, endpointFormat))
|
||||
}
|
||||
|
||||
export function isModelTestableEndpoint(
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { normalizeApiFormatAlias } from '@/api/endpoints/types/api-format'
|
||||
import {
|
||||
apiFormatPermissionCovers,
|
||||
normalizeApiFormatAlias,
|
||||
} from '@/api/endpoints/types/api-format'
|
||||
import type { ProviderModelMapping } from '@/api/endpoints/types'
|
||||
import type { TestModelRequest } from '@/api/endpoints/providers'
|
||||
import {
|
||||
@@ -29,12 +32,18 @@ export type { ModelTestImagePreview } from './model-test-preview'
|
||||
|
||||
const DEFAULT_MODEL_TEST_MESSAGE = 'Hello! This is a test message.'
|
||||
|
||||
function buildModelTestSearchSessionId(): string {
|
||||
const id = globalThis.crypto?.randomUUID?.()
|
||||
?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
|
||||
return `aether-model-test-${id}`
|
||||
}
|
||||
|
||||
type ModelTestMappingSource = {
|
||||
provider_model_name: string
|
||||
provider_model_mappings?: ProviderModelMapping[] | null
|
||||
}
|
||||
|
||||
type ModelTestMappingEndpoint = {
|
||||
export type ModelTestMappingEndpoint = {
|
||||
id: string
|
||||
api_format: string
|
||||
}
|
||||
@@ -44,17 +53,19 @@ export type ModelTestMappedModelOption = {
|
||||
priority: number
|
||||
}
|
||||
|
||||
function mappingApiFormatMatches(mapping: ProviderModelMapping, endpoint: ModelTestMappingEndpoint): boolean {
|
||||
const apiFormats = normalizeModelTestStringList(mapping.api_formats)
|
||||
if (apiFormats.length === 0) return true
|
||||
export function modelTestMappingScopeMatchesEndpoint(
|
||||
apiFormats: string[] | null | undefined,
|
||||
endpointIds: string[] | null | undefined,
|
||||
endpoint: ModelTestMappingEndpoint,
|
||||
): boolean {
|
||||
const normalizedApiFormats = normalizeModelTestStringList(apiFormats)
|
||||
const endpointFormat = normalizeApiFormatAlias(endpoint.api_format)
|
||||
return apiFormats.some(format => normalizeApiFormatAlias(format) === endpointFormat)
|
||||
}
|
||||
|
||||
function mappingEndpointMatches(mapping: ProviderModelMapping, endpoint: ModelTestMappingEndpoint): boolean {
|
||||
const endpointIds = normalizeModelTestStringList(mapping.endpoint_ids)
|
||||
if (endpointIds.length === 0) return true
|
||||
return endpointIds.includes(endpoint.id)
|
||||
const apiFormatMatches = normalizedApiFormats.length === 0
|
||||
|| normalizedApiFormats.some(format => apiFormatPermissionCovers(format, endpointFormat))
|
||||
const normalizedEndpointIds = normalizeModelTestStringList(endpointIds)
|
||||
const endpointMatches = normalizedEndpointIds.length === 0
|
||||
|| normalizedEndpointIds.includes(endpoint.id)
|
||||
return apiFormatMatches && endpointMatches
|
||||
}
|
||||
|
||||
export function listModelTestMappedModelOptions(
|
||||
@@ -65,8 +76,11 @@ export function listModelTestMappedModelOptions(
|
||||
|
||||
const matchedMappings = model.provider_model_mappings
|
||||
.filter(mapping => mapping.name.trim())
|
||||
.filter(mapping => mappingApiFormatMatches(mapping, endpoint))
|
||||
.filter(mapping => mappingEndpointMatches(mapping, endpoint))
|
||||
.filter(mapping => modelTestMappingScopeMatchesEndpoint(
|
||||
mapping.api_formats,
|
||||
mapping.endpoint_ids,
|
||||
endpoint,
|
||||
))
|
||||
.sort((left, right) => {
|
||||
const leftPriority = Number.isFinite(left.priority) ? left.priority : 1
|
||||
const rightPriority = Number.isFinite(right.priority) ? right.priority : 1
|
||||
@@ -204,6 +218,18 @@ export function buildDefaultModelTestRequestBody(
|
||||
}, null, 2)
|
||||
}
|
||||
|
||||
if (normalizedApiFormat === 'openai:search') {
|
||||
return JSON.stringify({
|
||||
id: buildModelTestSearchSessionId(),
|
||||
model: modelName,
|
||||
input: DEFAULT_MODEL_TEST_MESSAGE,
|
||||
commands: {
|
||||
search_query: [{ q: DEFAULT_MODEL_TEST_MESSAGE }],
|
||||
},
|
||||
max_output_tokens: 256,
|
||||
}, null, 2)
|
||||
}
|
||||
|
||||
if (normalizedApiFormat === 'openai:responses' && modelSupportsImageGeneration(model)) {
|
||||
return JSON.stringify({
|
||||
model: modelName,
|
||||
|
||||
@@ -1,35 +1,15 @@
|
||||
import type { EndpointHealthDetail } from '@/api/endpoints'
|
||||
import { compareApiFormats } from '@/api/endpoints/types/api-format'
|
||||
import { defaultLocale, translateLegacyText, type Locale } from '@/i18n/messages'
|
||||
|
||||
// 端点状态枚举
|
||||
export type EndpointStatus = 'disabled' | 'no_keys' | 'keys_disabled' | 'available'
|
||||
|
||||
const ENDPOINT_SORT_ORDER = [
|
||||
'claude:messages',
|
||||
'openai:chat',
|
||||
'openai:responses',
|
||||
'openai:responses:compact',
|
||||
'openai:embedding',
|
||||
'openai:rerank',
|
||||
'gemini:generate_content',
|
||||
'gemini:interactions',
|
||||
'gemini:embedding',
|
||||
'openai:video',
|
||||
'gemini:video',
|
||||
'gemini:files',
|
||||
'jina:embedding',
|
||||
'jina:rerank',
|
||||
'doubao:embedding',
|
||||
'aliyun:multimodal_embedding',
|
||||
]
|
||||
|
||||
/**
|
||||
* 端点排序
|
||||
*/
|
||||
export function sortEndpoints<T extends { api_format: string }>(endpoints: T[]): T[] {
|
||||
return [...endpoints].sort((a, b) => {
|
||||
return ENDPOINT_SORT_ORDER.indexOf(a.api_format) - ENDPOINT_SORT_ORDER.indexOf(b.api_format)
|
||||
})
|
||||
return [...endpoints].sort((a, b) => compareApiFormats(a.api_format, b.api_format))
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import type { ProviderSummaryQuery } from '@/api/endpoints'
|
||||
import { API_FORMAT_ORDER, formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
import { useI18n } from '@/i18n'
|
||||
|
||||
export interface FilterOption {
|
||||
@@ -25,19 +26,7 @@ export function useProviderFilters(
|
||||
|
||||
const apiFormatFilters = computed<FilterOption[]>(() => [
|
||||
{ value: 'all', label: legacyT('全部格式') },
|
||||
{ value: 'claude:messages', label: 'Claude Messages' },
|
||||
{ value: 'openai:chat', label: 'OpenAI Chat' },
|
||||
{ value: 'openai:responses', label: 'OpenAI Responses' },
|
||||
{ value: 'openai:responses:compact', label: 'OpenAI Responses Compact' },
|
||||
{ value: 'openai:embedding', label: 'OpenAI Embedding' },
|
||||
{ value: 'openai:rerank', label: 'OpenAI Rerank' },
|
||||
{ value: 'gemini:generate_content', label: 'Gemini Generate Content' },
|
||||
{ value: 'gemini:interactions', label: 'Gemini Interactions' },
|
||||
{ value: 'gemini:embedding', label: 'Gemini Embedding' },
|
||||
{ value: 'jina:embedding', label: 'Jina Embedding' },
|
||||
{ value: 'jina:rerank', label: 'Jina Rerank' },
|
||||
{ value: 'doubao:embedding', label: 'Doubao Embedding' },
|
||||
{ value: 'aliyun:multimodal_embedding', label: 'Aliyun Multimodal Embedding' },
|
||||
...API_FORMAT_ORDER.map(value => ({ value, label: formatApiFormat(value) })),
|
||||
])
|
||||
|
||||
const modelFilters = computed<FilterOption[]>(() => {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { parseProviderKeyBatchImport } from '../providerKeyBatchImport'
|
||||
|
||||
describe('provider key batch import parser', () => {
|
||||
it('parses required names and keys separated by four hyphens', () => {
|
||||
const result = parseProviderKeyBatchImport([
|
||||
'primary----sk-primary',
|
||||
'backup----sk-backup',
|
||||
'night----sk-night----suffix',
|
||||
'# ignored comment',
|
||||
].join('\n'))
|
||||
|
||||
expect(result.errors).toEqual([])
|
||||
expect(result.items).toEqual([
|
||||
{ lineNumber: 1, name: 'primary', apiKey: 'sk-primary' },
|
||||
{ lineNumber: 2, name: 'backup', apiKey: 'sk-backup' },
|
||||
{ lineNumber: 3, name: 'night', apiKey: 'sk-night----suffix' },
|
||||
])
|
||||
})
|
||||
|
||||
it('reports invalid format, missing fields and duplicates', () => {
|
||||
const result = parseProviderKeyBatchImport([
|
||||
'one----sk-1',
|
||||
'two----sk-1',
|
||||
'one----sk-2',
|
||||
'----sk-3',
|
||||
'three----',
|
||||
'sk-without-name',
|
||||
].join('\n'))
|
||||
|
||||
expect(result.items).toHaveLength(1)
|
||||
expect(result.errors.map(error => error.message)).toEqual([
|
||||
'Key 与前面行重复',
|
||||
'名称与前面行重复',
|
||||
'名称不能为空',
|
||||
'Key 不能为空',
|
||||
'格式应为 名称----Key',
|
||||
])
|
||||
})
|
||||
|
||||
it('does not impose a client-side item limit', () => {
|
||||
const input = Array.from({ length: 750 }, (_, index) => `key-${index}----sk-${index}`).join('\n')
|
||||
const result = parseProviderKeyBatchImport(input)
|
||||
|
||||
expect(result.items).toHaveLength(750)
|
||||
expect(result.errors).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,52 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS,
|
||||
isProviderQuotaAutoRefreshCoolingDown,
|
||||
markProviderQuotaAutoRefreshAttempt,
|
||||
resetProviderQuotaAutoRefreshCooldownForTests,
|
||||
} from '../quotaAutoRefreshCooldown'
|
||||
|
||||
describe('quota auto refresh cooldown', () => {
|
||||
afterEach(() => {
|
||||
resetProviderQuotaAutoRefreshCooldownForTests()
|
||||
})
|
||||
|
||||
it('starts cooldown after recording an auto refresh attempt', () => {
|
||||
markProviderQuotaAutoRefreshAttempt('provider-1', 1_000)
|
||||
|
||||
expect(isProviderQuotaAutoRefreshCoolingDown('provider-1', 1_000)).toBe(true)
|
||||
expect(
|
||||
isProviderQuotaAutoRefreshCoolingDown(
|
||||
'provider-1',
|
||||
1_000 + AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS - 1,
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('expires cooldown after the configured window', () => {
|
||||
markProviderQuotaAutoRefreshAttempt('provider-1', 1_000)
|
||||
|
||||
expect(
|
||||
isProviderQuotaAutoRefreshCoolingDown(
|
||||
'provider-1',
|
||||
1_000 + AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS,
|
||||
),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('tracks cooldown independently per provider', () => {
|
||||
markProviderQuotaAutoRefreshAttempt('provider-1', 1_000)
|
||||
markProviderQuotaAutoRefreshAttempt('provider-2', 1_200)
|
||||
|
||||
expect(isProviderQuotaAutoRefreshCoolingDown('provider-1', 1_301)).toBe(false)
|
||||
expect(isProviderQuotaAutoRefreshCoolingDown('provider-2', 1_301)).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores empty provider ids', () => {
|
||||
markProviderQuotaAutoRefreshAttempt('', 1_000)
|
||||
|
||||
expect(isProviderQuotaAutoRefreshCoolingDown('', 1_001)).toBe(false)
|
||||
expect(isProviderQuotaAutoRefreshCoolingDown(null, 1_001)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
export interface ProviderKeyBatchImportItem {
|
||||
lineNumber: number
|
||||
name: string
|
||||
apiKey: string
|
||||
}
|
||||
|
||||
export interface ProviderKeyBatchImportError {
|
||||
lineNumber: number | null
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface ProviderKeyBatchImportParseResult {
|
||||
items: ProviderKeyBatchImportItem[]
|
||||
errors: ProviderKeyBatchImportError[]
|
||||
}
|
||||
|
||||
export const PROVIDER_KEY_BATCH_SEPARATOR = '----'
|
||||
|
||||
function splitNamedKey(line: string): { name: string; apiKey: string } | null {
|
||||
const separatorIndex = line.indexOf(PROVIDER_KEY_BATCH_SEPARATOR)
|
||||
if (separatorIndex < 0) return null
|
||||
return {
|
||||
name: line.slice(0, separatorIndex),
|
||||
apiKey: line.slice(separatorIndex + PROVIDER_KEY_BATCH_SEPARATOR.length),
|
||||
}
|
||||
}
|
||||
|
||||
export function parseProviderKeyBatchImport(input: string): ProviderKeyBatchImportParseResult {
|
||||
const items: ProviderKeyBatchImportItem[] = []
|
||||
const errors: ProviderKeyBatchImportError[] = []
|
||||
const seenKeys = new Set<string>()
|
||||
const seenNames = new Set<string>()
|
||||
|
||||
for (const [index, rawLine] of input.split(/\r?\n/).entries()) {
|
||||
const lineNumber = index + 1
|
||||
const line = rawLine.trim()
|
||||
if (!line || line.startsWith('#')) continue
|
||||
|
||||
const named = splitNamedKey(line)
|
||||
if (!named) {
|
||||
errors.push({ lineNumber, message: `格式应为 名称${PROVIDER_KEY_BATCH_SEPARATOR}Key` })
|
||||
continue
|
||||
}
|
||||
const name = named.name.trim()
|
||||
const apiKey = named.apiKey.trim()
|
||||
if (!name) {
|
||||
errors.push({ lineNumber, message: '名称不能为空' })
|
||||
continue
|
||||
}
|
||||
if (!apiKey) {
|
||||
errors.push({ lineNumber, message: 'Key 不能为空' })
|
||||
continue
|
||||
}
|
||||
if (name.length > 100) {
|
||||
errors.push({ lineNumber, message: '名称不能超过 100 个字符' })
|
||||
continue
|
||||
}
|
||||
if (seenKeys.has(apiKey)) {
|
||||
errors.push({ lineNumber, message: 'Key 与前面行重复' })
|
||||
continue
|
||||
}
|
||||
if (seenNames.has(name)) {
|
||||
errors.push({ lineNumber, message: '名称与前面行重复' })
|
||||
continue
|
||||
}
|
||||
|
||||
seenKeys.add(apiKey)
|
||||
seenNames.add(name)
|
||||
items.push({ lineNumber, name, apiKey })
|
||||
}
|
||||
|
||||
return { items, errors }
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
const AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS = 5 * 60
|
||||
|
||||
const lastAutoQuotaRefreshAttemptAtByProvider = new Map<string, number>()
|
||||
|
||||
function normalizeUnixSeconds(value: number): number {
|
||||
return Math.max(Math.floor(value), 0)
|
||||
}
|
||||
|
||||
export function isProviderQuotaAutoRefreshCoolingDown(
|
||||
providerId: string | null | undefined,
|
||||
nowSeconds = Math.floor(Date.now() / 1000),
|
||||
): boolean {
|
||||
const id = String(providerId || '').trim()
|
||||
if (!id) return false
|
||||
|
||||
const lastAttemptAt = lastAutoQuotaRefreshAttemptAtByProvider.get(id)
|
||||
if (lastAttemptAt == null) return false
|
||||
|
||||
return normalizeUnixSeconds(nowSeconds) - lastAttemptAt < AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS
|
||||
}
|
||||
|
||||
export function markProviderQuotaAutoRefreshAttempt(
|
||||
providerId: string | null | undefined,
|
||||
nowSeconds = Math.floor(Date.now() / 1000),
|
||||
): void {
|
||||
const id = String(providerId || '').trim()
|
||||
if (!id) return
|
||||
|
||||
lastAutoQuotaRefreshAttemptAtByProvider.set(id, normalizeUnixSeconds(nowSeconds))
|
||||
}
|
||||
|
||||
export function resetProviderQuotaAutoRefreshCooldownForTests(): void {
|
||||
lastAutoQuotaRefreshAttemptAtByProvider.clear()
|
||||
}
|
||||
|
||||
export { AUTO_QUOTA_REFRESH_COOLDOWN_SECONDS }
|
||||
Reference in New Issue
Block a user