-
+
{{ t('admin.accounts.selectedModels', { count: allowedModels.length }) }}
{{
@@ -1865,7 +1889,12 @@
-
+
{{ t('admin.accounts.selectedModels', { count: allowedModels.length }) }}
{{ t('admin.accounts.supportsAllModels') }}
@@ -2201,7 +2230,12 @@
-
+
{{ t('admin.accounts.selectedModels', { count: allowedModels.length }) }}
{{
@@ -2958,6 +2992,7 @@
-
+
@@ -3740,15 +3775,18 @@ import Toggle from '@/components/common/Toggle.vue'
import GrokBaseUrlPresets from '@/components/account/GrokBaseUrlPresets.vue'
import CnBaseUrlPresets from '@/components/account/CnBaseUrlPresets.vue'
import HeaderOverrideEditor from '@/components/account/HeaderOverrideEditor.vue'
+import { allSelectedGroupsEnableLongContextPricing } from '@/components/account/longContextBilling'
import {
applyAntigravityProjectID,
applyHeaderOverride,
applyInterceptWarmup,
+ defaultCNAdaptiveBaseUrls,
defaultCNBaseUrl,
isHeaderOverrideCapable,
validateHeaderOverrideRows,
type CnAccountMode,
type CnApiProtocol,
+ type CnNativeApiProtocol,
type HeaderOverrideRow
} from '@/components/account/credentialsBuilder'
import { formatDateTimeLocalInput, parseDateTimeLocalInput } from '@/utils/format'
@@ -3857,6 +3895,10 @@ const emit = defineEmits<{
const appStore = useAppStore()
+const hideAccountLongContextBilling = computed(() => {
+ return allSelectedGroupsEnableLongContextPricing(form.group_ids, props.groups)
+})
+
// OAuth composables
const oauth = useAccountOAuth() // For Anthropic OAuth
const openaiOAuth = useOpenAIOAuth() // For OpenAI OAuth
@@ -3926,7 +3968,12 @@ const upstreamBillingAutoProbeEnabled = ref(true)
const accountMode = ref
('payg')
// API 协议决定转发端点与格式:cc=现有转换链,anthropic=原生直通(Claude Code),
// responses=deepseek 原生 Responses 端点(Codex)。与账号类型正交。
-const apiProtocol = ref('chat_completions')
+const apiProtocol = ref('adaptive')
+const adaptiveBaseUrls = ref>({
+ chat_completions: '',
+ anthropic: '',
+ responses: ''
+})
const isCNPlatform = computed(
() => form.platform === 'kimi' || form.platform === 'zhipu' || form.platform === 'deepseek'
)
@@ -3941,6 +3988,7 @@ const cnPresetPlatform = computed<'kimi' | 'zhipu' | 'deepseek'>(() => {
// 当前平台可选的协议档(responses 仅 deepseek)。
const cnProtocolOptions = computed>(() => {
const opts: Array<{ value: CnApiProtocol; labelKey: string }> = [
+ { value: 'adaptive', labelKey: 'adaptive' },
{ value: 'chat_completions', labelKey: 'chatCompletions' },
{ value: 'anthropic', labelKey: 'anthropic' }
]
@@ -3949,6 +3997,18 @@ const cnProtocolOptions = computed>(() => {
+ const opts: Array<{ value: CnNativeApiProtocol; labelKey: string }> = [
+ { value: 'chat_completions', labelKey: 'chatCompletions' },
+ { value: 'anthropic', labelKey: 'anthropic' }
+ ]
+ if (form.platform === 'deepseek') opts.push({ value: 'responses', labelKey: 'responses' })
+ return opts
+})
+
+function resetAdaptiveBaseUrls(platform: 'kimi' | 'zhipu' | 'deepseek', mode: CnAccountMode) {
+ adaptiveBaseUrls.value = defaultCNAdaptiveBaseUrls(platform, mode)
+}
// 当前选中平台的品牌色(选中卡片描边 / 图标底色),与 platformColors 取色一致。
const cnAccentActiveClass = computed(() => {
switch (form.platform) {
@@ -3975,24 +4035,44 @@ const cnAccentIconClass = computed(() => {
}
})
// 切换国产供应商平台:强制 apikey 类型,deepseek 无 coding 套餐故锁定 payg,
-// 协议回落 chat_completions,并把 base url 重置为该平台默认端点。
+// 协议回落 adaptive,并把 base url 重置为该平台默认端点。
function selectCNPlatform(platform: 'kimi' | 'zhipu' | 'deepseek') {
form.platform = platform
form.type = 'apikey'
accountCategory.value = 'apikey'
- apiProtocol.value = 'chat_completions'
+ apiProtocol.value = 'adaptive'
if (platform === 'deepseek') {
accountMode.value = 'payg'
}
apiKeyBaseUrl.value = defaultCNBaseUrl(platform, accountMode.value, apiProtocol.value)
+ resetAdaptiveBaseUrls(platform, accountMode.value)
}
// 账号类型 / 协议变更时同步默认 base url。
-watch(accountMode, (mode) => {
+watch(accountMode, (mode, previousMode) => {
if (!isCNPlatform.value) return
+ if (apiProtocol.value === 'adaptive') {
+ const previousDefaults = defaultCNAdaptiveBaseUrls(cnPresetPlatform.value, previousMode)
+ const nextDefaults = defaultCNAdaptiveBaseUrls(cnPresetPlatform.value, mode)
+ for (const item of cnAdaptiveProtocolOptions.value) {
+ if (!adaptiveBaseUrls.value[item.value] || adaptiveBaseUrls.value[item.value] === previousDefaults[item.value]) {
+ adaptiveBaseUrls.value[item.value] = nextDefaults[item.value]
+ }
+ }
+ apiKeyBaseUrl.value = adaptiveBaseUrls.value.chat_completions
+ return
+ }
apiKeyBaseUrl.value = defaultCNBaseUrl(form.platform, mode, apiProtocol.value)
})
watch(apiProtocol, (protocol) => {
if (!isCNPlatform.value) return
+ if (protocol === 'adaptive') {
+ const defaults = defaultCNAdaptiveBaseUrls(cnPresetPlatform.value, accountMode.value)
+ for (const item of cnAdaptiveProtocolOptions.value) {
+ if (!adaptiveBaseUrls.value[item.value]) adaptiveBaseUrls.value[item.value] = defaults[item.value]
+ }
+ apiKeyBaseUrl.value = adaptiveBaseUrls.value.chat_completions
+ return
+ }
apiKeyBaseUrl.value = defaultCNBaseUrl(form.platform, accountMode.value, protocol)
})
// 点击预设端点:同时回填 base url、账号类型与协议。
@@ -4004,11 +4084,20 @@ function onCnPresetSelect(preset: { mode: CnAccountMode; protocol: CnApiProtocol
const syncPreviewCredentials = computed(() => {
if (!apiKeyValue.value) return undefined
+ const baseUrl = isCNPlatform.value && apiProtocol.value === 'adaptive'
+ ? adaptiveBaseUrls.value.chat_completions.trim() || apiKeyBaseUrl.value.trim()
+ : apiKeyBaseUrl.value.trim()
+ const modelMapping = buildModelMappingObject(
+ modelRestrictionMode.value,
+ allowedModels.value,
+ modelMappings.value
+ )
return {
platform: form.platform,
type: form.type,
- base_url: apiKeyBaseUrl.value || undefined,
- api_key: apiKeyValue.value
+ base_url: baseUrl || undefined,
+ api_key: apiKeyValue.value,
+ ...(modelMapping ? { model_mapping: modelMapping } : {})
}
})
@@ -4025,6 +4114,7 @@ const modelMappings = ref([])
const openAICompactModelMappings = ref([])
const modelRestrictionMode = ref<'whitelist' | 'mapping'>('whitelist')
const allowedModels = ref([])
+const upstreamModelsPreviewed = ref(false)
const DEFAULT_POOL_MODE_RETRY_COUNT = 3
const MAX_POOL_MODE_RETRY_COUNT = 10
const DEFAULT_POOL_MODE_RETRY_STATUS_CODES = [401, 403, 429]
@@ -4511,6 +4601,7 @@ watch(
}
// Clear model-related settings
allowedModels.value = []
+ upstreamModelsPreviewed.value = false
modelMappings.value = []
// Antigravity: 默认使用映射模式并填充默认映射
if (newPlatform === 'antigravity') {
@@ -4902,6 +4993,23 @@ const submitCreateAccount = async (payload: CreateAccountRequest) => {
submitting.value = true
try {
const account = await adminAPI.accounts.create(withAntigravityConfirmFlag(payload))
+ const modelMapping = payload.credentials.model_mapping
+ const hasConcreteMappedTarget = payload.type === 'apikey' &&
+ typeof modelMapping === 'object' &&
+ modelMapping !== null &&
+ Object.values(modelMapping).some((target) =>
+ typeof target === 'string' && target.trim() !== '' && !target.includes('*')
+ )
+ if (upstreamModelsPreviewed.value || hasConcreteMappedTarget) {
+ try {
+ const result = await adminAPI.accounts.syncUpstreamModels(account.id)
+ if (result.warnings?.some(warning => warning.code === 'upstream_model_metadata_incomplete')) {
+ appStore.showWarning(t('admin.accounts.syncUpstreamModelsMetadataIncomplete'))
+ }
+ } catch {
+ appStore.showWarning(t('admin.accounts.syncUpstreamModelsFailed'))
+ }
+ }
if (
payload.type === 'apikey' &&
payload.upstream_billing_probe_enabled === true
@@ -4950,7 +5058,8 @@ const resetForm = () => {
accountCategory.value = 'oauth-based'
addMethod.value = 'oauth'
accountMode.value = 'payg'
- apiProtocol.value = 'chat_completions'
+ apiProtocol.value = 'adaptive'
+ adaptiveBaseUrls.value = { chat_completions: '', anthropic: '', responses: '' }
apiKeyBaseUrl.value = 'https://api.anthropic.com'
apiKeyValue.value = ''
upstreamBillingAutoProbeEnabled.value = true
@@ -5041,6 +5150,7 @@ const resetForm = () => {
grokOAuth.resetState()
oauthFlowRef.value?.reset()
antigravityMixedChannelConfirmed.value = false
+ upstreamModelsPreviewed.value = false
clearMixedChannelDialog()
}
@@ -5419,10 +5529,19 @@ const handleSubmit = async () => {
if (form.platform === 'kimi' || form.platform === 'zhipu' || form.platform === 'deepseek') {
credentials.account_mode = accountMode.value
credentials.api_protocol = apiProtocol.value
+ if (apiProtocol.value === 'adaptive') {
+ const defaults = defaultCNAdaptiveBaseUrls(form.platform, accountMode.value)
+ const protocolBaseUrls: Record = {}
+ for (const item of cnAdaptiveProtocolOptions.value) {
+ protocolBaseUrls[item.value] = (adaptiveBaseUrls.value[item.value] || defaults[item.value]).trim()
+ }
+ credentials.api_base_urls = protocolBaseUrls
+ credentials.base_url = protocolBaseUrls.chat_completions
+ }
const resolvedCNBase = (
apiKeyBaseUrl.value.trim() || defaultCNBaseUrl(form.platform, accountMode.value, apiProtocol.value)
).trim()
- if (resolvedCNBase) {
+ if (apiProtocol.value !== 'adaptive' && resolvedCNBase) {
credentials.base_url = resolvedCNBase
}
}
diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue
index 9369b229aa..b1a6d10e97 100644
--- a/frontend/src/components/account/EditAccountModal.vue
+++ b/frontend/src/components/account/EditAccountModal.vue
@@ -28,7 +28,7 @@
-
+
{{ t('admin.accounts.baseUrl') }}
+
+
{{ t('admin.accounts.cnProviders.apiProtocol.endpoints') }}
+
+
+
+ {{ t(`admin.accounts.cnProviders.apiProtocol.${item.labelKey}`) }}
+
+
+
+
+
+ {{ t('admin.accounts.cnProviders.apiProtocol.responsesFallbackDesc') }}
+
+
{{ t('admin.accounts.cnProviders.accountMode.title') }}
@@ -1966,7 +1980,7 @@
+
+
+
+
{{ t('admin.accounts.autoResetCredit.title') }}
+
+ {{ t('admin.accounts.autoResetCredit.hint') }}
+
+
+
+
+
+
+
+
{{ t('admin.accounts.autoResetCredit.thresholdHint') }}
+
+
props.account?.parent_account_id != null)
+const hideAccountLongContextBilling = computed(() => {
+ return allSelectedGroupsEnableLongContextPricing(form.group_ids, props.groups)
+})
+
const handleOllamaCloudUsageUpdated = (state: OllamaCloudUsageState) => {
if (props.account) emit('updated', { ...props.account, ollama_cloud_usage: state })
}
@@ -2904,8 +2985,13 @@ const cnPresetPlatform = computed<'kimi' | 'zhipu' | 'deepseek'>(() => {
}
return 'kimi'
})
-const editApiProtocol = ref
('chat_completions')
+const editApiProtocol = ref('adaptive')
const editAccountMode = ref('payg')
+const editAdaptiveBaseUrls = ref>({
+ chat_completions: '',
+ anthropic: '',
+ responses: ''
+})
// 回填窗口标志:syncFormFromAccount 会同步改写 editAccountMode / editApiProtocol,
// 而 watcher(pre-flush)在同步代码执行完之后才触发——若不抑制,会把刚恢复的
// 存储版 base_url(可能是用户自定义/中转地址)覆盖为官方预设并在下次保存时持久化。
@@ -2925,6 +3011,7 @@ const cnAccountModeOptions = computed>(() => {
const opts: Array<{ value: CnApiProtocol; labelKey: string }> = [
+ { value: 'adaptive', labelKey: 'adaptive' },
{ value: 'chat_completions', labelKey: 'chatCompletions' },
{ value: 'anthropic', labelKey: 'anthropic' }
]
@@ -2933,11 +3020,35 @@ const cnProtocolOptions = computed {
+const editAdaptiveProtocolOptions = computed>(() => {
+ const opts: Array<{ value: CnNativeApiProtocol; labelKey: string }> = [
+ { value: 'chat_completions', labelKey: 'chatCompletions' },
+ { value: 'anthropic', labelKey: 'anthropic' }
+ ]
+ if (props.account?.platform === 'deepseek') opts.push({ value: 'responses', labelKey: 'responses' })
+ return opts
+})
+watch(editApiProtocol, (protocol, previousProtocol) => {
if (!isCNApiKeyAccount.value || syncingForm.value) return
+ if (protocol === 'adaptive') {
+ const defaults = defaultCNAdaptiveBaseUrls(cnPresetPlatform.value, editAccountMode.value)
+ for (const item of editAdaptiveProtocolOptions.value) {
+ if (!editAdaptiveBaseUrls.value[item.value]) editAdaptiveBaseUrls.value[item.value] = defaults[item.value]
+ }
+ if (previousProtocol !== 'adaptive' && editBaseUrl.value.trim()) {
+ editAdaptiveBaseUrls.value[previousProtocol] = editBaseUrl.value.trim()
+ }
+ editBaseUrl.value = editAdaptiveBaseUrls.value.chat_completions
+ return
+ }
+ if (previousProtocol === 'adaptive') {
+ editBaseUrl.value = editAdaptiveBaseUrls.value[protocol] ||
+ defaultCNBaseUrl(props.account!.platform, editAccountMode.value, protocol)
+ return
+ }
editBaseUrl.value = defaultCNBaseUrl(props.account!.platform, editAccountMode.value, protocol)
})
-watch(editAccountMode, (mode) => {
+watch(editAccountMode, (mode, previousMode) => {
if (!isCNApiKeyAccount.value || syncingForm.value) return
// deepseek 无 coding 套餐:防御性回退(UI 已隐藏该选项)。
const effectiveMode = props.account!.platform === 'deepseek' && mode === 'coding' ? 'payg' : mode
@@ -2945,6 +3056,17 @@ watch(editAccountMode, (mode) => {
editAccountMode.value = effectiveMode
return
}
+ if (editApiProtocol.value === 'adaptive') {
+ const previousDefaults = defaultCNAdaptiveBaseUrls(cnPresetPlatform.value, previousMode)
+ const nextDefaults = defaultCNAdaptiveBaseUrls(cnPresetPlatform.value, mode)
+ for (const item of editAdaptiveProtocolOptions.value) {
+ if (!editAdaptiveBaseUrls.value[item.value] || editAdaptiveBaseUrls.value[item.value] === previousDefaults[item.value]) {
+ editAdaptiveBaseUrls.value[item.value] = nextDefaults[item.value]
+ }
+ }
+ editBaseUrl.value = editAdaptiveBaseUrls.value.chat_completions
+ return
+ }
editBaseUrl.value = defaultCNBaseUrl(props.account!.platform, mode, editApiProtocol.value)
})
const cnProtocolDescKey = computed(
@@ -3036,6 +3158,9 @@ const autoPause5hThreshold = ref(null)
const autoPause7dThreshold = ref(null)
const autoPause5hDisabled = ref(false)
const autoPause7dDisabled = ref(false)
+const autoResetCreditEnabled = ref(false)
+const autoResetCredit5hThreshold = ref(100)
+const autoResetCredit7dThreshold = ref(100)
const upstreamBillingAutoProbeEnabled = ref(false)
const upstreamBillingRateSyncEnabled = ref(false)
const mixedScheduling = ref(false) // For antigravity accounts: enable mixed scheduling
@@ -3564,6 +3689,11 @@ const syncFormFromAccount = (newAccount: Account | null) => {
autoPause7dThreshold.value = typeof extra?.auto_pause_7d_threshold === 'number' ? extra.auto_pause_7d_threshold * 100 : null
autoPause5hDisabled.value = extra?.auto_pause_5h_disabled === true
autoPause7dDisabled.value = extra?.auto_pause_7d_disabled === true
+ autoResetCreditEnabled.value = extra?.auto_reset_credit_enabled === true
+ autoResetCredit5hThreshold.value =
+ typeof extra?.auto_reset_credit_5h_threshold === 'number' ? extra.auto_reset_credit_5h_threshold * 100 : 100
+ autoResetCredit7dThreshold.value =
+ typeof extra?.auto_reset_credit_7d_threshold === 'number' ? extra.auto_reset_credit_7d_threshold * 100 : 100
upstreamBillingAutoProbeEnabled.value = extra?.upstream_billing_probe_enabled === true
upstreamBillingRateSyncEnabled.value =
upstreamBillingAutoProbeEnabled.value && extra?.upstream_billing_rate_sync_enabled === true
@@ -3769,10 +3899,46 @@ const syncFormFromAccount = (newAccount: Account | null) => {
editAccountMode.value = credentials.account_mode === 'coding' ? 'coding' : 'payg'
const storedProtocol = credentials.api_protocol
editApiProtocol.value =
- storedProtocol === 'anthropic' || storedProtocol === 'responses' ? storedProtocol : 'chat_completions'
+ storedProtocol === 'adaptive' ||
+ storedProtocol === 'chat_completions' ||
+ storedProtocol === 'anthropic' ||
+ storedProtocol === 'responses'
+ ? storedProtocol
+ : 'chat_completions'
if (newAccount.platform !== 'deepseek' && editApiProtocol.value === 'responses') {
editApiProtocol.value = 'chat_completions'
}
+ const adaptiveDefaults = defaultCNAdaptiveBaseUrls(newAccount.platform, editAccountMode.value)
+ const storedBaseUrls = (credentials.api_base_urls as Record | undefined) || {}
+ const legacyBaseUrl = typeof credentials.base_url === 'string' ? credentials.base_url.trim() : ''
+ const storedChatBaseUrl = typeof storedBaseUrls.chat_completions === 'string'
+ ? storedBaseUrls.chat_completions.trim()
+ : ''
+ const storedAnthropicBaseUrl = typeof storedBaseUrls.anthropic === 'string'
+ ? storedBaseUrls.anthropic.trim()
+ : ''
+ const storedResponsesBaseUrl = typeof storedBaseUrls.responses === 'string'
+ ? storedBaseUrls.responses.trim()
+ : ''
+ const nextAdaptiveBaseUrls: Record = {
+ chat_completions: storedChatBaseUrl || adaptiveDefaults.chat_completions,
+ anthropic: storedAnthropicBaseUrl || adaptiveDefaults.anthropic,
+ responses: storedResponsesBaseUrl || adaptiveDefaults.responses
+ }
+ const legacyProtocol: CnNativeApiProtocol = editApiProtocol.value === 'anthropic'
+ ? 'anthropic'
+ : editApiProtocol.value === 'responses'
+ ? 'responses'
+ : 'chat_completions'
+ const storedLegacyBaseUrl = legacyProtocol === 'anthropic'
+ ? storedAnthropicBaseUrl
+ : legacyProtocol === 'responses'
+ ? storedResponsesBaseUrl
+ : storedChatBaseUrl
+ if (legacyBaseUrl && !storedLegacyBaseUrl) {
+ nextAdaptiveBaseUrls[legacyProtocol] = legacyBaseUrl
+ }
+ editAdaptiveBaseUrls.value = nextAdaptiveBaseUrls
}
const platformDefaultUrl =
newAccount.platform === 'openai'
@@ -3786,7 +3952,9 @@ const syncFormFromAccount = (newAccount: Account | null) => {
newAccount.platform === 'deepseek'
? defaultCNBaseUrl(newAccount.platform, editAccountMode.value, editApiProtocol.value)
: 'https://api.anthropic.com'
- editBaseUrl.value = (credentials.base_url as string) || platformDefaultUrl
+ editBaseUrl.value = isCNApiKeyAccount.value && editApiProtocol.value === 'adaptive'
+ ? editAdaptiveBaseUrls.value.chat_completions
+ : (credentials.base_url as string) || platformDefaultUrl
// Load model mappings and detect mode
loadModelRestrictionFromMapping(credentials.model_mapping as Record | undefined)
@@ -3964,6 +4132,10 @@ const syncAntigravityUpstreamModels = async () => {
}
}
+ if (result.warnings?.some((warning) => warning.code === 'upstream_model_metadata_incomplete')) {
+ appStore.showWarning(t('admin.accounts.syncUpstreamModelsMetadataIncomplete'))
+ return
+ }
if (addedCount > 0) {
appStore.showSuccess(t('admin.accounts.syncUpstreamModelsSuccess', { count: addedCount, total: upstreamModels.length }))
} else {
@@ -4418,6 +4590,13 @@ const handleSubmit = async () => {
appStore.showError(t('admin.accounts.pleaseSelectStatus'))
return
}
+ if (autoResetCreditEnabled.value) {
+ const thresholds = [autoResetCredit5hThreshold.value, autoResetCredit7dThreshold.value]
+ if (thresholds.some((value) => !Number.isFinite(value) || value < 0.1 || value > 100)) {
+ appStore.showError(t('admin.accounts.autoResetCredit.thresholdInvalid'))
+ return
+ }
+ }
const updatePayload: Record = { ...form }
try {
@@ -4458,6 +4637,17 @@ const handleSubmit = async () => {
if (isCNApiKeyAccount.value) {
newCredentials.account_mode = editAccountMode.value
newCredentials.api_protocol = editApiProtocol.value
+ if (editApiProtocol.value === 'adaptive') {
+ const defaults = defaultCNAdaptiveBaseUrls(cnPresetPlatform.value, editAccountMode.value)
+ const protocolBaseUrls: Record = {}
+ for (const item of editAdaptiveProtocolOptions.value) {
+ protocolBaseUrls[item.value] = (editAdaptiveBaseUrls.value[item.value] || defaults[item.value]).trim()
+ }
+ newCredentials.api_base_urls = protocolBaseUrls
+ newCredentials.base_url = protocolBaseUrls.chat_completions
+ } else {
+ delete newCredentials.api_base_urls
+ }
}
// Handle API key
@@ -4971,6 +5161,13 @@ const handleSubmit = async () => {
} else {
delete newExtra.auto_pause_7d_disabled
}
+ if (props.account.type === 'oauth' && !isSparkShadow.value) {
+ newExtra.auto_reset_credit_enabled = autoResetCreditEnabled.value
+ newExtra.auto_reset_credit_5h_threshold = autoResetCredit5hThreshold.value / 100
+ newExtra.auto_reset_credit_7d_threshold = autoResetCredit7dThreshold.value / 100
+ }
+ // 运行态只允许后端服务更新,账号编辑不得回写旧状态。
+ delete newExtra.codex_auto_reset_credit_state
delete newExtra.codex_image_generation_bridge_enabled
switch (codexImageToolMode.value) {
diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue
index b6086c6d6b..a3b1309fbf 100644
--- a/frontend/src/components/account/ModelWhitelistSelector.vue
+++ b/frontend/src/components/account/ModelWhitelistSelector.vue
@@ -172,6 +172,7 @@ const props = defineProps<{
const emit = defineEmits<{
'update:modelValue': [value: string[]]
+ 'upstream-synced': []
}>()
const appStore = useAppStore()
@@ -312,6 +313,10 @@ const syncUpstreamModels = async () => {
return
}
+ if (!props.accountId) {
+ emit('upstream-synced')
+ }
+
const newModels = [...props.modelValue]
let addedCount = 0
for (const model of upstreamModels) {
@@ -322,6 +327,10 @@ const syncUpstreamModels = async () => {
}
emit('update:modelValue', newModels)
+ if (result.warnings?.some(warning => warning.code === 'upstream_model_metadata_incomplete')) {
+ appStore.showWarning(t('admin.accounts.syncUpstreamModelsMetadataIncomplete'))
+ return
+ }
if (addedCount > 0) {
appStore.showSuccess(t('admin.accounts.syncUpstreamModelsSuccess', { count: addedCount, total: upstreamModels.length }))
} else {
diff --git a/frontend/src/components/account/OpenAIQuotaResetCell.vue b/frontend/src/components/account/OpenAIQuotaResetCell.vue
index cb81bcfd9d..6a3225b8bf 100644
--- a/frontend/src/components/account/OpenAIQuotaResetCell.vue
+++ b/frontend/src/components/account/OpenAIQuotaResetCell.vue
@@ -63,6 +63,32 @@
+
+
+ {{ autoResetStateLabel }}
+
+ {{ autoResetState.trigger_window }}
+
+
+
+ {{ formatResetCreditExpiry(autoResetState.checked_at, 'short') }}
+
+
+ {{ autoResetState.error_code }}
+
+
+
(null)
const showResetConfirm = ref(false)
const showResetCreditDetails = ref(false)
+type AutoResetCreditState = NonNullable['codex_auto_reset_credit_state']>
+const validAutoResetStatuses = new Set(['checking', 'available', 'resetting', 'success', 'no_credit', 'failed'])
+const autoResetState = computed(() => {
+ if (props.account.extra?.auto_reset_credit_enabled !== true) return null
+ const state = props.account.extra?.codex_auto_reset_credit_state
+ if (!state || typeof state !== 'object' || !validAutoResetStatuses.has(String(state.status))) return null
+ return state
+})
+const autoResetStateLabel = computed(() => {
+ if (!autoResetState.value?.status) return ''
+ const keyByStatus: Record = {
+ checking: 'checking',
+ available: 'available',
+ resetting: 'resetting',
+ success: 'success',
+ no_credit: 'noCredit',
+ failed: 'failed'
+ }
+ return t(`admin.accounts.openaiQuotaReset.autoStatus.${keyByStatus[autoResetState.value.status]}`)
+})
+const autoResetStateClass = computed(() => {
+ switch (autoResetState.value?.status) {
+ case 'available':
+ return 'bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
+ case 'success':
+ return 'bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300'
+ case 'no_credit':
+ case 'failed':
+ return 'bg-red-50 text-red-700 dark:bg-red-900/30 dark:text-red-300'
+ case 'resetting':
+ return 'bg-orange-50 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300'
+ default:
+ return 'bg-gray-100 text-gray-600 dark:bg-dark-800 dark:text-gray-300'
+ }
+})
+
// Rehydrate the card from the persisted snapshot. Credits that already expired
// are dropped and the count is clamped to what remains: the snapshot has no
// freshness signal, so an unfiltered read would offer to consume credits that no
diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts
index 1ad6866dd7..b87269f7a6 100644
--- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts
+++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts
@@ -519,7 +519,7 @@ describe('AccountUsageCell', () => {
expect(wrapper.text()).toContain('5h|0|200')
})
- it('OpenAI 重置响应更新账号行时不会额外拉取 usage', async () => {
+ it('OpenAI 重置响应更新账号行后重新拉取 usage', async () => {
getUsage.mockResolvedValue({
five_hour: {
utilization: 0,
@@ -560,7 +560,7 @@ describe('AccountUsageCell', () => {
await wrapper.setProps({ account: updatedAccount as Account })
await flushPromises()
- expect(getUsage).toHaveBeenCalledTimes(1)
+ expect(getUsage).toHaveBeenCalledTimes(2)
})
it('OpenAI OAuth 已限额时显示 /usage API 返回的限额数据', async () => {
diff --git a/frontend/src/components/account/__tests__/CNProviderBalanceCell.spec.ts b/frontend/src/components/account/__tests__/CNProviderBalanceCell.spec.ts
new file mode 100644
index 0000000000..da60a91f6c
--- /dev/null
+++ b/frontend/src/components/account/__tests__/CNProviderBalanceCell.spec.ts
@@ -0,0 +1,76 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import CNProviderBalanceCell from '../CNProviderBalanceCell.vue'
+import type { Account } from '@/types'
+
+const { queryBalance } = vi.hoisted(() => ({
+ queryBalance: vi.fn()
+}))
+
+vi.mock('@/api/admin', () => ({
+ adminAPI: {
+ cnProviders: { queryBalance }
+ }
+}))
+
+vi.mock('vue-i18n', () => ({
+ useI18n: () => ({
+ t: (key: string) => key
+ })
+}))
+
+const account = {
+ id: 7,
+ platform: 'kimi',
+ type: 'apikey',
+ credentials: { account_mode: 'payg' },
+ extra: {
+ kimi_balance: 12.5,
+ kimi_balance_currency: 'CNY'
+ }
+} as Account
+
+describe('CNProviderBalanceCell', () => {
+ beforeEach(() => {
+ queryBalance.mockReset()
+ })
+
+ it('renders the persisted balance as static text with an explicit query action', async () => {
+ const wrapper = mount(CNProviderBalanceCell, { props: { account } })
+ await flushPromises()
+
+ // Snapshot value renders without any probe.
+ expect(queryBalance).not.toHaveBeenCalled()
+ expect(wrapper.get('[data-test="cn-provider-balance-value"]').text()).toContain('CNY 12.50')
+
+ // The control reads as an action; the i18n mock returns the key itself.
+ const probeButton = wrapper.get('[data-test="cn-provider-balance-probe"]')
+ expect(probeButton.text()).toBe('admin.accounts.cnProviders.probe')
+
+ await probeButton.trigger('click')
+ await flushPromises()
+ expect(queryBalance).toHaveBeenCalledWith(account.id)
+ })
+
+ it('shows the low-balance badge from the snapshot marker', () => {
+ const lowAccount = {
+ ...account,
+ extra: { kimi_balance: 0.4, kimi_balance_low: true }
+ } as Account
+
+ const wrapper = mount(CNProviderBalanceCell, { props: { account: lowAccount } })
+
+ expect(wrapper.text()).toContain('admin.accounts.cnProviders.balanceLow')
+ })
+
+ it('keeps the snapshot balance visible when a query fails', async () => {
+ queryBalance.mockResolvedValue({ success: false, error: 'HTTP 401' })
+ const wrapper = mount(CNProviderBalanceCell, { props: { account } })
+
+ await wrapper.get('[data-test="cn-provider-balance-probe"]').trigger('click')
+ await flushPromises()
+
+ expect(wrapper.text()).toContain('CNY 12.50')
+ expect(wrapper.text()).toContain('HTTP 401')
+ })
+})
diff --git a/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts b/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts
index 20a23585f8..ab50774ed1 100644
--- a/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts
+++ b/frontend/src/components/account/__tests__/CNProviderQuotaCell.spec.ts
@@ -73,4 +73,23 @@ describe('CNProviderQuotaCell', () => {
expect(queryQuota).toHaveBeenCalledWith(account.id)
})
+
+ it('labels the refresh control with an explicit action verb, not a data caption', async () => {
+ const wrapper = mount(CNProviderQuotaCell, { props: { account } })
+ await flushPromises()
+
+ // The snapshot is fresh (usage_updated_at = now): bars render without probing.
+ expect(queryQuota).not.toHaveBeenCalled()
+ expect(wrapper.text()).toContain('27%')
+
+ // The control reads as an action ("query"), unlike the old noun label
+ // ("5-hour window/weekly window") which looked like a passive caption.
+ // The i18n mock returns the key itself.
+ const probeButton = wrapper.get('[data-test="cn-provider-quota-probe"]')
+ expect(probeButton.text()).toBe('admin.accounts.cnProviders.probe')
+
+ await probeButton.trigger('click')
+ await flushPromises()
+ expect(queryQuota).toHaveBeenCalledWith(account.id)
+ })
})
diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts
index d70e7ec6d2..26305c4233 100644
--- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts
+++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts
@@ -5,25 +5,35 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
createAccountMock,
probeUpstreamBillingMock,
+ syncUpstreamModelsMock,
+ showWarningMock,
importCodexSessionMock,
createOpenAICodexPATMock,
+ authIsSimpleMode,
} = vi.hoisted(() => ({
createAccountMock: vi.fn(),
probeUpstreamBillingMock: vi.fn(),
+ syncUpstreamModelsMock: vi.fn(),
+ showWarningMock: vi.fn(),
importCodexSessionMock: vi.fn(),
createOpenAICodexPATMock: vi.fn(),
+ authIsSimpleMode: { value: true },
}))
vi.mock('@/stores/app', () => ({
useAppStore: () => ({
showError: vi.fn(),
showSuccess: vi.fn(),
- showWarning: vi.fn(),
+ showWarning: showWarningMock,
}),
}))
vi.mock('@/stores/auth', () => ({
- useAuthStore: () => ({ isSimpleMode: true }),
+ useAuthStore: () => ({
+ get isSimpleMode() {
+ return authIsSimpleMode.value
+ },
+ }),
}))
vi.mock('@/api/admin', () => ({
@@ -31,6 +41,7 @@ vi.mock('@/api/admin', () => ({
accounts: {
create: createAccountMock,
probeUpstreamBilling: probeUpstreamBillingMock,
+ syncUpstreamModels: syncUpstreamModelsMock,
checkMixedChannelRisk: vi.fn().mockResolvedValue({ has_risk: false }),
importCodexSession: importCodexSessionMock,
createOpenAICodexPAT: createOpenAICodexPATMock,
@@ -84,9 +95,47 @@ const OAuthAuthorizationFlowStub = defineComponent({
`,
})
-function mountModal() {
+const GroupSelectorStub = defineComponent({
+ name: 'GroupSelector',
+ props: {
+ modelValue: {
+ type: Array,
+ default: () => [],
+ },
+ },
+ emits: ['update:modelValue'],
+ template: `
+
+ groups
+
+ `,
+})
+
+const ModelWhitelistSelectorStub = defineComponent({
+ name: 'ModelWhitelistSelector',
+ props: {
+ modelValue: {
+ type: Array,
+ default: () => [],
+ },
+ platform: String,
+ syncCredentials: Object,
+ },
+ emits: ['update:modelValue', 'upstream-synced'],
+ template: `models `,
+})
+
+function mountModal(groups: any[] = []) {
return mount(CreateAccountModal, {
- props: { show: true, proxies: [], groups: [] },
+ props: { show: true, proxies: [], groups },
global: {
stubs: {
BaseDialog: BaseDialogStub,
@@ -97,8 +146,8 @@ function mountModal() {
PlatformIcon: true,
ProxySelector: true,
ProxyAdBanner: true,
- GroupSelector: true,
- ModelWhitelistSelector: true,
+ GroupSelector: GroupSelectorStub,
+ ModelWhitelistSelector: ModelWhitelistSelectorStub,
QuotaLimitCard: true,
},
},
@@ -147,8 +196,11 @@ async function openCodexImportStep(toggleClicks = 0) {
describe('CreateAccountModal OpenAI long-context billing', () => {
beforeEach(() => {
+ authIsSimpleMode.value = true
createAccountMock.mockReset().mockResolvedValue({ id: 42, platform: 'openai', type: 'apikey' })
probeUpstreamBillingMock.mockReset().mockResolvedValue({})
+ syncUpstreamModelsMock.mockReset().mockResolvedValue({ models: [], metadata: {} })
+ showWarningMock.mockReset()
importCodexSessionMock.mockReset().mockResolvedValue({
created: 1,
updated: 0,
@@ -160,6 +212,34 @@ describe('CreateAccountModal OpenAI long-context billing', () => {
createOpenAICodexPATMock.mockReset().mockResolvedValue({})
})
+ it('hides only the redundant account toggle when every selected group enables tier pricing', async () => {
+ authIsSimpleMode.value = false
+ const wrapper = mountModal([
+ { id: 1, long_context_pricing_enabled: true },
+ { id: 2, long_context_pricing_enabled: true },
+ ])
+
+ await selectButtonByText(wrapper, 'OpenAI')
+ await wrapper.get('[data-testid="select-pricing-groups"]').trigger('click')
+
+ expect(wrapper.find('[data-testid="openai-long-context-billing-toggle"]').exists()).toBe(false)
+ expect(wrapper.find('[data-testid="create-openai-ws-mode"]').exists()).toBe(true)
+ })
+
+ it('keeps the account toggle when any selected group disables tier pricing', async () => {
+ authIsSimpleMode.value = false
+ const wrapper = mountModal([
+ { id: 1, long_context_pricing_enabled: true },
+ { id: 2, long_context_pricing_enabled: false },
+ ])
+
+ await selectButtonByText(wrapper, 'OpenAI')
+ await wrapper.get('[data-testid="select-pricing-groups"]').trigger('click')
+
+ expect(wrapper.find('[data-testid="openai-long-context-billing-toggle"]').exists()).toBe(true)
+ expect(wrapper.find('[data-testid="create-openai-ws-mode"]').exists()).toBe(true)
+ })
+
it('sends false explicitly for normal OpenAI account creation by default', async () => {
await submitApiKeyAccount('openai')
@@ -167,6 +247,71 @@ describe('CreateAccountModal OpenAI long-context billing', () => {
expect(createAccountMock.mock.calls[0]?.[0]?.extra?.openai_long_context_billing_enabled).toBe(false)
})
+ it('persists upstream model metadata after creating an account from preview', async () => {
+ const wrapper = mountModal()
+ await selectButtonByText(wrapper, 'OpenAI')
+ await selectButtonByText(wrapper, 'API Key')
+ await wrapper.get('form#create-account-form input[type="text"]').setValue('OpenCode account')
+ await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key')
+ await wrapper.get('[data-testid="model-whitelist-selector"]').trigger('click')
+ await wrapper.get('form#create-account-form').trigger('submit.prevent')
+ await flushPromises()
+
+ expect(createAccountMock).toHaveBeenCalledOnce()
+ expect(syncUpstreamModelsMock).toHaveBeenCalledWith(42)
+ })
+
+ it('includes the current concrete model mapping in preview credentials', async () => {
+ const wrapper = mountModal()
+ await selectButtonByText(wrapper, 'OpenAI')
+ await selectButtonByText(wrapper, 'API Key')
+ await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key')
+ await wrapper.get('[data-testid="model-whitelist-selector"]').trigger('click')
+ await flushPromises()
+
+ expect(wrapper.getComponent(ModelWhitelistSelectorStub).props('syncCredentials')).toMatchObject({
+ model_mapping: { 'public-glm': 'public-glm' }
+ })
+ })
+
+ it('runs formal capability sync after creating an account with explicit mappings', async () => {
+ const wrapper = mountModal()
+ await selectButtonByText(wrapper, 'OpenAI')
+ await selectButtonByText(wrapper, 'API Key')
+ await wrapper.get('form#create-account-form input[type="text"]').setValue('Mapped account')
+ await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key')
+ await selectButtonByText(wrapper, 'admin.accounts.modelMapping')
+ await selectButtonByText(wrapper, 'admin.accounts.addMapping')
+ await wrapper.get('input[placeholder="admin.accounts.requestModel"]').setValue('public-glm')
+ await wrapper.get('input[placeholder="admin.accounts.actualModel"]').setValue('glm-5.3')
+ await wrapper.get('form#create-account-form').trigger('submit.prevent')
+ await flushPromises()
+
+ expect(createAccountMock.mock.calls[0]?.[0]?.credentials?.model_mapping).toEqual({
+ 'public-glm': 'glm-5.3'
+ })
+ expect(syncUpstreamModelsMock).toHaveBeenCalledWith(42)
+ })
+
+ it('warns when post-create capability metadata remains incomplete', async () => {
+ syncUpstreamModelsMock.mockResolvedValue({
+ models: ['x-preview-f-free'],
+ warnings: [{ code: 'upstream_model_metadata_incomplete', message: 'metadata incomplete' }],
+ })
+ const wrapper = mountModal()
+ await selectButtonByText(wrapper, 'OpenAI')
+ await selectButtonByText(wrapper, 'API Key')
+ await wrapper.get('form#create-account-form input[type="text"]').setValue('OpenCode account')
+ await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key')
+ await wrapper.get('[data-testid="model-whitelist-selector"]').trigger('click')
+ await wrapper.get('form#create-account-form').trigger('submit.prevent')
+ await flushPromises()
+
+ expect(showWarningMock).toHaveBeenCalledWith(
+ 'admin.accounts.syncUpstreamModelsMetadataIncomplete'
+ )
+ })
+
// namespace 摊平是仅 OAuth 的兼容开关:API Key 走 chat completions 回退桥时由桥自行摊平
it('shows the Codex namespace flatten toggle only for OpenAI OAuth accounts', async () => {
const wrapper = mountModal()
@@ -214,6 +359,43 @@ describe('CreateAccountModal OpenAI long-context billing', () => {
expect(probeUpstreamBillingMock).not.toHaveBeenCalled()
})
+ it('submits adaptive Kimi protocol endpoints', async () => {
+ const wrapper = mountModal()
+ await selectButtonByText(wrapper, 'Kimi')
+ await wrapper.get('form#create-account-form input[type="text"]').setValue('Kimi adaptive')
+ await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-kimi')
+
+ await wrapper.get('form#create-account-form').trigger('submit.prevent')
+ await flushPromises()
+
+ expect(createAccountMock).toHaveBeenCalledTimes(1)
+ expect(createAccountMock.mock.calls[0]?.[0]?.credentials).toMatchObject({
+ account_mode: 'payg',
+ api_protocol: 'adaptive',
+ base_url: 'https://api.moonshot.cn/v1',
+ api_base_urls: {
+ chat_completions: 'https://api.moonshot.cn/v1',
+ anthropic: 'https://api.moonshot.cn/anthropic'
+ }
+ })
+ })
+
+ it('uses the edited adaptive Chat endpoint when previewing upstream models', async () => {
+ const wrapper = mountModal()
+ await selectButtonByText(wrapper, 'Kimi')
+ await wrapper
+ .get('[data-testid="cn-adaptive-base-url-chat_completions"]')
+ .setValue('https://relay.example.com/v1')
+ await wrapper.get('form#create-account-form input[type="password"]').setValue('sk-relay')
+
+ expect(wrapper.getComponent(ModelWhitelistSelectorStub).props('syncCredentials')).toMatchObject({
+ platform: 'kimi',
+ type: 'apikey',
+ base_url: 'https://relay.example.com/v1',
+ api_key: 'sk-relay'
+ })
+ })
+
it('exposes Agent Identity in the OpenAI authorization methods', async () => {
const wrapper = mountModal()
await selectButtonByText(wrapper, 'OpenAI')
diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts
index e21089313e..eceb670c92 100644
--- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts
+++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts
@@ -290,6 +290,18 @@ function buildOpenAISetupTokenAccount() {
} as any
}
+function buildOpenAIOAuthParentAccount() {
+ return {
+ ...buildAccount(),
+ id: 7,
+ name: 'OpenAI OAuth Parent',
+ type: 'oauth',
+ parent_account_id: null,
+ credentials: { access_token: 'oauth-token' },
+ extra: {}
+ } as any
+}
+
function mountModal(account = buildAccount()) {
return mount(EditAccountModal, {
props: {
@@ -343,6 +355,178 @@ describe('EditAccountModal', () => {
})
})
+ it('preserves adaptive GLM endpoints on submit', async () => {
+ const account = buildAccount()
+ account.platform = 'zhipu'
+ account.credentials = {
+ api_key: 'sk-glm',
+ account_mode: 'coding',
+ api_protocol: 'adaptive',
+ base_url: 'https://open.bigmodel.cn/api/coding/paas/v4',
+ api_base_urls: {
+ chat_completions: 'https://open.bigmodel.cn/api/coding/paas/v4',
+ anthropic: 'https://open.bigmodel.cn/api/anthropic'
+ }
+ }
+ updateAccountMock.mockReset().mockResolvedValue(account)
+ checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false })
+
+ const wrapper = mountModal(account)
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ expect(updateAccountMock.mock.calls[0]?.[1]?.credentials).toMatchObject({
+ account_mode: 'coding',
+ api_protocol: 'adaptive',
+ base_url: 'https://open.bigmodel.cn/api/coding/paas/v4',
+ api_base_urls: {
+ chat_completions: 'https://open.bigmodel.cn/api/coding/paas/v4',
+ anthropic: 'https://open.bigmodel.cn/api/anthropic'
+ }
+ })
+ })
+
+ it.each([
+ ['explicit Chat Completions', 'chat_completions'],
+ ['legacy missing protocol', undefined]
+ ])('preserves a custom CN relay for %s accounts', async (_name, storedProtocol) => {
+ const account = buildAccount()
+ account.platform = 'zhipu'
+ account.credentials = {
+ api_key: 'sk-glm',
+ account_mode: 'payg',
+ base_url: 'https://relay.example.com/v1'
+ }
+ if (storedProtocol) {
+ account.credentials.api_protocol = storedProtocol
+ }
+ updateAccountMock.mockReset().mockResolvedValue(account)
+ checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false })
+
+ const wrapper = mountModal(account)
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ const submittedCredentials = updateAccountMock.mock.calls[0]?.[1]?.credentials
+ expect(submittedCredentials).toMatchObject({
+ account_mode: 'payg',
+ api_protocol: 'chat_completions',
+ base_url: 'https://relay.example.com/v1'
+ })
+ expect(submittedCredentials).not.toHaveProperty('api_base_urls')
+ })
+
+ it('uses the legacy base_url when adaptive endpoints are missing', async () => {
+ const account = buildAccount()
+ account.platform = 'zhipu'
+ account.credentials = {
+ api_key: 'sk-glm',
+ account_mode: 'payg',
+ api_protocol: 'adaptive',
+ base_url: 'https://relay.example.com/v1',
+ api_base_urls: {
+ chat_completions: ' '
+ }
+ }
+ updateAccountMock.mockReset().mockResolvedValue(account)
+ checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false })
+
+ const wrapper = mountModal(account)
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ expect(updateAccountMock.mock.calls[0]?.[1]?.credentials).toMatchObject({
+ api_protocol: 'adaptive',
+ base_url: 'https://relay.example.com/v1',
+ api_base_urls: {
+ chat_completions: 'https://relay.example.com/v1',
+ anthropic: 'https://open.bigmodel.cn/api/anthropic'
+ }
+ })
+ })
+
+ it('carries a fixed Chat relay into Adaptive when the user switches protocols', async () => {
+ const account = buildAccount()
+ account.platform = 'zhipu'
+ account.credentials = {
+ api_key: 'sk-glm',
+ account_mode: 'payg',
+ api_protocol: 'chat_completions',
+ base_url: 'https://relay.example.com/v1'
+ }
+ updateAccountMock.mockReset().mockResolvedValue(account)
+ checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false })
+
+ const wrapper = mountModal(account)
+ const adaptiveButton = wrapper
+ .findAll('button')
+ .find(button => button.text().includes('admin.accounts.cnProviders.apiProtocol.adaptive'))
+ expect(adaptiveButton).toBeDefined()
+ await adaptiveButton!.trigger('click')
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ expect(updateAccountMock.mock.calls[0]?.[1]?.credentials).toMatchObject({
+ api_protocol: 'adaptive',
+ base_url: 'https://relay.example.com/v1',
+ api_base_urls: {
+ chat_completions: 'https://relay.example.com/v1'
+ }
+ })
+ })
+
+ it.each([
+ {
+ name: 'Anthropic',
+ platform: 'zhipu',
+ protocol: 'anthropic',
+ baseUrl: 'https://relay.example.com/anthropic',
+ expectedBaseUrl: 'https://open.bigmodel.cn/api/paas/v4',
+ expectedProtocolUrls: {
+ chat_completions: 'https://open.bigmodel.cn/api/paas/v4',
+ anthropic: 'https://relay.example.com/anthropic'
+ }
+ },
+ {
+ name: 'Responses',
+ platform: 'deepseek',
+ protocol: 'responses',
+ baseUrl: 'https://relay.example.com/responses',
+ expectedBaseUrl: 'https://api.deepseek.com',
+ expectedProtocolUrls: {
+ chat_completions: 'https://api.deepseek.com',
+ anthropic: 'https://api.deepseek.com/anthropic',
+ responses: 'https://relay.example.com/responses'
+ }
+ }
+ ])('keeps a fixed $name relay in its protocol slot when switching to Adaptive', async (testCase) => {
+ const account = buildAccount()
+ account.platform = testCase.platform
+ account.credentials = {
+ api_key: 'sk-cn',
+ account_mode: 'payg',
+ api_protocol: testCase.protocol,
+ base_url: testCase.baseUrl
+ }
+ updateAccountMock.mockReset().mockResolvedValue(account)
+ checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false })
+
+ const wrapper = mountModal(account)
+ const adaptiveButton = wrapper
+ .findAll('button')
+ .find(button => button.text().includes('admin.accounts.cnProviders.apiProtocol.adaptive'))
+ expect(adaptiveButton).toBeDefined()
+ await adaptiveButton!.trigger('click')
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ expect(updateAccountMock.mock.calls[0]?.[1]?.credentials).toMatchObject({
+ api_protocol: 'adaptive',
+ base_url: testCase.expectedBaseUrl,
+ api_base_urls: testCase.expectedProtocolUrls
+ })
+ })
+
it('preserves model mappings when editing the whitelist', async () => {
const account = buildAccount()
account.credentials.model_mapping = {
@@ -1179,3 +1363,63 @@ describe('EditAccountModal', () => {
)
})
})
+
+describe('EditAccountModal OpenAI 自动使用重置卡', () => {
+ beforeEach(() => {
+ authIsSimpleMode.value = true
+ updateAccountMock.mockReset()
+ checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false })
+ })
+
+ it('仅对 OpenAI OAuth 母账号显示,默认关闭且阈值为 100/100', () => {
+ const parent = mountModal(buildOpenAIOAuthParentAccount())
+ expect(parent.find('[data-testid="auto-reset-credit-settings"]').exists()).toBe(true)
+ expect((parent.get('[data-testid="auto-reset-credit-5h-threshold"]').element as HTMLInputElement).value).toBe('100')
+ expect((parent.get('[data-testid="auto-reset-credit-7d-threshold"]').element as HTMLInputElement).value).toBe('100')
+ expect(parent.get('[data-testid="auto-reset-credit-5h-threshold"]').attributes('disabled')).toBeDefined()
+ parent.unmount()
+
+ for (const account of [buildAccount(), buildOpenAISetupTokenAccount(), buildOpenAISparkShadowAccount()]) {
+ const wrapper = mountModal(account)
+ expect(wrapper.find('[data-testid="auto-reset-credit-settings"]').exists()).toBe(false)
+ wrapper.unmount()
+ }
+ })
+
+ it('独立保存两个阈值,并禁止把运行态回写到管理请求', async () => {
+ const account = buildOpenAIOAuthParentAccount()
+ account.extra = {
+ codex_auto_reset_credit_state: {
+ status: 'success',
+ trigger_window: '5h',
+ available_count: 1
+ }
+ }
+ updateAccountMock.mockResolvedValue(account)
+ const wrapper = mountModal(account)
+
+ await wrapper.get('[data-testid="auto-reset-credit-enabled"]').trigger('click')
+ await wrapper.get('[data-testid="auto-reset-credit-5h-threshold"]').setValue('75.5')
+ await wrapper.get('[data-testid="auto-reset-credit-7d-threshold"]').setValue('92')
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+
+ expect(updateAccountMock).toHaveBeenCalledTimes(1)
+ const extra = updateAccountMock.mock.calls[0]?.[1]?.extra
+ expect(extra).toMatchObject({
+ auto_reset_credit_enabled: true,
+ auto_reset_credit_5h_threshold: 0.755,
+ auto_reset_credit_7d_threshold: 0.92
+ })
+ expect(extra).not.toHaveProperty('codex_auto_reset_credit_state')
+ wrapper.unmount()
+ })
+
+ it('开启后拒绝超出 0.1–100 范围的任一阈值', async () => {
+ const wrapper = mountModal(buildOpenAIOAuthParentAccount())
+ await wrapper.get('[data-testid="auto-reset-credit-enabled"]').trigger('click')
+ await wrapper.get('[data-testid="auto-reset-credit-5h-threshold"]').setValue('0')
+ await wrapper.get('form#edit-account-form').trigger('submit.prevent')
+ expect(updateAccountMock).not.toHaveBeenCalled()
+ wrapper.unmount()
+ })
+})
diff --git a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts
index 51f18611cc..928ab6e721 100644
--- a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts
+++ b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts
@@ -1,7 +1,23 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
-const copyToClipboard = vi.fn().mockResolvedValue(true)
+const {
+ copyToClipboard,
+ showError,
+ showSuccess,
+ showInfo,
+ showWarning,
+ syncUpstreamModels,
+ syncUpstreamModelsPreview
+} = vi.hoisted(() => ({
+ copyToClipboard: vi.fn().mockResolvedValue(true),
+ showError: vi.fn(),
+ showSuccess: vi.fn(),
+ showInfo: vi.fn(),
+ showWarning: vi.fn(),
+ syncUpstreamModels: vi.fn(),
+ syncUpstreamModelsPreview: vi.fn()
+}))
vi.mock('vue-i18n', async () => {
const actual = await vi.importActual('vue-i18n')
@@ -15,12 +31,20 @@ vi.mock('vue-i18n', async () => {
vi.mock('@/stores/app', () => ({
useAppStore: () => ({
- showError: vi.fn(),
- showSuccess: vi.fn(),
- showInfo: vi.fn()
+ showError,
+ showSuccess,
+ showInfo,
+ showWarning
})
}))
+vi.mock('@/api/admin/accounts', () => ({
+ accountsAPI: {
+ syncUpstreamModels,
+ syncUpstreamModelsPreview
+ }
+}))
+
vi.mock('@/composables/useClipboard', () => ({
useClipboard: () => ({
copyToClipboard
@@ -29,11 +53,12 @@ vi.mock('@/composables/useClipboard', () => ({
import ModelWhitelistSelector from '../ModelWhitelistSelector.vue'
-function mountSelector() {
+function mountSelector(props: Record = {}) {
return mount(ModelWhitelistSelector, {
props: {
modelValue: [],
- platform: 'openai'
+ platform: 'openai',
+ ...props,
},
global: {
stubs: {
@@ -58,6 +83,12 @@ function findModelRow(wrapper: ReturnType, modelId: string
describe('ModelWhitelistSelector', () => {
beforeEach(() => {
copyToClipboard.mockClear()
+ showError.mockReset()
+ showSuccess.mockReset()
+ showInfo.mockReset()
+ showWarning.mockReset()
+ syncUpstreamModels.mockReset()
+ syncUpstreamModelsPreview.mockReset()
})
it('copies a model ID without selecting the model', async () => {
@@ -86,4 +117,71 @@ describe('ModelWhitelistSelector', () => {
expect(wrapper.emitted('update:modelValue')).toEqual([[['gpt-5.6-sol']]])
expect(copyToClipboard).not.toHaveBeenCalled()
})
+
+ it('warns when model IDs sync but capability metadata is incomplete', async () => {
+ syncUpstreamModels.mockResolvedValue({
+ models: ['x-preview-f-free'],
+ warnings: [
+ {
+ code: 'upstream_model_metadata_incomplete',
+ message: 'Model IDs were synced, but capability metadata could not be updated.'
+ }
+ ]
+ })
+ const wrapper = mount(ModelWhitelistSelector, {
+ props: {
+ modelValue: [],
+ platform: 'openai',
+ accountId: 46
+ },
+ global: {
+ stubs: {
+ ModelIcon: true
+ }
+ }
+ })
+
+ const syncButton = wrapper
+ .findAll('button')
+ .find(button => button.text() === 'admin.accounts.syncUpstreamModels')
+ expect(syncButton).toBeDefined()
+ await syncButton!.trigger('click')
+ await flushPromises()
+
+ expect(wrapper.emitted('update:modelValue')).toEqual([[['x-preview-f-free']]])
+ expect(showWarning).toHaveBeenCalledWith('admin.accounts.syncUpstreamModelsMetadataIncomplete')
+ expect(showSuccess).not.toHaveBeenCalled()
+ })
+
+ it('reports a successful preview so account creation can persist metadata', async () => {
+ syncUpstreamModelsPreview.mockResolvedValue({
+ models: ['x-preview-f-free'],
+ metadata: {
+ 'x-preview-f-free': {
+ id: 'x-preview-f-free',
+ reasoning: true,
+ supported_reasoning_levels: ['low', 'high', 'max'],
+ },
+ },
+ })
+ const wrapper = mountSelector({
+ syncCredentials: {
+ platform: 'openai',
+ type: 'apikey',
+ base_url: 'https://opencode.ai/zen/v1',
+ api_key: 'test-key',
+ },
+ })
+ const syncButton = wrapper
+ .findAll('button')
+ .find(button => button.text() === 'admin.accounts.syncUpstreamModels')
+
+ expect(syncButton).toBeDefined()
+ await syncButton?.trigger('click')
+ await flushPromises()
+
+ expect(syncUpstreamModelsPreview).toHaveBeenCalledOnce()
+ expect(wrapper.emitted('upstream-synced')).toEqual([[]])
+ expect(wrapper.emitted('update:modelValue')).toEqual([[['x-preview-f-free']]])
+ })
})
diff --git a/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts b/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts
index f888cbee44..280725bc5b 100644
--- a/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts
+++ b/frontend/src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts
@@ -344,3 +344,45 @@ describe('OpenAIQuotaResetCell — 外审 F6:影子禁用重置', () => {
wrapper.unmount()
})
})
+
+describe('OpenAIQuotaResetCell 自动用卡运行态', () => {
+ it.each([
+ ['checking', 'checking'],
+ ['available', 'available'],
+ ['resetting', 'resetting'],
+ ['success', 'success'],
+ ['no_credit', 'noCredit'],
+ ['failed', 'failed'],
+ ] as const)('展示 %s 状态且不需要暴露卡标识', (status, labelKey) => {
+ const account = makeAccount({
+ extra: {
+ auto_reset_credit_enabled: true,
+ codex_auto_reset_credit_state: {
+ status,
+ trigger_window: '5h',
+ available_count: 1,
+ checked_at: '2099-07-03T04:05:06Z',
+ error_code: status === 'failed' ? 'RESET_FAILED' : undefined,
+ },
+ },
+ })
+ const wrapper = mount(OpenAIQuotaResetCell, { props: { account } })
+ const state = wrapper.get('[data-testid="auto-reset-credit-state"]')
+ expect(state.text()).toContain(`admin.accounts.openaiQuotaReset.autoStatus.${labelKey}`)
+ expect(state.text()).toContain('5h')
+ expect(state.text()).not.toContain('credit_id')
+ wrapper.unmount()
+ })
+
+ it('开关关闭时不显示历史运行态', () => {
+ const account = makeAccount({
+ extra: {
+ auto_reset_credit_enabled: false,
+ codex_auto_reset_credit_state: { status: 'success', available_count: 1 },
+ },
+ })
+ const wrapper = mount(OpenAIQuotaResetCell, { props: { account } })
+ expect(wrapper.find('[data-testid="auto-reset-credit-state"]').exists()).toBe(false)
+ wrapper.unmount()
+ })
+})
diff --git a/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts b/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts
new file mode 100644
index 0000000000..618210ddf0
--- /dev/null
+++ b/frontend/src/components/account/__tests__/credentialsBuilder.cnAdaptive.spec.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest'
+
+import { defaultCNAdaptiveBaseUrls } from '../credentialsBuilder'
+
+describe('defaultCNAdaptiveBaseUrls', () => {
+ it('resolves Kimi endpoints by account mode', () => {
+ expect(defaultCNAdaptiveBaseUrls('kimi', 'payg')).toEqual({
+ chat_completions: 'https://api.moonshot.cn/v1',
+ anthropic: 'https://api.moonshot.cn/anthropic',
+ responses: ''
+ })
+ expect(defaultCNAdaptiveBaseUrls('kimi', 'coding')).toEqual({
+ chat_completions: 'https://api.kimi.com/coding/v1',
+ anthropic: 'https://api.kimi.com/coding',
+ responses: ''
+ })
+ })
+
+ it('resolves GLM endpoints by account mode', () => {
+ expect(defaultCNAdaptiveBaseUrls('zhipu', 'payg')).toEqual({
+ chat_completions: 'https://open.bigmodel.cn/api/paas/v4',
+ anthropic: 'https://open.bigmodel.cn/api/anthropic',
+ responses: ''
+ })
+ expect(defaultCNAdaptiveBaseUrls('zhipu', 'coding')).toEqual({
+ chat_completions: 'https://open.bigmodel.cn/api/coding/paas/v4',
+ anthropic: 'https://open.bigmodel.cn/api/anthropic',
+ responses: ''
+ })
+ })
+
+ it('includes all three native DeepSeek endpoints', () => {
+ expect(defaultCNAdaptiveBaseUrls('deepseek', 'payg')).toEqual({
+ chat_completions: 'https://api.deepseek.com',
+ anthropic: 'https://api.deepseek.com/anthropic',
+ responses: 'https://api.deepseek.com'
+ })
+ })
+})
diff --git a/frontend/src/components/account/__tests__/longContextBilling.spec.ts b/frontend/src/components/account/__tests__/longContextBilling.spec.ts
new file mode 100644
index 0000000000..70e2c55695
--- /dev/null
+++ b/frontend/src/components/account/__tests__/longContextBilling.spec.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest'
+
+import { allSelectedGroupsEnableLongContextPricing } from '../longContextBilling'
+
+const group = (id: number, enabled: boolean) => ({
+ id,
+ long_context_pricing_enabled: enabled,
+}) as any
+
+describe('allSelectedGroupsEnableLongContextPricing', () => {
+ it('hides the account override when every selected group enables tier pricing', () => {
+ expect(allSelectedGroupsEnableLongContextPricing(
+ [1, 2],
+ [group(1, true), group(2, true)]
+ )).toBe(true)
+ })
+
+ it('keeps the account override when any selected group disables tier pricing', () => {
+ expect(allSelectedGroupsEnableLongContextPricing(
+ [1, 2],
+ [group(1, true), group(2, false)]
+ )).toBe(false)
+ })
+
+ it('keeps the account override when selection is empty or group data is incomplete', () => {
+ expect(allSelectedGroupsEnableLongContextPricing([], [group(1, true)])).toBe(false)
+ expect(allSelectedGroupsEnableLongContextPricing([1, 2], [group(1, true)])).toBe(false)
+ })
+})
diff --git a/frontend/src/components/account/credentialsBuilder.ts b/frontend/src/components/account/credentialsBuilder.ts
index 1ba2cb22bf..7f844fba0a 100644
--- a/frontend/src/components/account/credentialsBuilder.ts
+++ b/frontend/src/components/account/credentialsBuilder.ts
@@ -256,8 +256,9 @@ export const GROK_BASE_URL_PRESETS: GrokBaseUrlPreset[] = [
export type CnAccountMode = 'payg' | 'coding'
-/** 仅 deepseek 支持 responses 协议(官方原生 /responses 端点,适配 Codex)。 */
-export type CnApiProtocol = 'chat_completions' | 'anthropic' | 'responses'
+/** 仅 deepseek 支持原生 responses;adaptive 会按入站协议选择原生端点。 */
+export type CnApiProtocol = 'adaptive' | 'chat_completions' | 'anthropic' | 'responses'
+export type CnNativeApiProtocol = Exclude
export interface CnBaseUrlPreset {
mode: CnAccountMode
@@ -321,6 +322,18 @@ export function defaultCNBaseUrl(
}
}
+/** 返回自适应模式下需要配置的原生协议及其默认端点。 */
+export function defaultCNAdaptiveBaseUrls(
+ platform: 'kimi' | 'zhipu' | 'deepseek',
+ mode: CnAccountMode
+): Record {
+ return {
+ chat_completions: defaultCNBaseUrl(platform, mode, 'chat_completions'),
+ anthropic: defaultCNBaseUrl(platform, mode, 'anthropic'),
+ responses: platform === 'deepseek' ? defaultCNBaseUrl(platform, mode, 'responses') : ''
+ }
+}
+
// ===== 国产供应商用量单元格可见性(单一事实源) =====
// CNProviderQuotaCell / CNProviderBalanceCell 与 AccountUsageCell 的占位符判定
// 共用,避免多处复制条件后一处改另一处漏改。
diff --git a/frontend/src/components/account/longContextBilling.ts b/frontend/src/components/account/longContextBilling.ts
new file mode 100644
index 0000000000..38c64391b5
--- /dev/null
+++ b/frontend/src/components/account/longContextBilling.ts
@@ -0,0 +1,11 @@
+import type { AdminGroup } from '@/types'
+
+export function allSelectedGroupsEnableLongContextPricing(
+ groupIds: number[],
+ groups: AdminGroup[]
+): boolean {
+ if (groupIds.length === 0) return false
+ const selectedGroups = groups.filter(group => groupIds.includes(group.id))
+ return selectedGroups.length === groupIds.length &&
+ selectedGroups.every(group => group.long_context_pricing_enabled === true)
+}
diff --git a/frontend/src/components/admin/ErrorPassthroughRulesModal.vue b/frontend/src/components/admin/ErrorPassthroughRulesModal.vue
index 7d0058b759..ce8d14424d 100644
--- a/frontend/src/components/admin/ErrorPassthroughRulesModal.vue
+++ b/frontend/src/components/admin/ErrorPassthroughRulesModal.vue
@@ -433,6 +433,7 @@
import { ref, reactive, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
+import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'
import { adminAPI } from '@/api/admin'
import type { ErrorPassthroughRule } from '@/api/admin/errorPassthrough'
import BaseDialog from '@/components/common/BaseDialog.vue'
@@ -485,13 +486,7 @@ const matchModeOptions = computed(() => [
{ value: 'all', label: t('admin.errorPassthrough.matchMode.all'), description: t('admin.errorPassthrough.matchMode.allHint') }
])
-const platformOptions = [
- { value: 'anthropic', label: 'Anthropic' },
- { value: 'openai', label: 'OpenAI' },
- { value: 'gemini', label: 'Gemini' },
- { value: 'antigravity', label: 'Antigravity' },
- { value: 'grok', label: 'Grok' }
-]
+const platformOptions = CONCRETE_PLATFORM_OPTIONS
// Load rules when dialog opens
watch(() => props.show, (newVal) => {
diff --git a/frontend/src/components/admin/account/AccountTableFilters.vue b/frontend/src/components/admin/account/AccountTableFilters.vue
index a0587f27f8..9e48be822b 100644
--- a/frontend/src/components/admin/account/AccountTableFilters.vue
+++ b/frontend/src/components/admin/account/AccountTableFilters.vue
@@ -18,6 +18,7 @@
diff --git a/frontend/src/components/auth/LinuxDoOAuthSection.vue b/frontend/src/components/auth/LinuxDoOAuthSection.vue
index a8ae927eee..3333b4175c 100644
--- a/frontend/src/components/auth/LinuxDoOAuthSection.vue
+++ b/frontend/src/components/auth/LinuxDoOAuthSection.vue
@@ -48,6 +48,7 @@ import { resolveAffiliateReferralCode, storeOAuthAffiliateCode } from '@/utils/o
const props = withDefaults(defineProps<{
disabled?: boolean
affCode?: string
+ promoCode?: string
showDivider?: boolean
}>(), {
showDivider: true
@@ -62,6 +63,11 @@ const { t } = useI18n()
function startLogin(): void {
const redirectTo = (route.query.redirect as string) || '/dashboard'
storeOAuthAffiliateCode(resolveAffiliateReferralCode(props.affCode, route.query.aff, route.query.aff_code))
- emit('start', { provider: 'linuxdo', params: { redirect: redirectTo } })
+ const params: Record = { redirect: redirectTo }
+ const promoCode = props.promoCode?.trim()
+ if (promoCode) {
+ params.promo_code = promoCode
+ }
+ emit('start', { provider: 'linuxdo', params })
}
diff --git a/frontend/src/components/auth/__tests__/EmailOAuthButtons.spec.ts b/frontend/src/components/auth/__tests__/EmailOAuthButtons.spec.ts
index 845d763744..a7e5dc54a1 100644
--- a/frontend/src/components/auth/__tests__/EmailOAuthButtons.spec.ts
+++ b/frontend/src/components/auth/__tests__/EmailOAuthButtons.spec.ts
@@ -33,6 +33,7 @@ describe('EmailOAuthButtons', () => {
props: {
githubEnabled: true,
googleEnabled: false,
+ promoCode: ' PROMO123 ',
},
global: {
stubs: {
@@ -47,7 +48,7 @@ describe('EmailOAuthButtons', () => {
expect(wrapper.emitted('start')).toEqual([[
{
provider: 'github',
- params: { redirect: '/billing?plan=pro', aff_code: 'AFF123' }
+ params: { redirect: '/billing?plan=pro', aff_code: 'AFF123', promo_code: 'PROMO123' }
}
]])
expect(window.sessionStorage.getItem('oauth_aff_code')).toBe('AFF123')
@@ -60,6 +61,7 @@ describe('EmailOAuthButtons', () => {
props: {
githubEnabled: false,
googleEnabled: true,
+ promoCode: 'PROMO456',
},
global: {
stubs: {
@@ -73,7 +75,7 @@ describe('EmailOAuthButtons', () => {
expect(wrapper.emitted('start')?.[0]?.[0]).toEqual({
provider: 'google',
- params: { redirect: '/billing?plan=pro', aff_code: 'AFF123' }
+ params: { redirect: '/billing?plan=pro', aff_code: 'AFF123', promo_code: 'PROMO456' }
})
expect(window.location.href).toBe(originalHref)
})
diff --git a/frontend/src/components/auth/__tests__/OAuthLoginSections.spec.ts b/frontend/src/components/auth/__tests__/OAuthLoginSections.spec.ts
index 5111ac6f66..897d78e9aa 100644
--- a/frontend/src/components/auth/__tests__/OAuthLoginSections.spec.ts
+++ b/frontend/src/components/auth/__tests__/OAuthLoginSections.spec.ts
@@ -41,4 +41,23 @@ describe('OAuth login sections', () => {
expect(window.sessionStorage.getItem('oauth_aff_code')).toBe('AFF456')
expect(window.location.href).toBe(originalHref)
})
+
+ it('includes a trimmed promo code in the LinuxDo OAuth request', async () => {
+ const wrapper = mount(LinuxDoOAuthSection, {
+ props: {
+ affCode: 'AFF456',
+ promoCode: ' PROMO789 '
+ }
+ })
+
+ await wrapper.get('button').trigger('click')
+
+ expect(wrapper.emitted('start')?.[0]?.[0]).toEqual({
+ provider: 'linuxdo',
+ params: {
+ redirect: '/billing?plan=pro',
+ promo_code: 'PROMO789'
+ }
+ })
+ })
})
diff --git a/frontend/src/components/keys/UseKeyModal.vue b/frontend/src/components/keys/UseKeyModal.vue
index c8ae79d229..fc5356cf5e 100644
--- a/frontend/src/components/keys/UseKeyModal.vue
+++ b/frontend/src/components/keys/UseKeyModal.vue
@@ -172,6 +172,65 @@
+
+
+
+
+ {{ t('keys.useKeyModal.codexModelCatalog.title') }}
+
+
+ {{ t('keys.useKeyModal.codexModelCatalog.description') }}
+
+
+ {{ codexModelCatalogPath }}
+
+
+
+
+ {{ t('keys.useKeyModal.codexModelCatalog.download') }}
+
+
+
+ {{ codexModelManifestState === 'error'
+ ? t('keys.useKeyModal.codexModelCatalog.retry')
+ : t('keys.useKeyModal.codexModelCatalog.fetch') }}
+
+
+
+ {{ t('keys.useKeyModal.codexModelCatalog.modelsCount', { count: codexModelManifestModelCount }) }}
+
+
+ {{ t('keys.useKeyModal.codexModelCatalog.errorDescription') }}
+
+
+
@@ -198,10 +257,18 @@
diff --git a/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue b/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue
index edc72365ff..d4aac37a07 100644
--- a/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue
+++ b/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue
@@ -1,15 +1,15 @@
-
+
-
-
-
+
+
+
-
-
+
+
-
+
-
+
{{ m.name }}
+
+
+ {{
+ t('modelPlaza.table.timePricingWeekdays')
+ }}
+ {{ formatTimeWindow(period) }}
+
+ {{ t('modelPlaza.table.marginalBadge') }}
+
-
+
@@ -93,11 +111,11 @@
:key="idx"
class="whitespace-nowrap text-xs leading-5"
>
- {{ tierLabel(iv) }}
- {{ paidPerMillion(iv.input_price) }}
+ {{ tierLabel(iv) }}
+ {{ paidPerMillion(iv.input_price, period) }}
- {{ paidPerMillion(m.pricing?.input_price) }}
+ {{ paidPerMillion(m.pricing?.input_price, period) }}
@@ -105,25 +123,41 @@
v-for="(iv, idx) in tokenIntervals(m)"
:key="idx"
class="whitespace-nowrap text-xs leading-5"
+ :title="tierHint(m)"
>
- {{ tierLabel(iv) }}
- {{ paidPerMillion(iv.output_price) }}
+ {{ paidPerMillion(iv.output_price, period) }}
- {{ paidPerMillion(m.pricing?.output_price) }}
+ {{ paidPerMillion(m.pricing?.output_price, period) }}
+
+
+
+ {{ t('modelPlaza.table.cacheWriteShort') }}
+ {{ paidPerMillion(iv.cache_write_price, period) }}
+ {{ t('modelPlaza.table.cacheReadShort') }}
+ {{ paidPerMillion(iv.cache_read_price, period) }}
+
+ -
+
+
{{ t('modelPlaza.table.cacheWrite') }}
- {{ paidPerMillion(m.pricing?.cache_write_price) }}
+ {{ paidPerMillion(m.pricing?.cache_write_price, period) }}
{{ t('modelPlaza.table.cacheRead') }}
- {{ paidPerMillion(m.pricing?.cache_read_price) }}
+ {{ paidPerMillion(m.pricing?.cache_read_price, period) }}
-
@@ -157,18 +191,54 @@
-
+
- {{ official(m.official_pricing?.input_price) }}
+
+
+ {{ tierLabel(iv) }}
+ {{ official(iv.input_price) }}
+
+
+ {{ official(m.official_pricing?.input_price) }}
- {{ official(m.official_pricing?.output_price) }}
+
+
+ {{ official(iv.output_price) }}
+
+
+ {{ official(m.official_pricing?.output_price) }}
+
+
+
+ {{ t('modelPlaza.table.cacheWriteShort') }}
+ {{ official(iv.cache_write_price) }}
+ {{ t('modelPlaza.table.cacheReadShort') }}
+ {{ official(iv.cache_read_price) }}
+
+ -
+
+
-
+
{{ periodRate(period) }}x
+ {{ requestRate(m) }}x
@@ -218,7 +294,7 @@ import {
BILLING_MODE_IMAGE,
type BillingMode
} from '@/constants/channel'
-import type { PlazaModel } from '@/api/modelPlaza'
+import type { PlazaModel, PlazaTimePricingPeriod } from '@/api/modelPlaza'
import type { UserPricingInterval } from '@/api/channels'
const props = defineProps<{
@@ -232,6 +308,13 @@ const props = defineProps<{
/** 生图独立倍率:true 时图片计费模型的实付倍率取 imageRateMultiplier,不取分组/专属倍率。 */
imageRateIndependent?: boolean
imageRateMultiplier?: number | null
+ /**
+ * 高峰窗口描述(含倍率与服务器时区标注),空串/缺省 = 分组未启用高峰。
+ * 表格所有价格均为不含高峰因子的口径,该窗口仅用于分时时段行的 tooltip 披露:
+ * 与高峰重叠的部分实付还会再乘高峰倍率。
+ */
+ peakWindow?: string
+ peakRateMultiplier?: number | null
}>()
const { t } = useI18n()
@@ -279,10 +362,35 @@ function billingModeLabel(m: PlazaModel): string {
/** 价格统一保底 2 位小数,更长的有效小数原样保留。 */
const MIN_DECIMALS = 2
-/** 实付价 = 渠道单价 × 生效倍率,按 $/1M token 展示。 */
-function paidPerMillion(value: number | null | undefined): string {
+/** 表格行:每个模型一行标准价;配置了分时倍率的模型再按时段各加一行。 */
+interface PlazaRow {
+ model: PlazaModel
+ period: PlazaTimePricingPeriod | null
+ key: string
+}
+
+const rows = computed(() =>
+ sortedModels.value.flatMap((m) => {
+ const base: PlazaRow = { model: m, period: null, key: `${m.platform}:${m.name}` }
+ const periodRows = timePeriods(m).map((p, idx) => ({
+ model: m,
+ period: p,
+ key: `${m.platform}:${m.name}:${idx}`
+ }))
+ return [base, ...periodRows]
+ })
+)
+
+/** 时段行的生效倍率 = 生效倍率 × 时段倍率(去掉浮点噪声)。 */
+function periodRate(period: PlazaTimePricingPeriod): number {
+ return Math.round(effectiveRate.value * period.multiplier * 1000) / 1000
+}
+
+/** 实付价 = 渠道单价 × 生效倍率(时段行再乘时段倍率),按 $/1M token 展示。 */
+function paidPerMillion(value: number | null | undefined, period: PlazaTimePricingPeriod | null = null): string {
if (value == null) return '-'
- return formatScaled(value * effectiveRate.value, PER_MILLION, MIN_DECIMALS)
+ const rate = period ? periodRate(period) : effectiveRate.value
+ return formatScaled(value * rate, PER_MILLION, MIN_DECIMALS)
}
/** 图片计费模型且分组开启生图独立倍率:实付倍率取独立倍率,与计费口径一致。 */
@@ -322,23 +430,76 @@ function hasOfficialCache(o: NonNullable): boole
return o.cache_write_price != null || o.cache_read_price != null || o.cache_write_1h_price != null
}
-/** token 模式的阶梯定价(内联进输入/输出列)。 */
-function tokenIntervals(m: PlazaModel): UserPricingInterval[] {
- return m.pricing?.intervals ?? []
+/** 分时倍率时段(后端只给出倍率 ≠ 1 的时段,已升序)。 */
+function timePeriods(m: PlazaModel): PlazaTimePricingPeriod[] {
+ return m.time_pricing?.periods ?? []
}
+/**
+ * 时段行 tooltip:仅工作日生效的配置换用带周末回落说明的文案;
+ * 分组启用高峰倍率时追加披露——本行价格不含高峰因子,与高峰窗口重叠的部分实付再乘高峰倍率。
+ */
+function timePricingRowHint(m: PlazaModel): string {
+ const key = m.time_pricing?.weekdays_only
+ ? 'modelPlaza.table.timePricingRowHintWeekdays'
+ : 'modelPlaza.table.timePricingRowHint'
+ let hint = t(key, { timezone: m.time_pricing?.timezone })
+ if (props.peakWindow) {
+ hint += t('modelPlaza.table.timePricingRowHintPeak', {
+ window: props.peakWindow,
+ multiplier: props.peakRateMultiplier ?? 1
+ })
+ }
+ return hint
+}
+
+/** “00:30–08:30”;整分钟的 HH:mm:ss 省略秒。 */
+function formatTimeWindow(p: PlazaTimePricingPeriod): string {
+ const clock = (v: string) => v.replace(/^(\d{2}:\d{2}):00$/, '$1')
+ return `${clock(p.start_time)}–${clock(p.end_time)}`
+}
+
+/** 上下文档位按下限升序展示(后端已升序,此处兜底)。 */
+function sortByContext(intervals: UserPricingInterval[]): UserPricingInterval[] {
+ return [...intervals].sort((a, b) => a.min_tokens - b.min_tokens)
+}
+
+/** token 模式的阶梯定价(内联进输入/输出/缓存列)。 */
+function tokenIntervals(m: PlazaModel): UserPricingInterval[] {
+ return sortByContext(m.pricing?.intervals ?? [])
+}
+
+/** 官方阶梯(后端按目录规则合成,不受分组开关影响)。 */
+function officialIntervals(m: PlazaModel): UserPricingInterval[] {
+ return sortByContext(m.official_pricing?.intervals ?? [])
+}
+
+/** 任一档带缓存价才按档渲染缓存列;否则沿用平价的写入/读取两行。 */
+function hasTierCachePricing(intervals: UserPricingInterval[]): boolean {
+ return intervals.some((iv) => iv.cache_write_price != null || iv.cache_read_price != null)
+}
+
+/** 档位说明:整单按档计价,或(平台旧规则)仅超出部分按档计价。 */
+function tierHint(m: PlazaModel): string {
+ return m.long_context_basis === 'marginal'
+ ? t('modelPlaza.table.tierHintMarginal')
+ : t('modelPlaza.table.tierHint')
+}
+
+
/** 按次/按图模式的阶梯定价(仅保留配了按次价的档位)。 */
function requestIntervals(m: PlazaModel): UserPricingInterval[] {
return (m.pricing?.intervals ?? []).filter((iv) => iv.per_request_price != null)
}
-/** 档位标签:优先管理员配置的 tier_label,否则按 token 区间生成(≤200K / >200K / 200K–1M)。 */
+/**
+ * 档位标签:优先后端/管理员给出的 tier_label,否则按区间生成统一形态——
+ * 有上限为「≤上限」,末档为「>下限」;档位升序排列,相邻的 ≤100K / ≤200K 即表示 (100K,200K]。
+ */
function tierLabel(iv: UserPricingInterval): string {
if (iv.tier_label) return iv.tier_label
const { min_tokens: min, max_tokens: max } = iv
- if (max == null) return `>${formatTokenCount(min)}`
- if (min === 0) return `≤${formatTokenCount(max)}`
- return `${formatTokenCount(min)}–${formatTokenCount(max)}`
+ return max == null ? `>${formatTokenCount(min)}` : `≤${formatTokenCount(max)}`
}
function formatTokenCount(n: number): string {
diff --git a/frontend/src/components/modelPlaza/__tests__/PlazaGroupSection.spec.ts b/frontend/src/components/modelPlaza/__tests__/PlazaGroupSection.spec.ts
new file mode 100644
index 0000000000..aad4e25a35
--- /dev/null
+++ b/frontend/src/components/modelPlaza/__tests__/PlazaGroupSection.spec.ts
@@ -0,0 +1,139 @@
+import { describe, expect, it, vi } from 'vitest'
+import { mount } from '@vue/test-utils'
+import PlazaGroupSection from '../PlazaGroupSection.vue'
+import PlazaModelPricingTable from '../PlazaModelPricingTable.vue'
+import type { ModelPlazaGroup, PlazaModel } from '@/api/modelPlaza'
+
+vi.mock('vue-i18n', async () => {
+ const actual = await vi.importActual('vue-i18n')
+ return {
+ ...actual,
+ useI18n: () => ({
+ t: (key: string) => key
+ })
+ }
+})
+
+vi.mock('@/stores/app', () => ({
+ useAppStore: () => ({ cachedPublicSettings: null })
+}))
+
+function ladderModel(tiers: number): PlazaModel {
+ const intervals = Array.from({ length: tiers }, (_, i) => ({
+ min_tokens: i * 272000,
+ max_tokens: i === tiers - 1 ? null : (i + 1) * 272000,
+ tier_label: '',
+ input_price: 5e-6,
+ output_price: 3e-5,
+ cache_write_price: null,
+ cache_read_price: null,
+ per_request_price: null
+ }))
+ return {
+ name: 'gpt-5.6-sol',
+ platform: 'openai',
+ pricing: {
+ billing_mode: 'token',
+ input_price: 5e-6,
+ output_price: 3e-5,
+ cache_write_price: null,
+ cache_read_price: null,
+ image_input_price: null,
+ image_output_price: null,
+ per_request_price: null,
+ intervals: []
+ },
+ official_pricing: {
+ input_price: 5e-6,
+ output_price: 3e-5,
+ cache_write_price: null,
+ cache_read_price: null,
+ intervals
+ }
+ }
+}
+
+function group(overrides: Partial = {}): ModelPlazaGroup {
+ return {
+ id: 1,
+ name: 'g',
+ description: '',
+ platform: 'openai',
+ subscription_type: 'standard',
+ rate_multiplier: 1,
+ peak_rate_enabled: false,
+ peak_start: '',
+ peak_end: '',
+ peak_rate_multiplier: 1,
+ is_exclusive: false,
+ image_rate_independent: false,
+ image_rate_multiplier: 1,
+ long_context_pricing_enabled: true,
+ models: [ladderModel(2)],
+ ...overrides
+ }
+}
+
+function mountSection(g: ModelPlazaGroup) {
+ return mount(PlazaGroupSection, {
+ props: { group: g },
+ global: {
+ stubs: {
+ GroupBadge: true,
+ Icon: true,
+ PlazaModelPricingTable: true
+ }
+ }
+ })
+}
+
+const NOTE = 'modelPlaza.detail.longContextDisabledNote'
+
+describe('PlazaGroupSection 长上下文说明', () => {
+ it('分组关闭阶梯且组内有官方阶梯模型时显示说明', () => {
+ const wrapper = mountSection(group({ long_context_pricing_enabled: false }))
+ expect(wrapper.text()).toContain(NOTE)
+ })
+
+ it('分组开启阶梯时不显示', () => {
+ const wrapper = mountSection(group({ long_context_pricing_enabled: true }))
+ expect(wrapper.text()).not.toContain(NOTE)
+ })
+
+ it('分组关闭但没有官方阶梯模型时不显示', () => {
+ const wrapper = mountSection(
+ group({ long_context_pricing_enabled: false, models: [ladderModel(1)] })
+ )
+ expect(wrapper.text()).not.toContain(NOTE)
+ })
+
+ it('旧后端缺少开关字段时不显示', () => {
+ const g = group()
+ delete (g as Partial).long_context_pricing_enabled
+ const wrapper = mountSection(g)
+ expect(wrapper.text()).not.toContain(NOTE)
+ })
+})
+
+describe('PlazaGroupSection 高峰配置传递', () => {
+ it('分组启用高峰时把窗口描述与倍率传给价格表', () => {
+ const wrapper = mountSection(
+ group({
+ subscription_type: 'subscription',
+ peak_rate_enabled: true,
+ peak_start: '14:00',
+ peak_end: '18:00',
+ peak_rate_multiplier: 1.5
+ })
+ )
+ const table = wrapper.findComponent(PlazaModelPricingTable)
+ // appStore mock 无 server_utc_offset,窗口描述不带时区标注
+ expect(table.props('peakWindow')).toBe('14:00-18:00 ×1.5')
+ expect(table.props('peakRateMultiplier')).toBe(1.5)
+ })
+
+ it('分组未启用高峰时窗口描述为空串', () => {
+ const wrapper = mountSection(group())
+ expect(wrapper.findComponent(PlazaModelPricingTable).props('peakWindow')).toBe('')
+ })
+})
diff --git a/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts b/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts
index ca5f72cd6a..b4acf6efe5 100644
--- a/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts
+++ b/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts
@@ -43,7 +43,12 @@ function mountTable(
models: PlazaModel[],
rateMultiplier: number,
userRateMultiplier?: number | null,
- extraProps?: { imageRateIndependent?: boolean; imageRateMultiplier?: number | null }
+ extraProps?: {
+ imageRateIndependent?: boolean
+ imageRateMultiplier?: number | null
+ peakWindow?: string
+ peakRateMultiplier?: number | null
+ }
) {
return mount(PlazaModelPricingTable, {
props: { models, rateMultiplier, userRateMultiplier: userRateMultiplier ?? null, ...extraProps }
@@ -405,3 +410,225 @@ describe('PlazaModelPricingTable', () => {
expect(wrapper.text()).toContain('OpenAI')
})
})
+
+describe('PlazaModelPricingTable 长上下文阶梯', () => {
+ function ladderIntervals() {
+ return [
+ {
+ min_tokens: 0,
+ max_tokens: 272000,
+ tier_label: '≤272K',
+ input_price: 5e-6,
+ output_price: 3e-5,
+ cache_write_price: 6.25e-6,
+ cache_read_price: 5e-7,
+ per_request_price: null
+ },
+ {
+ min_tokens: 272000,
+ max_tokens: null,
+ tier_label: '>272K',
+ input_price: 1e-5,
+ output_price: 4.5e-5,
+ cache_write_price: 1.25e-5,
+ cache_read_price: 1e-6,
+ per_request_price: null
+ }
+ ]
+ }
+
+ function ladderModel(overrides: Partial = {}): PlazaModel {
+ return tokenModel({
+ name: 'gpt-5.6-sol',
+ platform: 'openai',
+ pricing: {
+ billing_mode: 'token',
+ input_price: 5e-6,
+ output_price: 3e-5,
+ cache_write_price: 6.25e-6,
+ cache_read_price: 5e-7,
+ image_input_price: null,
+ image_output_price: null,
+ per_request_price: null,
+ intervals: ladderIntervals()
+ },
+ official_pricing: {
+ input_price: 5e-6,
+ output_price: 3e-5,
+ cache_write_price: 6.25e-6,
+ cache_read_price: 5e-7,
+ intervals: ladderIntervals()
+ },
+ long_context_basis: 'whole_request',
+ ...overrides
+ })
+ }
+
+ it('实付缓存列按档分行并乘倍率,每档一行与输入/输出列对齐;档位标签只在输入列', () => {
+ const wrapper = mountTable([ladderModel()], 0.5)
+ const cells = wrapper.findAll('tbody td')
+ const cacheCell = cells[3]
+ const rows = cacheCell.findAll('.leading-5')
+ expect(rows).toHaveLength(2)
+ // 写 6.25 × 0.5 / 读 0.5 × 0.5;高档 12.5 × 0.5 / 1 × 0.5
+ expect(rows[0].text()).toContain('modelPlaza.table.cacheWriteShort')
+ expect(rows[0].text()).toContain('$3.125')
+ expect(rows[0].text()).toContain('$0.25')
+ expect(rows[1].text()).toContain('$6.25')
+ expect(rows[1].text()).toContain('$0.50')
+ // 输入列带标签,输出/缓存列只按行对齐不重复标签
+ expect(cells[1].text()).toContain('≤272K')
+ expect(cells[1].text()).toContain('>272K')
+ expect(cells[2].text()).not.toContain('272K')
+ expect(cacheCell.text()).not.toContain('272K')
+ expect(cells[1].findAll('.leading-5')).toHaveLength(2)
+ expect(cells[2].findAll('.leading-5')).toHaveLength(2)
+ })
+
+ it('官方三列按 official_pricing.intervals 分档且不乘倍率,不内联 1h', () => {
+ const wrapper = mountTable([ladderModel()], 0.5)
+ const cells = wrapper.findAll('tbody td')
+ expect(cells[4].text()).toContain('≤272K')
+ expect(cells[4].text()).toContain('$5.00')
+ expect(cells[4].text()).toContain('>272K')
+ expect(cells[4].text()).toContain('$10.00')
+ expect(cells[5].text()).toContain('$30.00')
+ expect(cells[5].text()).toContain('$45.00')
+ expect(cells[6].text()).toContain('$6.25')
+ expect(cells[6].text()).toContain('$12.50')
+ expect(cells[6].text()).toContain('$1.00')
+ expect(cells[6].text()).not.toContain('(1h')
+ })
+
+ it('整单计价的档位标签带 tooltip;边际计价在模型名旁加徽章并换用边际说明', () => {
+ const whole = mountTable([ladderModel()], 1)
+ const wholeLabels = whole.findAll('tbody td span[title="modelPlaza.table.tierHint"]')
+ expect(wholeLabels.length).toBeGreaterThan(0)
+ expect(whole.text()).not.toContain('modelPlaza.table.marginalBadge')
+
+ const marginal = mountTable([ladderModel({ long_context_basis: 'marginal' })], 1)
+ const marginalLabels = marginal.findAll('tbody td span[title="modelPlaza.table.tierHintMarginal"]')
+ expect(marginalLabels.length).toBeGreaterThan(0)
+ expect(marginal.findAll('tbody td')[0].text()).toContain('modelPlaza.table.marginalBadge')
+ })
+
+ it('无标签的多档按区间生成统一形态(≤上限 / >下限),并按下限升序展示', () => {
+ const model = ladderModel({
+ pricing: {
+ ...ladderModel().pricing!,
+ // 故意乱序:展示必须按上下文从低到高
+ intervals: [
+ { ...ladderIntervals()[1], min_tokens: 1000000, tier_label: '' },
+ { ...ladderIntervals()[0], min_tokens: 100000, max_tokens: 200000, tier_label: '' },
+ { ...ladderIntervals()[0], max_tokens: 100000, tier_label: '' },
+ { ...ladderIntervals()[1], min_tokens: 200000, max_tokens: 1000000, tier_label: '' }
+ ]
+ }
+ })
+ const rows = mountTable([model], 1).findAll('tbody td')[1].findAll('.leading-5')
+ expect(rows.map((r) => r.text().split(/\s+/)[0])).toEqual(['≤100K', '≤200K', '≤1M', '>1M'])
+ })
+
+ it('官方无 intervals 字段(旧响应)时官方列保持平价,实付无阶梯时缓存列保持两行', () => {
+ const wrapper = mountTable([tokenModel()], 1)
+ const cells = wrapper.findAll('tbody td')
+ expect(cells[3].text()).toContain('modelPlaza.table.cacheWrite')
+ expect(cells[3].text()).toContain('modelPlaza.table.cacheRead')
+ expect(cells[3].findAll('.leading-5')).toHaveLength(0)
+ expect(cells[6].text()).toContain('(1h')
+ })
+})
+
+describe('PlazaModelPricingTable 分时计价', () => {
+ function timePricedModel() {
+ return tokenModel({
+ name: 'deepseek-chat',
+ platform: 'deepseek',
+ time_pricing: {
+ timezone: 'Asia/Shanghai',
+ periods: [
+ { start_time: '00:30', end_time: '08:30:00', multiplier: 0.5 },
+ { start_time: '18:00', end_time: '22:00', multiplier: 1.2 }
+ ]
+ }
+ })
+ }
+
+ it('有分时倍率的模型展开为标准行 + 每时段一行,时段行价格按倍率折算且倍率列显示生效倍率', () => {
+ const wrapper = mountTable([timePricedModel()], 0.8)
+ const trs = wrapper.findAll('tbody tr')
+ expect(trs).toHaveLength(3)
+
+ // 标准行:输入 3 × 0.8
+ const baseCells = trs[0].findAll('td')
+ expect(baseCells[0].text()).toBe('deepseek-chat')
+ expect(baseCells[1].text()).toContain('$2.40')
+ expect(baseCells[7].text()).toContain('0.8x')
+
+ // 夜间时段行:输入 3 × 0.8 × 0.5,倍率 0.4x,标注时段不含时区
+ const nightCells = trs[1].findAll('td')
+ expect(nightCells[0].text()).toContain('deepseek-chat')
+ expect(nightCells[0].text()).toContain('00:30–08:30')
+ expect(nightCells[0].text()).not.toContain('Asia/Shanghai')
+ // 时区只放在 tooltip 里(i18n mock 不做插值,这里只断言挂了说明)
+ expect(nightCells[0].find('[title="modelPlaza.table.timePricingRowHint"]').exists()).toBe(true)
+ expect(nightCells[1].text()).toContain('$1.20')
+ expect(nightCells[2].text()).toContain('$6.00')
+ expect(nightCells[3].text()).toContain('$1.50')
+ expect(nightCells[7].text()).toContain('0.4x')
+
+ // 晚高峰行:3 × 0.8 × 1.2 = 2.88,倍率 0.96x
+ const peakCells = trs[2].findAll('td')
+ expect(peakCells[0].text()).toContain('18:00–22:00')
+ expect(peakCells[1].text()).toContain('$2.88')
+ expect(peakCells[7].text()).toContain('0.96x')
+
+ // 官方列不受时段影响
+ expect(nightCells[4].text()).toContain('$3.00')
+ })
+
+ it('仅工作日生效时时段行带工作日前缀,tooltip 换用周末回落文案', () => {
+ const model = timePricedModel()
+ model.time_pricing!.weekdays_only = true
+ const wrapper = mountTable([model], 1)
+ const trs = wrapper.findAll('tbody tr')
+ expect(trs).toHaveLength(3)
+
+ const nightCells = trs[1].findAll('td')
+ expect(nightCells[0].text()).toContain('modelPlaza.table.timePricingWeekdays')
+ expect(nightCells[0].text()).toContain('00:30–08:30')
+ expect(nightCells[0].find('[title="modelPlaza.table.timePricingRowHintWeekdays"]').exists()).toBe(true)
+ expect(nightCells[0].find('[title="modelPlaza.table.timePricingRowHint"]').exists()).toBe(false)
+ })
+
+ it('每日生效(无 weekdays_only)不渲染工作日前缀', () => {
+ const wrapper = mountTable([timePricedModel()], 1)
+ expect(wrapper.find('tbody').text()).not.toContain('modelPlaza.table.timePricingWeekdays')
+ expect(wrapper.find('[title="modelPlaza.table.timePricingRowHint"]').exists()).toBe(true)
+ })
+
+ it('分组启用高峰倍率时时段行 tooltip 追加高峰披露,价格与倍率列保持不含高峰的口径', () => {
+ const wrapper = mountTable([timePricedModel()], 0.8, null, {
+ peakWindow: '14:00-18:00 ×1.5 (UTC+08:00)',
+ peakRateMultiplier: 1.5
+ })
+ const nightCells = wrapper.findAll('tbody tr')[1].findAll('td')
+ const title = nightCells[0].find('[title*="modelPlaza.table.timePricingRowHint"]').attributes('title')
+ expect(title).toContain('modelPlaza.table.timePricingRowHintPeak')
+ // 行内数字仍是 基础倍率 × 时段倍率(0.8 × 0.5),高峰只进披露不进价格
+ expect(nightCells[1].text()).toContain('$1.20')
+ expect(nightCells[7].text()).toContain('0.4x')
+ })
+
+ it('分组未启用高峰(peakWindow 缺省)时 tooltip 不含高峰披露', () => {
+ const wrapper = mountTable([timePricedModel()], 1)
+ const badge = wrapper.find('[title*="modelPlaza.table.timePricingRowHint"]')
+ expect(badge.attributes('title')).not.toContain('modelPlaza.table.timePricingRowHintPeak')
+ })
+
+ it('无分时倍率时只有一行,不渲染时段标注', () => {
+ const wrapper = mountTable([tokenModel()], 1)
+ expect(wrapper.findAll('tbody tr')).toHaveLength(1)
+ expect(wrapper.find('[title*="modelPlaza.table.timePricingRowHint"]').exists()).toBe(false)
+ })
+})
diff --git a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts
index 9fd93e6573..af6cc61820 100644
--- a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts
+++ b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts
@@ -51,7 +51,8 @@ describe('useModelWhitelist', () => {
expect(models).toContain('grok-4.5')
expect(models).toContain('grok-4.5-latest')
expect(models).toContain('grok-build-latest')
- expect(models).toContain('grok-imagine-video-1.5-preview')
+ expect(models).toContain('grok-imagine-image-2.0')
+ expect(models).toContain('grok-imagine-video-1.5')
})
it('combined 模式支持 Grok 4.5 官方别名映射', () => {
diff --git a/frontend/src/composables/useModelWhitelist.ts b/frontend/src/composables/useModelWhitelist.ts
index 2ca860c673..4b16d44b02 100644
--- a/frontend/src/composables/useModelWhitelist.ts
+++ b/frontend/src/composables/useModelWhitelist.ts
@@ -157,8 +157,8 @@ const xaiModels = [
'grok-imagine',
'grok-imagine-image-quality',
'grok-imagine-image',
+ 'grok-imagine-image-2.0',
'grok-imagine-video',
- 'grok-imagine-video-1.5-preview',
'grok-imagine-video-1.5'
]
diff --git a/frontend/src/constants/__tests__/platforms.spec.ts b/frontend/src/constants/__tests__/platforms.spec.ts
new file mode 100644
index 0000000000..2b38fbaf3f
--- /dev/null
+++ b/frontend/src/constants/__tests__/platforms.spec.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest'
+import { CONCRETE_PLATFORM_OPTIONS, GROUP_PLATFORM_OPTIONS } from '@/constants/platforms'
+
+const concretePlatforms = [
+ 'anthropic',
+ 'openai',
+ 'gemini',
+ 'antigravity',
+ 'grok',
+ 'kimi',
+ 'zhipu',
+ 'deepseek'
+]
+
+describe('platform option catalogs', () => {
+ it('exposes every concrete account platform', () => {
+ expect(CONCRETE_PLATFORM_OPTIONS.map((option) => option.value)).toEqual(concretePlatforms)
+ })
+
+ it('adds composite for group-backed filters', () => {
+ expect(GROUP_PLATFORM_OPTIONS.map((option) => option.value)).toEqual([
+ ...concretePlatforms,
+ 'composite'
+ ])
+ })
+})
diff --git a/frontend/src/constants/platforms.ts b/frontend/src/constants/platforms.ts
new file mode 100644
index 0000000000..a47987bd7c
--- /dev/null
+++ b/frontend/src/constants/platforms.ts
@@ -0,0 +1,28 @@
+import type { AccountPlatform, GroupPlatform } from '@/types'
+
+export interface PlatformOption {
+ value: T
+ label: string
+}
+
+/**
+ * Concrete upstream platforms supported by accounts and request routing.
+ * Keep platform selectors derived from this catalog so newly added providers
+ * do not silently disappear from list filters.
+ */
+export const CONCRETE_PLATFORM_OPTIONS = [
+ { value: 'anthropic', label: 'Anthropic' },
+ { value: 'openai', label: 'OpenAI' },
+ { value: 'gemini', label: 'Gemini' },
+ { value: 'antigravity', label: 'Antigravity' },
+ { value: 'grok', label: 'Grok' },
+ { value: 'kimi', label: 'Kimi' },
+ { value: 'zhipu', label: 'Zhipu GLM' },
+ { value: 'deepseek', label: 'DeepSeek' }
+] as const satisfies readonly PlatformOption[]
+
+/** Platforms that can own a group. */
+export const GROUP_PLATFORM_OPTIONS = [
+ ...CONCRETE_PLATFORM_OPTIONS,
+ { value: 'composite', label: 'Composite' }
+] as const satisfies readonly PlatformOption[]
diff --git a/frontend/src/i18n/__tests__/opsLocaleKeys.spec.ts b/frontend/src/i18n/__tests__/opsLocaleKeys.spec.ts
index d44a47dbc8..4f5cdd4e38 100644
--- a/frontend/src/i18n/__tests__/opsLocaleKeys.spec.ts
+++ b/frontend/src/i18n/__tests__/opsLocaleKeys.spec.ts
@@ -21,6 +21,13 @@ describe('ops locale key completeness', () => {
'admin.ops.timeRange.custom',
'admin.ops.customTimeRange.startTime',
'admin.ops.customTimeRange.endTime',
+ 'admin.ops.errorDetail.upstreamStatus',
+ 'admin.ops.errorDetail.rootCause',
+ 'admin.ops.errorDetail.diagnosticPayloads',
+ 'admin.ops.errorDetail.payloads.client',
+ 'admin.ops.errorDetail.payloads.upstream_message',
+ 'admin.ops.errorDetail.payloads.upstream_detail',
+ 'admin.ops.errorDetail.payloads.upstream_events',
]
for (const key of requiredKeys) {
@@ -29,6 +36,13 @@ describe('ops locale key completeness', () => {
expect(enKeys).toContain(key)
})
}
+
+ for (const key of requiredKeys) {
+ it(`zh locale has ${key}`, () => {
+ const zhKeys = flattenKeys(zh)
+ expect(zhKeys).toContain(key)
+ })
+ }
})
describe('groups locale key completeness', () => {
diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts
index 858e420b99..ae0867b9f1 100644
--- a/frontend/src/i18n/locales/en/admin/accounts.ts
+++ b/frontend/src/i18n/locales/en/admin/accounts.ts
@@ -118,6 +118,10 @@ export default {
},
apiProtocol: {
title: 'API Protocol',
+ adaptive: 'Adaptive',
+ adaptiveDesc: 'Uses the matching native provider endpoint for each inbound protocol, converting only when unavailable.',
+ endpoints: 'Protocol endpoints',
+ responsesFallbackDesc: 'Responses requests are converted to Chat Completions because this provider has no native Responses endpoint.',
chatCompletions: 'Chat Completions',
chatCompletionsDesc: 'Standard OpenAI-compatible endpoint; requests in other formats are converted.',
anthropic: 'Anthropic',
@@ -128,7 +132,9 @@ export default {
balance: 'Balance --',
window5h: '5-hour window',
windowWeekly: 'Weekly window',
+ probe: 'Query',
probeTooltip: 'Query the provider quota endpoint for 5-hour / weekly rolling window usage',
+ balanceProbeTooltip: 'Query the provider balance endpoint for the account balance',
balanceLow: 'Insufficient balance',
noBalanceEndpoint: 'This platform has no balance query endpoint',
resetSoon: 'reset soon',
@@ -737,6 +743,8 @@ export default {
syncUpstreamModelsEmpty: 'Upstream returned no models to sync',
syncUpstreamModelsFailed: 'Failed to sync upstream models',
syncUpstreamModelsError: 'Failed to sync upstream models: {message}',
+ syncUpstreamModelsMetadataIncomplete:
+ 'Model IDs were synced, but capability metadata is incomplete and was not updated.',
clearAllModels: 'Clear all models',
customModelName: 'Custom model name',
enterCustomModelName: 'Enter custom model name',
@@ -815,6 +823,14 @@ export default {
autoPause5hDisabled: 'Disable 5h auto-pause',
autoPause7dDisabled: 'Disable 7d auto-pause',
autoPauseDisabledHint: 'When enabled, this account is never auto-paused (even if a global default threshold is configured).',
+ autoResetCredit: {
+ title: 'Automatically use reset credits',
+ hint: 'Uses the earliest-expiring available credit only when actual usage reaches a threshold. Off by default; the account remains paused if no credit is available or reset fails.',
+ threshold5h: '5h auto-reset threshold (%)',
+ threshold7d: '7d auto-reset threshold (%)',
+ thresholdHint: 'Each window is evaluated independently. Enter 0.1–100; both default to 100.',
+ thresholdInvalid: 'Automatic reset-credit thresholds must be between 0.1% and 100%.'
+ },
// Quota control (Anthropic OAuth/SetupToken only)
quotaControl: {
title: 'Quota Control',
@@ -1509,6 +1525,14 @@ export default {
resetAccountRecoveryFailed: 'The window was reset, but account state recovery failed. Recover the account state manually.',
resetAccountRefreshFailed: 'The window, account state, and reset-credit cache were updated, but the latest account display could not be loaded.',
refreshCachePersistFailed: 'Showing the live count, but its expiration details were unavailable, so the cached details were kept.',
+ autoStatus: {
+ checking: 'Checking',
+ available: 'Credit available',
+ resetting: 'Auto-resetting',
+ success: 'Auto-reset succeeded',
+ noCredit: 'No credit',
+ failed: 'Auto-reset failed'
+ },
confirmTitle: 'Confirm Weekly Limit Reset',
confirmMessage: 'This will consume 1 reset credit to immediately restore the current window ({count} remaining). This action cannot be undone. Continue?'
},
diff --git a/frontend/src/i18n/locales/en/admin/channels.ts b/frontend/src/i18n/locales/en/admin/channels.ts
index 41793496f0..404bcc17d1 100644
--- a/frontend/src/i18n/locales/en/admin/channels.ts
+++ b/frontend/src/i18n/locales/en/admin/channels.ts
@@ -70,6 +70,7 @@ export default {
maxPositive: 'Interval #{index}: maximum token count ({value}) must be greater than 0',
maxGreaterThanMin: 'Interval #{index}: maximum token count ({max}) must be greater than minimum token count ({min})',
negativePrice: 'Interval #{index}: {field} cannot be negative',
+ multiplierPositive: 'Interval #{index}: {field} must be greater than 0',
unboundedLast: 'Interval #{index}: an unbounded interval (empty maximum token count) must be last',
overlap: 'Intervals #{previousIndex} and #{currentIndex} overlap: previous upper bound ({previousMax}) is greater than current lower bound ({currentMin})',
price: {
@@ -128,9 +129,20 @@ export default {
imageTokenPrice: 'Image Output',
imageOutputPrice: 'Image Output Price',
pricePlaceholder: 'Default',
+ fastMultiplier: 'Fast Multiplier',
+ flexMultiplier: 'Flex Multiplier',
+ multiplierPlaceholder: 'Not set',
+ multiplierPositive: 'Fast/Flex multipliers must be greater than 0',
+ inputMultiplier: 'Input Mult.',
+ outputMultiplier: 'Output Mult.',
+ cacheWriteMultiplier: 'Cache Write Mult.',
+ cacheReadMultiplier: 'Cache Read Mult.',
intervals: 'Context Intervals (optional)',
timePricing: 'Time-based pricing (optional)',
timezone: 'Time zone',
+ timePricingDayScope: 'Effective days',
+ timePricingEveryDay: 'Every day (Monday-Sunday, including weekends)',
+ timePricingWeekdaysOnly: 'Weekdays only (Monday-Friday)',
addTimePeriod: 'Add period',
startTime: 'Start time',
endTime: 'End time',
diff --git a/frontend/src/i18n/locales/en/admin/index.ts b/frontend/src/i18n/locales/en/admin/index.ts
index 224ab94b39..b86114e058 100644
--- a/frontend/src/i18n/locales/en/admin/index.ts
+++ b/frontend/src/i18n/locales/en/admin/index.ts
@@ -6,6 +6,7 @@ import ops from './ops'
import settings from './settings'
import audit from './audit'
import promptAudit from './promptAudit'
+import plugins from './plugins'
export default {
...overview,
@@ -16,4 +17,5 @@ export default {
...settings,
...audit,
...promptAudit,
+ ...plugins,
}
diff --git a/frontend/src/i18n/locales/en/admin/ops.ts b/frontend/src/i18n/locales/en/admin/ops.ts
index 8210b789aa..4bb48c64da 100644
--- a/frontend/src/i18n/locales/en/admin/ops.ts
+++ b/frontend/src/i18n/locales/en/admin/ops.ts
@@ -307,6 +307,7 @@ export default {
title: 'Error Detail',
titleWithId: 'Error #{id}',
noErrorSelected: 'No error selected.',
+ backToList: 'Back to List',
resolution: 'Resolved:',
failedToUpdateResolvedStatus: 'Failed to update resolved status',
classificationKeys: {
@@ -339,7 +340,16 @@ export default {
time: 'Time',
phase: 'Phase',
status: 'Status',
+ upstreamStatus: 'Upstream Status',
message: 'Message',
+ rootCause: 'Root Cause',
+ diagnosticPayloads: 'Diagnostic Payloads',
+ payloads: {
+ client: 'Client Response',
+ upstream_message: 'Upstream Message',
+ upstream_detail: 'Upstream Detail',
+ upstream_events: 'Upstream Events'
+ },
basicInfo: 'Basic Info',
platform: 'Platform',
model: 'Model',
diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts
index d8ea00c62d..e91233132d 100644
--- a/frontend/src/i18n/locales/en/admin/overview.ts
+++ b/frontend/src/i18n/locales/en/admin/overview.ts
@@ -513,6 +513,8 @@ export default {
statusLabel: 'Status',
selectStatus: 'Select status',
rpmLimit: 'Requests Per Minute (RPM)',
+ concurrencyPlaceholder: '0 = unlimited',
+ concurrencyHint: 'Max concurrent requests for this user; 0 = unlimited.',
rpmLimitPlaceholder: '0 = unlimited',
rpmLimitHint: 'Max requests per minute for this user; 0 = unlimited. Acts as a fallback only when the group has no rpm_limit set.'
},
@@ -577,7 +579,7 @@ export default {
failedToToggle: 'Failed to update user status',
failedToLoadApiKeys: 'Failed to load user API keys',
emailRequired: 'Please enter email',
- concurrencyMin: 'Concurrency must be at least 1',
+ concurrencyNonNegative: 'Concurrency cannot be negative; 0 = unlimited',
amountRequired: 'Please enter a valid amount',
insufficientBalance: 'Insufficient balance',
adjustBalance: 'Adjust Balance',
@@ -610,6 +612,9 @@ export default {
groupConfigHint: 'Configure custom rate multipliers for user {email} (overrides group defaults)',
exclusiveGroups: 'Exclusive Groups',
publicGroups: 'Public Groups (Default Available)',
+ restrictPublicGroups: 'Restrict accessible public groups',
+ restrictPublicGroupsHint: 'When on, this user may only use the public groups checked below. When off, every public group stays available.',
+ publicGroupsRestricted: 'Public Groups (Restricted)',
defaultRate: 'Default Rate',
customRate: 'Custom Rate',
useDefaultRate: 'Use Default',
@@ -1011,7 +1016,7 @@ export default {
title: 'Per-model group pricing',
description: 'Overrides channel and built-in prices for matching models. Long-context tiers come from official presets — do not enter custom intervals. Use per-request tiers such as realtime, tts, and stt for audio.',
longContext: 'Enable long-context tier pricing',
- longContextHint: 'When checked, official/preset long-context tiers apply. When unchecked, token models stay on the first-tier base rate.',
+ longContextHint: 'When checked, channel intervals or official preset tiers apply. Otherwise the first tier is used unless the account explicitly enables long-context billing.',
add: 'Add model price'
},
voicePricing: {
diff --git a/frontend/src/i18n/locales/en/admin/plugins.ts b/frontend/src/i18n/locales/en/admin/plugins.ts
new file mode 100644
index 0000000000..1d68ba6dc6
--- /dev/null
+++ b/frontend/src/i18n/locales/en/admin/plugins.ts
@@ -0,0 +1,50 @@
+export default {
+ plugins: {
+ title: 'Plugin Management',
+ description: 'Install and manage isolated OAuth outbound transport plugins. API Key flows are unchanged.',
+ upload: 'Install plugin',
+ uploadHint: 'Only .s2plugin packages are accepted; trusted publisher signatures are required by default.',
+ runtimeNotice: 'Plugin installation, enable/disable, and configuration are handled dynamically by the Sub2API host and normally do not require a host restart. Restart only when the host version or host configuration changes according to your deployment process.',
+ menuNotice: 'The Plugin Management switch in System Settings controls only sidebar visibility; it does not stop loaded or running plugins.',
+ empty: 'No plugins installed',
+ emptyHint: 'Select a local .s2plugin package. Sub2API never downloads third-party plugins automatically.',
+ configure: 'Configure',
+ enable: 'Enable',
+ disable: 'Disable',
+ test: 'Test',
+ uninstall: 'Uninstall',
+ rollout: 'OAuth traffic percentage',
+ compatibility: 'Version compatibility',
+ currentVersion: 'Current Sub2API',
+ requiredVersion: 'Required range',
+ recommendedVersion: 'Recommended version',
+ signature: 'Package signature',
+ trusted: 'Verified',
+ unsigned: 'Unsigned',
+ runtime: 'Runtime',
+ healthy: 'Healthy',
+ unhealthy: 'Not running',
+ compatible: 'Compatible',
+ untested: 'Untested version',
+ incompatible: 'Incompatible',
+ enabled: 'Enabled',
+ disabled: 'Disabled',
+ error: 'Error',
+ starting: 'Starting',
+ configTitle: '{name} configuration',
+ loadingUI: 'Loading plugin configuration UI...',
+ uiUnavailable: 'Unable to load the plugin configuration UI',
+ uploadSuccess: 'Plugin installed and kept disabled',
+ enableSuccess: 'Plugin enabled',
+ disableSuccess: 'Plugin disabled',
+ uninstallSuccess: 'Plugin uninstalled',
+ testSuccess: 'Plugin test passed',
+ confirmDisable: 'Disable this plugin? New OAuth requests immediately return to the built-in Sub2API path.',
+ confirmUninstall: 'Uninstall this plugin? It must be disabled first. Installed files and configuration will be removed.',
+ confirmUntested: 'This plugin is compatible but has not declared the current Sub2API version as tested. Enable it anyway?',
+ fileRequired: 'Select a .s2plugin file',
+ bridgeRejected: 'Plugin UI message validation failed',
+ onlyOpenAI: 'Initial capability: OpenAI OAuth outbound transport only',
+ noAccountCoupling: 'The scope is platform and account type. Account records are not changed and no per-account toggle is required.'
+ }
+}
diff --git a/frontend/src/i18n/locales/en/admin/settings.ts b/frontend/src/i18n/locales/en/admin/settings.ts
index 2d6d344097..4c23f239ae 100644
--- a/frontend/src/i18n/locales/en/admin/settings.ts
+++ b/frontend/src/i18n/locales/en/admin/settings.ts
@@ -52,6 +52,12 @@ export default {
priceDescription: 'Pricing notes (Markdown)',
priceDescriptionHint: 'Rendered at the top of the plaza page. Use it for billing rules, exchange rates, promotions, etc.',
},
+ pluginManagement: {
+ title: 'Plugin Management',
+ description: 'Controls whether the plugin management entry appears in the admin sidebar. This switch does not control plugin runtime state.',
+ enabled: 'Show Plugin Management',
+ enabledHint: 'Turning this off only hides the sidebar entry; loaded or running plugins are not stopped.',
+ },
riskControl: {
title: 'Risk Control',
description: 'Enable the content moderation menu and gateway audit entry point. Disabled by default.',
diff --git a/frontend/src/i18n/locales/en/common.ts b/frontend/src/i18n/locales/en/common.ts
index a0190ca0b1..d0afbee551 100644
--- a/frontend/src/i18n/locales/en/common.ts
+++ b/frontend/src/i18n/locales/en/common.ts
@@ -176,6 +176,7 @@ export default {
modelPlaza: 'Model Plaza',
subscriptions: 'Subscriptions',
accounts: 'Accounts',
+ plugins: 'Plugins',
proxies: 'Proxies',
redeemCodes: 'Redeem Codes',
ops: 'Ops',
diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts
index 9f49522a84..12169ebbe9 100644
--- a/frontend/src/i18n/locales/en/dashboard.ts
+++ b/frontend/src/i18n/locales/en/dashboard.ts
@@ -188,6 +188,32 @@ export default {
codexNoteWindows:
'Set $env:SUB2API_API_KEY, save config.toml under %USERPROFILE%\\.codex. Prefer env_key auth; do not commit secrets.',
},
+ deepseek: {
+ description: 'Configure Claude Code, Codex, or OpenCode through the current DeepSeek group.',
+ codexDescription: 'Configure Codex with API key authentication through the current DeepSeek group.',
+ codexConfigTomlHint: 'Download the model catalog below, save both files under the Codex config directory, and restart Codex.',
+ codexNote: 'Export SUB2API_API_KEY before starting Codex. The downloaded catalog contains model metadata only, not your API key.',
+ },
+ composite: {
+ description: 'Configure supported clients through the current Composite routing group.',
+ codexDescription: 'Configure Codex with API key authentication and the complete model catalog for this Composite group.',
+ codexConfigTomlHint: 'Download the model catalog below, save both files under the Codex config directory, and restart Codex.',
+ codexNote: 'Export SUB2API_API_KEY before starting Codex. Model requests are routed by the selected catalog slug.',
+ },
+ routedCodex: {
+ description: 'Configure Codex with the complete model catalog for the current routed group.',
+ configTomlHint: 'Download the model catalog below, save both files under the Codex config directory, and restart Codex.',
+ note: 'Export SUB2API_API_KEY before starting Codex. The downloaded catalog contains model metadata only, not your API key.',
+ },
+ codexModelCatalog: {
+ title: 'Codex model catalog',
+ description: 'Fetch with this API key, then save the catalog at the path referenced by config.toml.',
+ fetch: 'Fetch catalog',
+ retry: 'Retry',
+ download: 'Download catalog',
+ modelsCount: '{count} models ready to download',
+ errorDescription: 'The catalog could not be fetched with this API key.',
+ },
opencode: {
title: 'OpenCode Example',
subtitle: 'opencode.json',
@@ -309,6 +335,7 @@ export default {
modelVariant: 'Possible version variant',
modelMismatch: 'Different model',
reasoningEffort: 'Reasoning Effort',
+ requestedReasoningEffort: 'Requested reasoning effort',
endpoint: 'Endpoint',
endpointDistribution: 'Endpoint Distribution',
inbound: 'Inbound',
@@ -589,7 +616,8 @@ export default {
detail: {
noModels: 'No models configured for this group',
noPricing: 'Pricing not configured',
- peakNote: 'Peak hours {window}: billing rate ×{multiplier}'
+ peakNote: 'Peak hours {window}: billing rate ×{multiplier}',
+ longContextDisabledNote: 'Long-context tier pricing is disabled for this group: requests above the threshold are billed at the base tier; official tiers are for reference only'
},
table: {
model: 'Model',
@@ -598,6 +626,18 @@ export default {
cache: 'Cache',
cacheWrite: 'Write',
cacheRead: 'Read',
+ cacheWriteShort: 'W',
+ cacheReadShort: 'R',
+ tierHint: 'The whole request is billed at the tier matching its total context (input + cache write + cache read)',
+ tierHintMarginal: 'Only the portion above the threshold is billed at this tier; output is unaffected',
+ marginalBadge: 'excess-only tiers',
+ timePricingRowHint: 'Requests made within this period ({timezone} time) are billed at the prices in this row',
+ timePricingRowHintWeekdays:
+ 'On weekdays (Mon–Fri) only, requests made within this period ({timezone} time) are billed at the prices in this row; weekends use the standard prices',
+ timePricingRowHintPeak:
+ '; prices in this row exclude the peak-hour rate — where this period overlaps the peak hours {window}, the overlapping portion is additionally multiplied by ×{multiplier}',
+ timePricingWeekdays: 'Weekdays',
+ timePricingRateHint: 'Effective rate {rate} × period multiplier {multiplier}',
paidPrice: 'Your Price (Discounted)',
officialPrice: 'Official Price',
rate: 'Rate',
diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts
index 0d1883da06..c277eb7c2f 100644
--- a/frontend/src/i18n/locales/zh/admin/accounts.ts
+++ b/frontend/src/i18n/locales/zh/admin/accounts.ts
@@ -321,6 +321,10 @@ export default {
},
apiProtocol: {
title: 'API 协议',
+ adaptive: '自适应',
+ adaptiveDesc: '按入站协议优先使用供应商原生端点,仅在没有对应端点时转换。',
+ endpoints: '协议端点',
+ responsesFallbackDesc: '该供应商没有原生 Responses 端点,Responses 请求将转换为 Chat Completions。',
chatCompletions: 'Chat Completions',
chatCompletionsDesc: '标准 OpenAI 兼容端点,其他格式请求将被转换。',
anthropic: 'Anthropic',
@@ -331,7 +335,9 @@ export default {
balance: '余额 --',
window5h: '5 小时窗口',
windowWeekly: '每周窗口',
+ probe: '查询',
probeTooltip: '请求供应商额度端点,查询 5 小时 / 每周滚动窗口用量',
+ balanceProbeTooltip: '请求供应商余额端点,查询账户余额',
balanceLow: '余额不足',
noBalanceEndpoint: '该平台暂无余额查询接口',
resetSoon: '即将重置',
@@ -480,6 +486,14 @@ export default {
resetAccountRecoveryFailed: '窗口已重置,但账号状态恢复失败,请手动恢复账号状态。',
resetAccountRefreshFailed: '窗口、账号状态和重置次数缓存已更新,但无法加载最新账号显示。',
refreshCachePersistFailed: '已显示实时次数,但到期明细获取失败,仍保留原有缓存明细。',
+ autoStatus: {
+ checking: '检测中',
+ available: '卡可用',
+ resetting: '自动重置中',
+ success: '自动重置成功',
+ noCredit: '无卡',
+ failed: '自动重置失败'
+ },
confirmTitle: '确认重置周限',
confirmMessage: '将消耗 1 次重置次数立即恢复当前窗口,剩余 {count} 次。此操作不可撤销,确定继续吗?'
},
@@ -805,6 +819,7 @@ export default {
syncUpstreamModelsEmpty: '上游没有返回可同步的模型',
syncUpstreamModelsFailed: '同步上游模型失败',
syncUpstreamModelsError: '同步上游模型失败:{message}',
+ syncUpstreamModelsMetadataIncomplete: '模型 ID 已同步,但能力元数据不完整,能力信息未更新。',
clearAllModels: '清除所有模型',
customModelName: '自定义模型名称',
enterCustomModelName: '输入自定义模型名称',
@@ -879,6 +894,14 @@ export default {
autoPause5hDisabled: '禁用 5h 自动暂停',
autoPause7dDisabled: '禁用 7d 自动暂停',
autoPauseDisabledHint: '开启后该账号永不进入自动暂停(即使全局默认阈值已配置)。',
+ autoResetCredit: {
+ title: '自动使用重置卡',
+ hint: '仅在实际用量达到阈值时使用最早到期的可用卡;默认关闭。无卡或失败时账号保持暂停。',
+ threshold5h: '5h 自动用卡阈值(%)',
+ threshold7d: '7d 自动用卡阈值(%)',
+ thresholdHint: '两个窗口独立判断,任一达到自身阈值即触发。可填写 0.1–100,默认均为 100。',
+ thresholdInvalid: '自动使用重置卡阈值必须在 0.1% 到 100% 之间。'
+ },
// Quota control (Anthropic OAuth/SetupToken only)
quotaControl: {
title: '配额控制',
diff --git a/frontend/src/i18n/locales/zh/admin/channels.ts b/frontend/src/i18n/locales/zh/admin/channels.ts
index 60e154858b..12272becd1 100644
--- a/frontend/src/i18n/locales/zh/admin/channels.ts
+++ b/frontend/src/i18n/locales/zh/admin/channels.ts
@@ -70,6 +70,7 @@ export default {
maxPositive: '区间 #{index}:最大 token 数({value})必须大于 0',
maxGreaterThanMin: '区间 #{index}:最大 token 数({max})必须大于最小 token 数({min})',
negativePrice: '区间 #{index}:{field}不能为负数',
+ multiplierPositive: '区间 #{index}:{field}必须大于 0',
unboundedLast: '区间 #{index}:无上限区间(最大 token 数为空)必须放在最后',
overlap: '区间 #{previousIndex} 和 #{currentIndex} 重叠:前一个上界({previousMax})大于当前下界({currentMin})',
price: {
@@ -128,9 +129,20 @@ export default {
imageTokenPrice: '图片输出',
imageOutputPrice: '图片输出价格',
pricePlaceholder: '默认',
+ fastMultiplier: 'Fast 倍率',
+ flexMultiplier: 'Flex 倍率',
+ multiplierPlaceholder: '未配置',
+ multiplierPositive: 'Fast/Flex 倍率必须大于 0',
+ inputMultiplier: '输入倍率',
+ outputMultiplier: '输出倍率',
+ cacheWriteMultiplier: '缓存写倍率',
+ cacheReadMultiplier: '缓存读倍率',
intervals: '上下文区间定价(可选)',
timePricing: '时间段定价(可选)',
timezone: '时区',
+ timePricingDayScope: '生效日',
+ timePricingEveryDay: '每日生效(周一至周日,含周末)',
+ timePricingWeekdaysOnly: '仅工作日生效(周一至周五)',
addTimePeriod: '添加时间段',
startTime: '开始时间',
endTime: '结束时间',
diff --git a/frontend/src/i18n/locales/zh/admin/index.ts b/frontend/src/i18n/locales/zh/admin/index.ts
index 224ab94b39..b86114e058 100644
--- a/frontend/src/i18n/locales/zh/admin/index.ts
+++ b/frontend/src/i18n/locales/zh/admin/index.ts
@@ -6,6 +6,7 @@ import ops from './ops'
import settings from './settings'
import audit from './audit'
import promptAudit from './promptAudit'
+import plugins from './plugins'
export default {
...overview,
@@ -16,4 +17,5 @@ export default {
...settings,
...audit,
...promptAudit,
+ ...plugins,
}
diff --git a/frontend/src/i18n/locales/zh/admin/ops.ts b/frontend/src/i18n/locales/zh/admin/ops.ts
index 3c8e9b0446..3e568e1dd7 100644
--- a/frontend/src/i18n/locales/zh/admin/ops.ts
+++ b/frontend/src/i18n/locales/zh/admin/ops.ts
@@ -307,6 +307,7 @@ export default {
title: '错误详情',
titleWithId: '错误 #{id}',
noErrorSelected: '未选择错误。',
+ backToList: '返回列表',
resolution: '已解决:',
failedToUpdateResolvedStatus: '更新解决状态失败',
classificationKeys: {
@@ -339,7 +340,16 @@ export default {
time: '时间',
phase: '阶段',
status: '状态码',
+ upstreamStatus: '上游状态码',
message: '消息',
+ rootCause: '根因',
+ diagnosticPayloads: '诊断载荷',
+ payloads: {
+ client: '客户端响应',
+ upstream_message: '上游消息',
+ upstream_detail: '上游详情',
+ upstream_events: '上游事件'
+ },
basicInfo: '基本信息',
platform: '平台',
model: '模型',
diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts
index fdfbc8fdac..cbc930fa10 100644
--- a/frontend/src/i18n/locales/zh/admin/overview.ts
+++ b/frontend/src/i18n/locales/zh/admin/overview.ts
@@ -578,6 +578,8 @@ export default {
statusLabel: '状态',
selectStatus: '选择状态',
rpmLimit: '每分钟请求数 (RPM)',
+ concurrencyPlaceholder: '0 表示不限制',
+ concurrencyHint: '该用户的最大并发请求数,0 = 不限制',
rpmLimitPlaceholder: '0 表示不限制',
rpmLimitHint: '该用户每分钟最大请求数,0 = 不限制;仅在所用分组未设置 rpm_limit 时作为兜底生效'
},
@@ -598,7 +600,7 @@ export default {
failedToSave: '保存用户失败',
failedToAdjust: '调整失败',
emailRequired: '请输入邮箱',
- concurrencyMin: '并发数不能小于1',
+ concurrencyNonNegative: '并发数不能为负数,0 表示不限制',
amountRequired: '请输入有效金额',
insufficientBalance: '余额不足',
setAllowedGroups: '设置允许分组',
@@ -614,6 +616,9 @@ export default {
groupConfigHint: '为用户 {email} 配置专属分组倍率(覆盖分组默认倍率)',
exclusiveGroups: '专属分组',
publicGroups: '公开分组(默认可用)',
+ restrictPublicGroups: '限制可访问的公开分组',
+ restrictPublicGroupsHint: '开启后,该用户仅能使用下方勾选的公开分组;关闭则可使用全部公开分组。',
+ publicGroupsRestricted: '公开分组(已限制)',
defaultRate: '默认倍率',
customRate: '专属倍率',
useDefaultRate: '使用默认',
@@ -1008,7 +1013,7 @@ export default {
title: '分组逐模型定价',
description: '匹配模型后覆盖渠道和内置价格。长上下文阶梯沿用官方/预设价卡,无需再手填区间。音频可用按次层级配置 realtime、tts、stt。',
longContext: '启用长上下文阶梯定价',
- longContextHint: '勾选后按官方/预设阶梯计费;关闭则始终按第一档基础价。',
+ longContextHint: '勾选后按渠道区间或官方预设阶梯计费;关闭后默认按第一档,账号显式开启时除外。',
add: '添加模型价格'
},
voicePricing: {
diff --git a/frontend/src/i18n/locales/zh/admin/plugins.ts b/frontend/src/i18n/locales/zh/admin/plugins.ts
new file mode 100644
index 0000000000..8b279bd8f3
--- /dev/null
+++ b/frontend/src/i18n/locales/zh/admin/plugins.ts
@@ -0,0 +1,50 @@
+export default {
+ plugins: {
+ title: '插件管理',
+ description: '安装和管理独立运行的 OAuth 出站传输插件。API Key 流程不受影响。',
+ upload: '安装插件',
+ uploadHint: '仅接受 .s2plugin 包;默认要求可信发布者签名。',
+ runtimeNotice: '插件安装、启用、停用和配置由 Sub2API 宿主动态处理,通常不需要重启宿主实例。只有宿主版本或宿主配置本身变化时,才按部署方式执行重启。',
+ menuNotice: '系统设置中的“插件管理”开关仅控制侧边栏菜单显示,不会停止已经加载或正在运行的插件。',
+ empty: '尚未安装插件',
+ emptyHint: '选择本机的 .s2plugin 文件进行安装。Sub2API 不会自动下载第三方插件。',
+ configure: '配置',
+ enable: '启用',
+ disable: '停用',
+ test: '测试',
+ uninstall: '卸载',
+ rollout: 'OAuth 流量比例',
+ compatibility: '版本兼容性',
+ currentVersion: '当前 Sub2API',
+ requiredVersion: '要求范围',
+ recommendedVersion: '建议版本',
+ signature: '包签名',
+ trusted: '已验证',
+ unsigned: '未签名',
+ runtime: '运行状态',
+ healthy: '运行正常',
+ unhealthy: '未运行',
+ compatible: '兼容',
+ untested: '未验证版本',
+ incompatible: '不兼容',
+ enabled: '已启用',
+ disabled: '已停用',
+ error: '异常',
+ starting: '启动中',
+ configTitle: '{name} 配置',
+ loadingUI: '正在加载插件配置界面...',
+ uiUnavailable: '无法加载插件配置界面',
+ uploadSuccess: '插件安装成功,当前保持停用',
+ enableSuccess: '插件已启用',
+ disableSuccess: '插件已停用',
+ uninstallSuccess: '插件已卸载',
+ testSuccess: '插件测试通过',
+ confirmDisable: '确定停用此插件吗?新的 OAuth 请求会立即恢复 Sub2API 原有路径。',
+ confirmUninstall: '确定卸载此插件吗?插件必须先停用。此操作会移除安装文件和配置。',
+ confirmUntested: '该插件兼容当前版本范围,但未声明已测试当前 Sub2API 版本。确定承担风险并启用吗?',
+ fileRequired: '请选择 .s2plugin 文件',
+ bridgeRejected: '插件 UI 消息校验失败',
+ onlyOpenAI: '初期能力:仅 OpenAI OAuth 出站传输',
+ noAccountCoupling: '作用域为平台与账号类型,不修改账号数据,也不需要在账号页逐个开启。'
+ }
+}
diff --git a/frontend/src/i18n/locales/zh/admin/settings.ts b/frontend/src/i18n/locales/zh/admin/settings.ts
index f315480666..fb5371e8c5 100644
--- a/frontend/src/i18n/locales/zh/admin/settings.ts
+++ b/frontend/src/i18n/locales/zh/admin/settings.ts
@@ -52,6 +52,12 @@ export default {
priceDescription: '价格说明(Markdown)',
priceDescriptionHint: '展示在模型广场页面顶部,可用于说明计费规则、汇率、优惠活动等。',
},
+ pluginManagement: {
+ title: '插件管理',
+ description: '控制管理员侧边栏是否显示插件管理入口。此开关不控制插件运行状态。',
+ enabled: '显示插件管理菜单',
+ enabledHint: '关闭后仅隐藏侧边栏菜单;已加载或正在运行的插件不会因此停止。',
+ },
riskControl: {
title: '风控中心',
description: '启用内容审计菜单和全端点请求审核入口。默认关闭。',
diff --git a/frontend/src/i18n/locales/zh/common.ts b/frontend/src/i18n/locales/zh/common.ts
index 04dd321287..c5b2c4002e 100644
--- a/frontend/src/i18n/locales/zh/common.ts
+++ b/frontend/src/i18n/locales/zh/common.ts
@@ -176,6 +176,7 @@ export default {
modelPlaza: '模型广场',
subscriptions: '订阅管理',
accounts: '账号管理',
+ plugins: '插件管理',
proxies: 'IP管理',
redeemCodes: '兑换码',
ops: '运维监控',
diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts
index bcd31fa1f5..7aad26eaa0 100644
--- a/frontend/src/i18n/locales/zh/dashboard.ts
+++ b/frontend/src/i18n/locales/zh/dashboard.ts
@@ -192,6 +192,32 @@ export default {
codexNoteWindows:
'设置 $env:SUB2API_API_KEY,将 config.toml 保存到 %USERPROFILE%\\.codex。优先 env_key,勿提交密钥。'
},
+ deepseek: {
+ description: '通过当前 DeepSeek 分组配置 Claude Code、Codex 或 OpenCode。',
+ codexDescription: '使用 API Key 配置 Codex,并通过当前 DeepSeek 分组发送请求。',
+ codexConfigTomlHint: '下载下方模型目录,将两个文件保存到 Codex 配置目录后重启 Codex。',
+ codexNote: '启动 Codex 前先导出 SUB2API_API_KEY。下载的目录只包含模型元数据,不包含 API Key。'
+ },
+ composite: {
+ description: '通过当前 Composite 路由分组配置受支持的客户端。',
+ codexDescription: '使用 API Key 和当前 Composite 分组的完整模型目录配置 Codex。',
+ codexConfigTomlHint: '下载下方模型目录,将两个文件保存到 Codex 配置目录后重启 Codex。',
+ codexNote: '启动 Codex 前先导出 SUB2API_API_KEY;分组会根据目录中选中的模型路由请求。'
+ },
+ routedCodex: {
+ description: '使用当前路由分组的完整模型目录配置 Codex。',
+ configTomlHint: '下载下方模型目录,将两个文件保存到 Codex 配置目录后重启 Codex。',
+ note: '启动 Codex 前先导出 SUB2API_API_KEY。下载的目录只包含模型元数据,不包含 API Key。'
+ },
+ codexModelCatalog: {
+ title: 'Codex 模型目录',
+ description: '使用当前 API Key 获取目录,并保存到 config.toml 引用的路径。',
+ fetch: '获取目录',
+ retry: '重试',
+ download: '下载目录',
+ modelsCount: '已获取 {count} 个模型',
+ errorDescription: '无法使用当前 API Key 获取模型目录。'
+ },
opencode: {
title: 'OpenCode 配置示例',
subtitle: 'opencode.json',
@@ -314,6 +340,7 @@ export default {
modelVariant: '疑似版本变体',
modelMismatch: '模型不一致',
reasoningEffort: '推理强度',
+ requestedReasoningEffort: '请求推理强度',
endpoint: '端点',
endpointDistribution: '端点分布',
inbound: '入站',
@@ -594,7 +621,8 @@ export default {
detail: {
noModels: '该分组暂未配置模型',
noPricing: '未配置定价',
- peakNote: '高峰时段 {window} 计费倍率 ×{multiplier}'
+ peakNote: '高峰时段 {window} 计费倍率 ×{multiplier}',
+ longContextDisabledNote: '该分组未启用长上下文阶梯计费,超阈值请求仍按基础档计费,官方阶梯仅供参考'
},
table: {
model: '模型',
@@ -603,6 +631,17 @@ export default {
cache: '缓存',
cacheWrite: '写入',
cacheRead: '读取',
+ cacheWriteShort: '写',
+ cacheReadShort: '读',
+ tierHint: '按单次请求的总上下文(输入 + 缓存写入 + 缓存读取)所在档位对整单计价',
+ tierHintMarginal: '仅超过阈值的部分按该档计价,输出不加价',
+ marginalBadge: '超出部分计价',
+ timePricingRowHint: '按 {timezone} 时间,在该时段内发起的请求按本行价格计费',
+ timePricingRowHintWeekdays:
+ '按 {timezone} 时间,仅工作日(周一至周五)在该时段内发起的请求按本行价格计费,周末全天按标准价',
+ timePricingRowHintPeak: ';本行价格未含高峰倍率,与高峰时段 {window} 重叠的部分实付再乘 ×{multiplier}',
+ timePricingWeekdays: '工作日',
+ timePricingRateHint: '生效倍率 {rate} × 时段倍率 {multiplier}',
paidPrice: '实付价格(折后)',
officialPrice: '官方价格',
rate: '折扣倍率',
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 1221a53f6d..1191944f52 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -524,6 +524,18 @@ const routes: RouteRecordRaw[] = [
descriptionKey: 'admin.accounts.description'
}
},
+ {
+ path: '/admin/plugins',
+ name: 'AdminPlugins',
+ component: () => import('@/views/admin/PluginsView.vue'),
+ meta: {
+ requiresAuth: true,
+ requiresAdmin: true,
+ title: 'Plugin Management',
+ titleKey: 'admin.plugins.title',
+ descriptionKey: 'admin.plugins.description'
+ }
+ },
{
path: '/admin/announcements',
name: 'AdminAnnouncements',
diff --git a/frontend/src/stores/__tests__/app.spec.ts b/frontend/src/stores/__tests__/app.spec.ts
index d5cee36065..d2c55d13ef 100644
--- a/frontend/src/stores/__tests__/app.spec.ts
+++ b/frontend/src/stores/__tests__/app.spec.ts
@@ -57,6 +57,7 @@ function createPublicSettings(overrides: Partial = {}): PublicSe
available_channels_enabled: false,
model_plaza_enabled: false,
model_plaza_require_auth: false,
+ plugin_management_enabled: false,
service_quota_enabled: false,
affiliate_enabled: false,
...overrides,
diff --git a/frontend/src/stores/app.ts b/frontend/src/stores/app.ts
index e2d614ec3d..496e17d270 100644
--- a/frontend/src/stores/app.ts
+++ b/frontend/src/stores/app.ts
@@ -373,6 +373,7 @@ export const useAppStore = defineStore('app', () => {
available_channels_enabled: false,
model_plaza_enabled: false,
model_plaza_require_auth: false,
+ plugin_management_enabled: false,
risk_control_enabled: false,
service_quota_enabled: false,
affiliate_enabled: false,
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index eaa585f15c..bfcffff433 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -107,6 +107,9 @@ export interface AdminUser extends User {
last_used_at?: string | null
// 用户专属分组倍率配置 (group_id -> rate_multiplier)
group_rates?: Record
+ // 为 true 时该用户仅可使用 allowed_groups 中列出的公开分组。
+ // 管理侧权限开关,普通用户接口不返回。
+ restrict_public_groups?: boolean
// 当前并发数(仅管理员列表接口返回)
current_concurrency?: number
}
@@ -273,6 +276,7 @@ export interface PublicSettings {
available_channels_enabled: boolean
model_plaza_enabled: boolean
model_plaza_require_auth: boolean
+ plugin_management_enabled: boolean
service_quota_enabled: boolean
affiliate_enabled: boolean
allow_user_view_error_requests?: boolean
@@ -1133,6 +1137,17 @@ export interface Account {
available_count?: number
credits?: { expires_at?: string }[]
}
+ auto_reset_credit_enabled?: boolean
+ auto_reset_credit_5h_threshold?: number
+ auto_reset_credit_7d_threshold?: number
+ codex_auto_reset_credit_state?: {
+ status?: 'checking' | 'available' | 'resetting' | 'success' | 'no_credit' | 'failed'
+ trigger_window?: string
+ available_count?: number
+ checked_at?: string
+ last_result_at?: string
+ error_code?: string
+ }
} & Record)
proxy_id: number | null
proxy_fallback_origin_id?: number | null
@@ -1693,6 +1708,7 @@ export interface UsageLogAccountSummary {
export interface AdminUsageLog extends UsageLog {
upstream_model?: string | null
+ upstream_reasoning_effort?: string | null
upstream_response_model?: string | null
upstream_model_mismatch?: boolean | null
model_mapping_chain?: string | null
@@ -1961,6 +1977,7 @@ export interface UpdateUserRequest {
rpm_limit?: number
status?: 'active' | 'disabled'
allowed_groups?: number[] | null
+ restrict_public_groups?: boolean
// 用户专属分组倍率配置 (group_id -> rate_multiplier | null)
// null 表示删除该分组的专属倍率
group_rates?: Record
diff --git a/frontend/src/utils/__tests__/codexCatalogConfig.spec.ts b/frontend/src/utils/__tests__/codexCatalogConfig.spec.ts
new file mode 100644
index 0000000000..ff78bb1b0a
--- /dev/null
+++ b/frontend/src/utils/__tests__/codexCatalogConfig.spec.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest'
+import {
+ findCodexCatalogModel,
+ formatCodexReasoningEffortTomlLine,
+ parseCodexCatalogModels,
+ selectCodexConfigReasoningEffort
+} from '@/utils/codexCatalogConfig'
+
+describe('codexCatalogConfig', () => {
+ it('parses catalog slugs and finds a model by id', () => {
+ const content = JSON.stringify({
+ models: [
+ { slug: 'glm-5.3', default_reasoning_level: 'none', supported_reasoning_levels: [{ effort: 'none' }] },
+ { slug: ' ', supported_reasoning_levels: [] }
+ ]
+ })
+ expect(parseCodexCatalogModels(content).map((model) => model.slug)).toEqual(['glm-5.3'])
+ expect(findCodexCatalogModel(content, 'glm-5.3')?.slug).toBe('glm-5.3')
+ expect(findCodexCatalogModel(content, 'missing')).toBeUndefined()
+ })
+
+ it('omits effort when the descriptor only advertises none', () => {
+ expect(selectCodexConfigReasoningEffort({
+ slug: 'glm-5.3',
+ default_reasoning_level: 'none',
+ supported_reasoning_levels: [{ effort: 'none' }]
+ })).toBeNull()
+ expect(formatCodexReasoningEffortTomlLine(null)).toBe('')
+ })
+
+ it('does not emit an effort absent from supported_reasoning_levels', () => {
+ expect(selectCodexConfigReasoningEffort({
+ slug: 'glm-5.3',
+ default_reasoning_level: 'xhigh',
+ supported_reasoning_levels: [{ effort: 'none' }]
+ })).toBeNull()
+ })
+
+ it('uses the catalog default when it is a supported non-none effort', () => {
+ expect(selectCodexConfigReasoningEffort({
+ slug: 'gpt-5.5',
+ default_reasoning_level: 'medium',
+ supported_reasoning_levels: [
+ { effort: 'low' },
+ { effort: 'medium' },
+ { effort: 'high' },
+ { effort: 'xhigh' }
+ ]
+ })).toBe('medium')
+ expect(formatCodexReasoningEffortTomlLine('medium')).toBe('model_reasoning_effort = "medium"\n')
+ })
+
+ it('falls back to the first usable supported effort when default is missing', () => {
+ expect(selectCodexConfigReasoningEffort({
+ slug: 'custom',
+ supported_reasoning_levels: [{ effort: 'none' }, { effort: 'high' }]
+ })).toBe('high')
+ })
+})
diff --git a/frontend/src/utils/__tests__/formatReasoningEffort.spec.ts b/frontend/src/utils/__tests__/formatReasoningEffort.spec.ts
new file mode 100644
index 0000000000..aaac5d156c
--- /dev/null
+++ b/frontend/src/utils/__tests__/formatReasoningEffort.spec.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest'
+import {
+ formatReasoningEffort,
+ formatReasoningEffortMapping,
+ reasoningEffortValuesEqual,
+} from '@/utils/format'
+
+describe('formatReasoningEffort', () => {
+ it('title-cases known effort values', () => {
+ expect(formatReasoningEffort('max')).toBe('Max')
+ expect(formatReasoningEffort('x-high')).toBe('XHigh')
+ expect(formatReasoningEffort(null)).toBe('-')
+ })
+})
+
+describe('formatReasoningEffortMapping', () => {
+ it('shows a single value when requested and forwarded match', () => {
+ expect(formatReasoningEffortMapping('max', 'max')).toBe('Max')
+ expect(formatReasoningEffortMapping(null, 'high')).toBe('High')
+ })
+
+ it('shows requested then forwarded when mapping changed the value', () => {
+ expect(formatReasoningEffortMapping('max', 'xhigh')).toBe('Max → XHigh')
+ expect(formatReasoningEffortMapping('high', 'medium')).toBe('High → Medium')
+ })
+})
+
+describe('reasoningEffortValuesEqual', () => {
+ it('treats x-high aliases as equal', () => {
+ expect(reasoningEffortValuesEqual('x-high', 'xhigh')).toBe(true)
+ expect(reasoningEffortValuesEqual('max', 'xhigh')).toBe(false)
+ })
+})
diff --git a/frontend/src/utils/codexCatalogConfig.ts b/frontend/src/utils/codexCatalogConfig.ts
new file mode 100644
index 0000000000..18e07dc991
--- /dev/null
+++ b/frontend/src/utils/codexCatalogConfig.ts
@@ -0,0 +1,63 @@
+export interface CodexCatalogReasoningLevel {
+ effort?: unknown
+}
+
+export interface CodexCatalogModel {
+ slug: string
+ default_reasoning_level?: unknown
+ supported_reasoning_levels?: CodexCatalogReasoningLevel[]
+}
+
+function trimEffort(value: unknown): string {
+ if (typeof value !== 'string') return ''
+ return value.trim()
+}
+
+export function parseCodexCatalogModels(content: string | null | undefined): CodexCatalogModel[] {
+ if (!content) return []
+ try {
+ const payload: unknown = JSON.parse(content)
+ if (typeof payload !== 'object' || payload === null || !('models' in payload)) return []
+ const models = (payload as { models?: unknown }).models
+ if (!Array.isArray(models)) return []
+ return models.flatMap((model) => {
+ if (typeof model !== 'object' || model === null || !('slug' in model)) return []
+ const slug = trimEffort((model as { slug?: unknown }).slug)
+ if (!slug) return []
+ return [{ ...(model as CodexCatalogModel), slug }]
+ })
+ } catch {
+ return []
+ }
+}
+
+export function findCodexCatalogModel(
+ content: string | null | undefined,
+ slug: string
+): CodexCatalogModel | undefined {
+ const wanted = slug.trim()
+ if (!wanted) return undefined
+ return parseCodexCatalogModels(content).find((model) => model.slug === wanted)
+}
+
+export function selectCodexConfigReasoningEffort(
+ model: CodexCatalogModel | undefined
+): string | null {
+ if (!model) return null
+ const efforts = (model.supported_reasoning_levels ?? []).flatMap((level) => {
+ const effort = trimEffort(level?.effort)
+ return effort ? [effort] : []
+ })
+ if (efforts.length === 0) return null
+
+ const defaultLevel = trimEffort(model.default_reasoning_level)
+ if (defaultLevel && efforts.includes(defaultLevel)) {
+ return defaultLevel === 'none' ? null : defaultLevel
+ }
+ return efforts.find((effort) => effort !== 'none') ?? null
+}
+
+export function formatCodexReasoningEffortTomlLine(effort: string | null): string {
+ if (!effort) return ''
+ return `model_reasoning_effort = "${effort}"\n`
+}
diff --git a/frontend/src/utils/featureFlags.ts b/frontend/src/utils/featureFlags.ts
index f2e36b4a60..5cf6c46b31 100644
--- a/frontend/src/utils/featureFlags.ts
+++ b/frontend/src/utils/featureFlags.ts
@@ -109,6 +109,11 @@ export const FeatureFlags = {
mode: 'opt-in',
label: 'Model Plaza',
}),
+ pluginManagement: defineFlag({
+ key: 'plugin_management_enabled',
+ mode: 'opt-in',
+ label: 'Plugin Management',
+ }),
payment: defineFlag({
key: 'payment_enabled',
mode: 'opt-out',
diff --git a/frontend/src/utils/format.ts b/frontend/src/utils/format.ts
index 787bd4b545..17ba82e098 100644
--- a/frontend/src/utils/format.ts
+++ b/frontend/src/utils/format.ts
@@ -211,11 +211,15 @@ export function parseDateTimeLocalInput(value: string): number | null {
* @param effort 原始 effort(如 "low" / "medium" / "high" / "xhigh")
* @returns 格式化后的字符串(Low / Medium / High / Xhigh),无值返回 "-"
*/
+function normalizeReasoningEffortKey(effort: string | null | undefined): string {
+ return (effort ?? '').toString().trim().toLowerCase().replace(/[-_\s]/g, '')
+}
+
export function formatReasoningEffort(effort: string | null | undefined): string {
const raw = (effort ?? '').toString().trim()
if (!raw) return '-'
- const normalized = raw.toLowerCase().replace(/[-_\s]/g, '')
+ const normalized = normalizeReasoningEffortKey(raw)
switch (normalized) {
case 'low':
return 'Low'
@@ -237,6 +241,31 @@ export function formatReasoningEffort(effort: string | null | undefined): string
}
}
+export function reasoningEffortValuesEqual(
+ left: string | null | undefined,
+ right: string | null | undefined,
+): boolean {
+ const a = normalizeReasoningEffortKey(left)
+ const b = normalizeReasoningEffortKey(right)
+ if (!a && !b) return true
+ return a !== '' && a === b
+}
+
+/** Requested vs forwarded effort for usage export; one value when they match. */
+export function formatReasoningEffortMapping(
+ requested: string | null | undefined,
+ forwarded: string | null | undefined,
+): string {
+ const requestedLabel = formatReasoningEffort(requested)
+ const forwardedLabel = formatReasoningEffort(forwarded)
+ if (requestedLabel === '-' && forwardedLabel === '-') return '-'
+ if (requestedLabel === '-' || reasoningEffortValuesEqual(requested, forwarded)) {
+ return forwardedLabel === '-' ? requestedLabel : forwardedLabel
+ }
+ if (forwardedLabel === '-') return requestedLabel
+ return `${requestedLabel} → ${forwardedLabel}`
+}
+
/**
* 格式化时间(显示时分秒)
* @param date 日期字符串或 Date 对象
diff --git a/frontend/src/views/HomeView.vue b/frontend/src/views/HomeView.vue
index ddb3e87e1d..bde794ba0b 100644
--- a/frontend/src/views/HomeView.vue
+++ b/frontend/src/views/HomeView.vue
@@ -40,6 +40,15 @@
>
+
+
+ {{ t('nav.modelPlaza') }}
+
+
+
+
+ {{ t('nav.modelPlaza') }}
+
+
sanitizeUrl(appStore.cachedPublicSettings?.doc_url
const homeContent = computed(() => appStore.cachedPublicSettings?.home_content || '')
const hasHomeContent = computed(() => homeContent.value.trim().length > 0)
const compactHomeEnabled = computed(() => appStore.cachedPublicSettings?.compact_home_enabled === true)
+const modelPlazaEnabled = computed(() => isFeatureFlagEnabled(FeatureFlags.modelPlaza))
// Check if homeContent is a URL (for iframe display)
const isHomeContentUrl = computed(() => {
@@ -509,6 +531,12 @@ const githubUrl = 'https://github.com/Wei-Shaw/sub2api'
// Auth state
const isAuthenticated = computed(() => authStore.isAuthenticated)
+const modelPlazaRequiresAuth = computed(
+ () => appStore.cachedPublicSettings?.model_plaza_require_auth === true,
+)
+const showModelPlazaEntry = computed(
+ () => modelPlazaEnabled.value && (isAuthenticated.value || !modelPlazaRequiresAuth.value),
+)
const isAdmin = computed(() => authStore.isAdmin)
const dashboardPath = computed(() => isAdmin.value ? '/admin/dashboard' : '/dashboard')
const userInitial = computed(() => {
diff --git a/frontend/src/views/__tests__/HomeView.compact.spec.ts b/frontend/src/views/__tests__/HomeView.compact.spec.ts
index fbe8f8f604..7d9ad9f979 100644
--- a/frontend/src/views/__tests__/HomeView.compact.spec.ts
+++ b/frontend/src/views/__tests__/HomeView.compact.spec.ts
@@ -25,6 +25,10 @@ vi.mock('@/stores', () => ({
useAuthStore: () => authStore,
}))
+vi.mock('@/stores/app', () => ({
+ useAppStore: () => appStore,
+}))
+
vi.mock('vue-i18n', async (importOriginal) => {
const actual = await importOriginal()
return {
@@ -55,6 +59,13 @@ function compactDestination(wrapper: ReturnType) {
return wrapper.get('[data-testid="compact-home"]').findComponent(RouterLinkStub).props('to')
}
+function modelPlazaDestination(wrapper: ReturnType) {
+ return wrapper
+ .findAllComponents(RouterLinkStub)
+ .find((link) => link.props('to') === '/model-plaza')
+ ?.props('to')
+}
+
describe('HomeView compact mode', () => {
beforeEach(() => {
authStore.isAuthenticated = false
@@ -119,4 +130,55 @@ describe('HomeView compact mode', () => {
expect(authStore.checkAuth).toHaveBeenCalledOnce()
expect(appStore.fetchPublicSettings).not.toHaveBeenCalled()
})
+
+ it('shows the model plaza link to anonymous visitors when public access is enabled', () => {
+ const wrapper = mountHome({
+ compact_home_enabled: true,
+ model_plaza_enabled: true,
+ model_plaza_require_auth: false,
+ })
+
+ expect(modelPlazaDestination(wrapper)).toBe('/model-plaza')
+ })
+
+ it('hides the model plaza link from anonymous visitors when sign-in is required', () => {
+ const wrapper = mountHome({
+ compact_home_enabled: true,
+ model_plaza_enabled: true,
+ model_plaza_require_auth: true,
+ })
+
+ expect(modelPlazaDestination(wrapper)).toBeUndefined()
+ })
+
+ it('shows the model plaza link to authenticated visitors when sign-in is required', () => {
+ authStore.isAuthenticated = true
+
+ const wrapper = mountHome({
+ compact_home_enabled: true,
+ model_plaza_enabled: true,
+ model_plaza_require_auth: true,
+ })
+
+ expect(modelPlazaDestination(wrapper)).toBe('/model-plaza')
+ })
+
+ it('shows the model plaza link in the default home header', () => {
+ const wrapper = mountHome({
+ model_plaza_enabled: true,
+ model_plaza_require_auth: false,
+ })
+
+ expect(modelPlazaDestination(wrapper)).toBe('/model-plaza')
+ })
+
+ it('hides the model plaza link when the feature is disabled', () => {
+ const wrapper = mountHome({
+ compact_home_enabled: true,
+ model_plaza_enabled: false,
+ model_plaza_require_auth: false,
+ })
+
+ expect(modelPlazaDestination(wrapper)).toBeUndefined()
+ })
})
diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue
index 982c21b6f5..cbefbc5a03 100644
--- a/frontend/src/views/admin/AccountsView.vue
+++ b/frontend/src/views/admin/AccountsView.vue
@@ -634,7 +634,7 @@ const accountToolsDropdownStyle = computed(() => ({
width: `${accountToolsDropdownPosition.width}px`
}))
const hiddenColumns = reactive>(new Set())
-const DEFAULT_HIDDEN_COLUMNS = ['today_stats', 'proxy', 'notes', 'priority', 'scheduler_score', 'rate_multiplier']
+const DEFAULT_HIDDEN_COLUMNS = ['today_stats', 'proxy', 'notes', 'scheduler_score', 'rate_multiplier']
const HIDDEN_COLUMNS_KEY = 'account-hidden-columns'
// One-time migration: hide scheduler score for existing admins too, because showing it opt-ins to heavy backend scoring.
const HIDDEN_COLUMNS_VERSION_KEY = 'account-hidden-columns-version'
diff --git a/frontend/src/views/admin/ChannelsView.vue b/frontend/src/views/admin/ChannelsView.vue
index 4da09f900c..fece592ad1 100644
--- a/frontend/src/views/admin/ChannelsView.vue
+++ b/frontend/src/views/admin/ChannelsView.vue
@@ -448,6 +448,7 @@
:entry="entry"
:platform="section.platform"
enable-time-pricing
+ enable-tier-multipliers
@update="updatePricingEntry(sIdx, idx, $event)"
@remove="removePricingEntry(sIdx, idx)"
/>
@@ -633,7 +634,7 @@ import { extractApiErrorMessage } from '@/utils/apiError'
import { adminAPI } from '@/api/admin'
import type { Channel, ChannelModelPricing, CreateChannelRequest, UpdateChannelRequest, AccountStatsPricingRule } from '@/api/admin/channels'
import type { PricingFormEntry } from '@/components/admin/channel/types'
-import { apiIntervalsToForm, apiTimePricingToForm, createDefaultTimePricingForm, findModelConflict, formIntervalsToAPI, formTimePricingToAPI, mTokToPerToken, perTokenToMTok, validateIntervals, validateTimePricing } from '@/components/admin/channel/types'
+import { apiIntervalsToForm, apiTimePricingToForm, createDefaultTimePricingForm, findModelConflict, formIntervalsToAPI, formTimePricingToAPI, isValidPositiveMultiplier, mTokToPerToken, perTokenToMTok, validateIntervals, validateTimePricing } from '@/components/admin/channel/types'
import type { AdminGroup, GroupPlatform } from '@/types'
import type { Column } from '@/components/common/types'
import { platformTextClass, platformBadgeLightClass } from '@/utils/platformColors'
@@ -861,6 +862,8 @@ function addPricingEntry(sectionIdx: number) {
output_price: null,
cache_write_price: null,
cache_read_price: null,
+ fast_multiplier: null,
+ flex_multiplier: null,
image_input_price: null,
image_output_price: null,
per_request_price: null,
@@ -895,6 +898,8 @@ async function syncLatestModels(sectionIdx: number) {
output_price: null,
cache_write_price: null,
cache_read_price: null,
+ fast_multiplier: null,
+ flex_multiplier: null,
image_input_price: null,
image_output_price: null,
per_request_price: null,
@@ -1120,6 +1125,8 @@ function formToAPI(): { group_ids: number[], model_pricing: ChannelModelPricing[
output_price: mTokToPerToken(entry.output_price),
cache_write_price: mTokToPerToken(entry.cache_write_price),
cache_read_price: mTokToPerToken(entry.cache_read_price),
+ fast_multiplier: entry.fast_multiplier != null && entry.fast_multiplier !== '' ? Number(entry.fast_multiplier) : null,
+ flex_multiplier: entry.flex_multiplier != null && entry.flex_multiplier !== '' ? Number(entry.flex_multiplier) : null,
image_input_price: mTokToPerToken(entry.image_input_price),
image_output_price: mTokToPerToken(entry.image_output_price),
per_request_price: entry.per_request_price != null && entry.per_request_price !== '' ? Number(entry.per_request_price) : null,
@@ -1219,6 +1226,8 @@ function apiToForm(channel: Channel): PlatformSection[] {
output_price: perTokenToMTok(p.output_price),
cache_write_price: perTokenToMTok(p.cache_write_price),
cache_read_price: perTokenToMTok(p.cache_read_price),
+ fast_multiplier: p.fast_multiplier,
+ flex_multiplier: p.flex_multiplier,
image_input_price: perTokenToMTok(p.image_input_price),
image_output_price: perTokenToMTok(p.image_output_price),
per_request_price: p.per_request_price,
@@ -1524,6 +1533,14 @@ async function handleSubmit() {
// 校验区间合法性(范围、重叠等)
for (const section of form.platforms.filter(s => s.enabled)) {
for (const entry of section.model_pricing) {
+ if (!isValidPositiveMultiplier(entry.fast_multiplier) ||
+ !isValidPositiveMultiplier(entry.flex_multiplier)) {
+ const platformLabel = t('admin.groups.platforms.' + section.platform, section.platform)
+ const modelLabel = entry.models.join(', ') || t('admin.channels.form.unnamed')
+ appStore.showError(`${platformLabel} - ${modelLabel}: ${t('admin.channels.form.multiplierPositive')}`)
+ activeTab.value = section.platform
+ return
+ }
if (!entry.intervals || entry.intervals.length === 0) continue
const intervalErr = validateIntervals(entry.intervals, entry.billing_mode, t)
if (intervalErr) {
diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue
index 3fff44b131..d019a24b8e 100644
--- a/frontend/src/views/admin/GroupsView.vue
+++ b/frontend/src/views/admin/GroupsView.vue
@@ -1614,9 +1614,9 @@
-
+
@@ -1655,7 +1655,13 @@
{{ t("admin.groups.openaiMessages.allowDispatchHint") }}
-
+
@@ -3336,9 +3342,9 @@
-
+
@@ -3377,7 +3383,12 @@
{{ t("admin.groups.openaiMessages.allowDispatchHint") }}
-
+
@@ -4422,6 +4433,10 @@ import type {
GroupPlatform,
SubscriptionType,
} from "@/types";
+import {
+ CONCRETE_PLATFORM_OPTIONS,
+ GROUP_PLATFORM_OPTIONS,
+} from "@/constants/platforms";
import type { Column } from "@/components/common/types";
import AppLayout from "@/components/layout/AppLayout.vue";
import TablePageLayout from "@/components/layout/TablePageLayout.vue";
@@ -4458,6 +4473,7 @@ import {
messagesDispatchConfigToFormState,
messagesDispatchFormStateToConfig,
resetMessagesDispatchFormState,
+ supportsMessagesDispatchPlatform,
type MessagesDispatchMappingRow,
} from "./groupsMessagesDispatch";
import {
@@ -4740,40 +4756,15 @@ const exclusiveOptions = computed(() => [
{ value: "false", label: t("admin.groups.nonExclusive") },
]);
-const platformOptions = computed(() => [
- { value: "anthropic", label: "Anthropic" },
- { value: "openai", label: "OpenAI" },
- { value: "gemini", label: "Gemini" },
- { value: "antigravity", label: "Antigravity" },
- { value: "grok", label: "Grok" },
- { value: "kimi", label: "Kimi" },
- { value: "zhipu", label: "Zhipu GLM" },
- { value: "deepseek", label: "DeepSeek" },
- { value: "composite", label: "Composite" },
-]);
+const platformOptions = computed(() => [...GROUP_PLATFORM_OPTIONS]);
const platformFilterOptions = computed(() => [
{ value: "", label: t("admin.groups.allPlatforms") },
- { value: "anthropic", label: "Anthropic" },
- { value: "openai", label: "OpenAI" },
- { value: "gemini", label: "Gemini" },
- { value: "antigravity", label: "Antigravity" },
- { value: "grok", label: "Grok" },
- { value: "kimi", label: "Kimi" },
- { value: "zhipu", label: "Zhipu GLM" },
- { value: "deepseek", label: "DeepSeek" },
- { value: "composite", label: "Composite" },
+ ...GROUP_PLATFORM_OPTIONS,
]);
const compositeRoutePlatformOptions = computed(() => [
- { value: "anthropic", label: "Anthropic" },
- { value: "openai", label: "OpenAI" },
- { value: "gemini", label: "Gemini" },
- { value: "antigravity", label: "Antigravity" },
- { value: "grok", label: "Grok" },
- { value: "kimi", label: "Kimi" },
- { value: "zhipu", label: "Zhipu GLM" },
- { value: "deepseek", label: "DeepSeek" },
+ ...CONCRETE_PLATFORM_OPTIONS,
]);
const compositeRouteEndpointOptions = computed(() => [
@@ -6667,7 +6658,7 @@ watch(
if (!["anthropic", "antigravity"].includes(newVal)) {
createForm.fallback_group_id_on_invalid_request = null;
}
- if (newVal !== "openai") {
+ if (!supportsMessagesDispatchPlatform(newVal)) {
resetMessagesDispatchFormState(createForm);
}
if (!supportsLivePlatform(newVal)) {
@@ -6717,7 +6708,7 @@ watch(
if (!["anthropic", "antigravity"].includes(newVal)) {
editForm.fallback_group_id_on_invalid_request = null;
}
- if (newVal !== "openai") {
+ if (!supportsMessagesDispatchPlatform(newVal)) {
resetMessagesDispatchFormState(editForm);
}
if (!supportsLivePlatform(newVal)) {
@@ -6769,7 +6760,7 @@ watch(
if (!['anthropic', 'antigravity'].includes(newVal)) {
editForm.fallback_group_id_on_invalid_request = null
}
- if (newVal !== 'openai') {
+ if (!supportsMessagesDispatchPlatform(newVal)) {
editForm.allow_messages_dispatch = false
editForm.default_mapped_model = ''
}
diff --git a/frontend/src/views/admin/PluginsView.vue b/frontend/src/views/admin/PluginsView.vue
new file mode 100644
index 0000000000..a947b6d74a
--- /dev/null
+++ b/frontend/src/views/admin/PluginsView.vue
@@ -0,0 +1,716 @@
+
+
+
+
+
+
+ {{ t("admin.plugins.title") }}
+
+
+ {{ t("admin.plugins.description") }}
+
+
+ {{
+ t("admin.plugins.onlyOpenAI")
+ }}
+ {{
+ t("admin.plugins.noAccountCoupling")
+ }}
+
+
+
+
+
+
+
+ {{ uploading ? t("common.processing") : t("admin.plugins.upload") }}
+
+
+
+ {{ t("common.refresh") }}
+
+
+
+
+
+ {{ t("admin.plugins.uploadHint") }}
+
+
+
+
{{ t("admin.plugins.runtimeNotice") }}
+
{{ t("admin.plugins.menuNotice") }}
+
+
+
+ {{ t("common.loading") }}
+
+
+
+
+
+ {{ t("admin.plugins.empty") }}
+
+
+ {{ t("admin.plugins.emptyHint") }}
+
+
+
+
+
+
+
+
+
+ {{ plugin.name }}
+
+ v{{ plugin.version }}
+
+ {{ t(`admin.plugins.${plugin.state}`) }}
+
+
+
+ {{ plugin.plugin_key
+ }} · {{ plugin.author }}
+
+
+ {{ plugin.description }}
+
+
+
+
+ {{ t("admin.plugins.configure") }}
+
+
+
+
+
+
+ {{ t("admin.plugins.compatibility") }}
+
+
+
+ {{ t(`admin.plugins.${plugin.compatibility.status}`) }}
+
+ {{
+ plugin.compatibility.message
+ }}
+
+
+
+ {{ t("admin.plugins.currentVersion") }}
+
+
+ {{ plugin.compatibility.current_sub2api_version }}
+
+
+ {{ t("admin.plugins.requiredVersion") }}
+
+
+ {{ plugin.compatibility.required_sub2api_version }}
+
+
+ {{ t("admin.plugins.recommendedVersion") }}
+
+
+ {{ plugin.compatibility.recommended_sub2api_version || "-" }}
+
+
+
+
+
+
+ {{ t("admin.plugins.runtime") }}
+
+
+
+ {{
+ plugin.runtime_healthy
+ ? t("admin.plugins.healthy")
+ : t("admin.plugins.unhealthy")
+ }}
+
+
+ {{ t("admin.plugins.signature") }}:
+ {{ t(`admin.plugins.${plugin.signature_status}`) }}
+
+
+
+ {{ plugin.last_error }}
+
+
+ {{ plugin.runtime_message }}
+
+
+
+
+
+ {{ t("admin.plugins.rollout") }}
+ {{
+ rolloutValues[plugin.id] ?? currentRollout(plugin)
+ }}%
+
+
+
+
+
+
+
+
+ {{ t("admin.plugins.test") }}
+
+
+
+ {{ t("admin.plugins.disable") }}
+
+
+
+ {{ t("admin.plugins.enable") }}
+
+
+
+ {{ t("admin.plugins.uninstall") }}
+
+
+
+
+
+
+
+
+ {{ t("admin.plugins.loadingUI") }}
+
+
+
+
+ {{ t("admin.plugins.uiUnavailable") }}
+
+
{{ uiError }}
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/views/admin/ProxiesView.vue b/frontend/src/views/admin/ProxiesView.vue
index 0572cc254b..a5cd50f07e 100644
--- a/frontend/src/views/admin/ProxiesView.vue
+++ b/frontend/src/views/admin/ProxiesView.vue
@@ -1276,6 +1276,7 @@ const handleDataImported = () => {
}
// Parse proxy URL: protocol://user:pass@host:port or protocol://host:port
+// Host may be a domain, IPv4, or bracketed IPv6 ([2001:db8::1]).
const parseProxyUrl = (
line: string
): {
@@ -1288,20 +1289,26 @@ const parseProxyUrl = (
const trimmed = line.trim()
if (!trimmed) return null
- // Regex to parse proxy URL (supports http, https, socks5, socks5h)
- const regex = /^(https?|socks5h?):\/\/(?:([^:@]+):([^@]+)@)?([^:]+):(\d+)$/i
+ // Regex to parse proxy URL (supports http, https, socks5, socks5h).
+ // Host alternatives: [bracketed-IPv6] | hostname/IPv4 (colon-free, so the
+ // match stops before the final :port).
+ const regex =
+ /^(https?|socks5h?):\/\/(?:([^:@\[\]]+):([^@\[\]]+)@)?(\[[0-9a-f:.]+\]|[^:\[\]]+):(\d+)$/i
const match = trimmed.match(regex)
if (!match) return null
- const [, protocol, username, password, host, port] = match
+ const [, protocol, username, password, rawHost, port] = match
const portNum = parseInt(port, 10)
if (portNum < 1 || portNum > 65535) return null
+ // Strip brackets from IPv6 literals; the backend re-brackets via net.JoinHostPort.
+ const host = rawHost.replace(/^\[|\]$/g, '').trim()
+
return {
protocol: protocol.toLowerCase() as ProxyProtocol,
- host: host.trim(),
+ host,
port: portNum,
username: username?.trim() || '',
password: password?.trim() || ''
diff --git a/frontend/src/views/admin/SettingsView.vue b/frontend/src/views/admin/SettingsView.vue
index 80af0b1940..7d68bcb87b 100644
--- a/frontend/src/views/admin/SettingsView.vue
+++ b/frontend/src/views/admin/SettingsView.vue
@@ -7188,6 +7188,30 @@
+
+
+
+ {{ t('admin.settings.features.pluginManagement.title') }}
+
+
+ {{ t('admin.settings.features.pluginManagement.description') }}
+
+
+
+
+
+
+ {{ t('admin.settings.features.pluginManagement.enabled') }}
+
+
+ {{ t('admin.settings.features.pluginManagement.enabledHint') }}
+
+
+
+
+
+
+
@@ -9752,6 +9776,8 @@ const form = reactive({
model_plaza_enabled: false,
model_plaza_require_auth: false,
model_plaza_description: '',
+ // Plugin management menu visibility; plugin runtime is unaffected.
+ plugin_management_enabled: false,
// Affiliate (邀请返利) feature switch
affiliate_enabled: false,
// Allow user view error requests
@@ -11408,6 +11434,7 @@ async function saveSettings() {
model_plaza_enabled: form.model_plaza_enabled,
model_plaza_require_auth: form.model_plaza_require_auth,
model_plaza_description: form.model_plaza_description,
+ plugin_management_enabled: form.plugin_management_enabled,
// Affiliate (邀请返利) feature switch
affiliate_enabled: form.affiliate_enabled,
allow_user_view_error_requests: form.allow_user_view_error_requests,
diff --git a/frontend/src/views/admin/SubscriptionsView.vue b/frontend/src/views/admin/SubscriptionsView.vue
index b23fa2fdc7..66569dad94 100644
--- a/frontend/src/views/admin/SubscriptionsView.vue
+++ b/frontend/src/views/admin/SubscriptionsView.vue
@@ -788,6 +788,7 @@ import {
isOneTimeDailyQuota,
type RemainingDurationParts
} from '@/utils/subscriptionQuota'
+import { GROUP_PLATFORM_OPTIONS } from '@/constants/platforms'
const { t } = useI18n()
const appStore = useAppStore()
@@ -996,10 +997,7 @@ const groupOptions = computed(() => [
const platformFilterOptions = computed(() => [
{ value: '', label: t('admin.subscriptions.allPlatforms') },
- { value: 'anthropic', label: 'Anthropic' },
- { value: 'openai', label: 'OpenAI' },
- { value: 'gemini', label: 'Gemini' },
- { value: 'antigravity', label: 'Antigravity' }
+ ...GROUP_PLATFORM_OPTIONS
])
// Group options for assign (only subscription type groups)
diff --git a/frontend/src/views/admin/UsageView.vue b/frontend/src/views/admin/UsageView.vue
index b598f610ab..1fa950e75b 100644
--- a/frontend/src/views/admin/UsageView.vue
+++ b/frontend/src/views/admin/UsageView.vue
@@ -87,6 +87,7 @@
@@ -575,7 +577,7 @@ const exportToExcel = async () => {
const XLSX = await import('xlsx')
const headers = [
t('usage.time'), t('admin.usage.user'), t('usage.apiKeyFilter'),
- t('admin.usage.account'), t('usage.requestedModel'), t('usage.sentUpstreamModel'), t('usage.upstreamResponseModel'), t('usage.upstreamModelMismatch'), t('usage.reasoningEffort'), t('admin.usage.group'),
+ t('admin.usage.account'), t('usage.requestedModel'), t('usage.sentUpstreamModel'), t('usage.upstreamResponseModel'), t('usage.upstreamModelMismatch'), t('usage.requestedReasoningEffort'), t('usage.reasoningEffort'), t('admin.usage.group'),
t('usage.inboundEndpoint'), t('usage.upstreamEndpoint'),
t('usage.type'),
t('admin.usage.inputTokens'), t('admin.usage.outputTokens'),
@@ -595,7 +597,7 @@ const exportToExcel = async () => {
if (c.signal.aborted) break; if (p === 1) { total = res.total; exportProgress.total = total }
const rows = (res.items || []).map((log: AdminUsageLog) => [
log.created_at, log.user?.email || '', log.api_key?.name || '', log.account?.name || '', log.model,
- log.upstream_model || log.model, log.upstream_response_model || '', log.upstream_model_mismatch == null ? '' : t(log.upstream_model_mismatch ? 'common.yes' : 'common.no'), formatReasoningEffort(log.reasoning_effort), log.group?.name || '',
+ log.upstream_model || log.model, log.upstream_response_model || '', log.upstream_model_mismatch == null ? '' : t(log.upstream_model_mismatch ? 'common.yes' : 'common.no'), formatReasoningEffort(log.reasoning_effort), formatReasoningEffort(log.upstream_reasoning_effort || log.reasoning_effort), log.group?.name || '',
log.inbound_endpoint || '', log.upstream_endpoint || '', getRequestTypeLabel(log),
log.input_tokens, log.output_tokens, log.cache_read_tokens, log.cache_creation_tokens,
log.input_cost?.toFixed(6) || '0.000000', log.output_cost?.toFixed(6) || '0.000000',
diff --git a/frontend/src/views/admin/__tests__/AccountsView.priorityColumn.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.priorityColumn.spec.ts
new file mode 100644
index 0000000000..42c1071e87
--- /dev/null
+++ b/frontend/src/views/admin/__tests__/AccountsView.priorityColumn.spec.ts
@@ -0,0 +1,152 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { flushPromises, mount } from '@vue/test-utils'
+
+import AccountsView from '../AccountsView.vue'
+
+const { listAccounts } = vi.hoisted(() => ({
+ listAccounts: vi.fn()
+}))
+
+vi.mock('@/api/admin', () => ({
+ adminAPI: {
+ accounts: {
+ list: listAccounts,
+ listWithEtag: vi.fn(),
+ getBatchTodayStats: vi.fn().mockResolvedValue({ stats: {} }),
+ getUpstreamBillingProbeSettings: vi.fn().mockResolvedValue({ enabled: true, interval_minutes: 30 }),
+ delete: vi.fn(),
+ batchClearError: vi.fn(),
+ batchRefresh: vi.fn(),
+ toggleSchedulable: vi.fn()
+ },
+ proxies: { getAll: vi.fn().mockResolvedValue([]) },
+ groups: { getAll: vi.fn().mockResolvedValue([]) }
+ }
+}))
+
+vi.mock('@/stores/app', () => ({
+ useAppStore: () => ({ showError: vi.fn(), showSuccess: vi.fn(), showInfo: vi.fn() })
+}))
+
+vi.mock('@/stores/auth', () => ({
+ useAuthStore: () => ({ token: 'test-token', isSimpleMode: false })
+}))
+
+vi.mock('vue-i18n', async () => {
+ const actual = await vi.importActual('vue-i18n')
+ return {
+ ...actual,
+ useI18n: () => ({ t: (key: string) => key })
+ }
+})
+
+const DataTableStub = {
+ props: ['columns'],
+ emits: ['sort'],
+ template: `
+
+
+ {{ column.sortable ? 'sortable' : 'fixed' }}
+
+
+
+ `
+}
+
+function mountView() {
+ return mount(AccountsView, {
+ global: {
+ stubs: {
+ AppLayout: { template: '
' },
+ TablePageLayout: {
+ template: '
'
+ },
+ DataTable: DataTableStub,
+ AccountTableActions: { template: '
' },
+ AccountTableFilters: true,
+ AccountBulkActionsBar: true,
+ Pagination: true,
+ ConfirmDialog: true,
+ AccountActionMenu: true,
+ ImportDataModal: true,
+ ReAuthAccountModal: true,
+ AccountTestModal: true,
+ AccountStatsModal: true,
+ ScheduledTestsPanel: true,
+ SyncFromCrsModal: true,
+ TempUnschedStatusModal: true,
+ ErrorPassthroughRulesModal: true,
+ TLSFingerprintProfilesModal: true,
+ CreateAccountModal: true,
+ EditAccountModal: true,
+ BulkEditAccountModal: true,
+ PlatformTypeBadge: true,
+ AccountCapacityCell: true,
+ AccountStatusIndicator: true,
+ AccountTodayStatsCell: true,
+ AccountGroupsCell: true,
+ AccountUsageCell: true,
+ HelpTooltip: true,
+ Icon: true,
+ Teleport: true
+ }
+ }
+ })
+}
+
+describe('admin AccountsView priority column preferences', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ listAccounts.mockReset().mockResolvedValue({
+ items: [],
+ total: 0,
+ page: 1,
+ page_size: 20,
+ pages: 0
+ })
+ })
+
+ it('shows priority as a sortable column for fresh preferences', async () => {
+ const wrapper = mountView()
+ await flushPromises()
+
+ expect(wrapper.get('[data-column="priority"]').text()).toBe('sortable')
+
+ await wrapper.get('[data-test="sort-priority"]').trigger('click')
+ await flushPromises()
+
+ expect(listAccounts).toHaveBeenLastCalledWith(
+ 1,
+ 20,
+ expect.objectContaining({ sort_by: 'priority', sort_order: 'desc' }),
+ expect.objectContaining({ signal: expect.any(AbortSignal) })
+ )
+ })
+
+ it('preserves an existing preference that explicitly hides priority', async () => {
+ localStorage.setItem('account-hidden-columns', JSON.stringify(['priority', 'today_stats']))
+ localStorage.setItem('account-hidden-columns-version', 'scheduler-score-hidden-by-default')
+
+ const wrapper = mountView()
+ await flushPromises()
+
+ expect(wrapper.find('[data-column="priority"]').exists()).toBe(false)
+ expect(JSON.parse(localStorage.getItem('account-hidden-columns') || '[]')).toEqual([
+ 'priority',
+ 'today_stats'
+ ])
+ })
+
+ it('keeps priority visible while migrating older saved preferences', async () => {
+ localStorage.setItem('account-hidden-columns', JSON.stringify(['today_stats']))
+
+ const wrapper = mountView()
+ await flushPromises()
+
+ expect(wrapper.get('[data-column="priority"]').text()).toBe('sortable')
+ expect(JSON.parse(localStorage.getItem('account-hidden-columns') || '[]')).toEqual(
+ expect.arrayContaining(['today_stats', 'scheduler_score'])
+ )
+ expect(JSON.parse(localStorage.getItem('account-hidden-columns') || '[]')).not.toContain('priority')
+ })
+})
diff --git a/frontend/src/views/admin/__tests__/GroupsView.compositePlatforms.spec.ts b/frontend/src/views/admin/__tests__/GroupsView.compositePlatforms.spec.ts
index d6b5abcfd7..93dcd679d4 100644
--- a/frontend/src/views/admin/__tests__/GroupsView.compositePlatforms.spec.ts
+++ b/frontend/src/views/admin/__tests__/GroupsView.compositePlatforms.spec.ts
@@ -1,17 +1,10 @@
-import { readFileSync } from 'node:fs'
-import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
+import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'
describe('GroupsView Composite route options', () => {
it('offers Kimi, Zhipu GLM, and DeepSeek as route targets', () => {
- const source = readFileSync(resolve('src/views/admin/GroupsView.vue'), 'utf8')
- const options = source.slice(
- source.indexOf('const compositeRoutePlatformOptions'),
- source.indexOf('const compositeRouteEndpointOptions')
+ expect(CONCRETE_PLATFORM_OPTIONS.map((option) => option.value)).toEqual(
+ expect.arrayContaining(['kimi', 'zhipu', 'deepseek'])
)
-
- expect(options).toContain('{ value: "kimi", label: "Kimi" }')
- expect(options).toContain('{ value: "zhipu", label: "Zhipu GLM" }')
- expect(options).toContain('{ value: "deepseek", label: "DeepSeek" }')
})
})
diff --git a/frontend/src/views/admin/__tests__/PluginsView.spec.ts b/frontend/src/views/admin/__tests__/PluginsView.spec.ts
new file mode 100644
index 0000000000..3fa4a7ed29
--- /dev/null
+++ b/frontend/src/views/admin/__tests__/PluginsView.spec.ts
@@ -0,0 +1,169 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import PluginsView from '../PluginsView.vue'
+
+const {
+ listPlugins,
+ uploadPlugin,
+ enablePlugin,
+ savePluginConfig,
+ createUISession,
+ stepUpRun,
+} = vi.hoisted(() => ({
+ listPlugins: vi.fn(),
+ uploadPlugin: vi.fn(),
+ enablePlugin: vi.fn(),
+ savePluginConfig: vi.fn(),
+ createUISession: vi.fn(),
+ stepUpRun: vi.fn((action: () => Promise) => action()),
+}))
+
+vi.mock('@/api/admin', () => ({
+ adminAPI: {
+ plugins: {
+ list: listPlugins,
+ upload: uploadPlugin,
+ enable: enablePlugin,
+ disable: vi.fn(),
+ remove: vi.fn(),
+ getConfig: vi.fn().mockResolvedValue({}),
+ saveConfig: savePluginConfig,
+ test: vi.fn().mockResolvedValue({ success: true, message: 'ok', latency_ms: 1 }),
+ createUISession,
+ },
+ },
+}))
+
+vi.mock('@/stores', () => ({
+ useAppStore: () => ({
+ showError: vi.fn(),
+ showSuccess: vi.fn(),
+ showInfo: vi.fn(),
+ }),
+}))
+
+vi.mock('@/composables/useStepUp', () => ({
+ useStepUp: () => ({ run: stepUpRun }),
+ isStepUpBlocked: () => false,
+ isStepUpCancelled: () => false,
+ stepUpBlockReason: () => '',
+}))
+
+vi.mock('vue-i18n', async (importOriginal) => ({
+ ...(await importOriginal()),
+ useI18n: () => ({ t: (key: string) => key }),
+}))
+
+const plugin = {
+ id: 7,
+ plugin_key: 'local.test.transport',
+ name: 'Test Transport',
+ version: '1.0.0',
+ description: '',
+ author: 'test',
+ manifest: {
+ schema_version: 1,
+ id: 'local.test.transport',
+ name: 'Test Transport',
+ version: '1.0.0',
+ requires: {
+ sub2api: '>=0.1.0',
+ plugin_protocol: 1,
+ transport_api: 1,
+ ui_bridge: 1,
+ },
+ capabilities: [],
+ ui: { entrypoint: 'ui/index.html' },
+ },
+ binary_sha256: 'a'.repeat(64),
+ signature_status: 'trusted' as const,
+ state: 'disabled' as const,
+ last_error: '',
+ installed_at: '2026-08-22T00:00:00Z',
+ updated_at: '2026-08-22T00:00:00Z',
+ bindings: [
+ {
+ id: 1,
+ plugin_id: 7,
+ capability: 'openai.oauth.outbound_transport.v1',
+ platform: 'openai',
+ account_type: 'oauth',
+ enabled: false,
+ rollout_percent: 100,
+ },
+ ],
+ compatibility: {
+ compatible: true,
+ tested: true,
+ status: 'compatible' as const,
+ message: '',
+ current_sub2api_version: '0.1.0',
+ required_sub2api_version: '>=0.1.0',
+ recommended_sub2api_version: '0.1.0',
+ plugin_protocol: 1,
+ transport_api: 1,
+ ui_bridge: 1,
+ },
+ runtime_healthy: false,
+ runtime_message: '',
+}
+
+function mountView() {
+ return mount(PluginsView, {
+ global: {
+ stubs: {
+ AppLayout: { template: '
' },
+ BaseDialog: { template: '
' },
+ Icon: true,
+ TotpStepUpDialog: true,
+ },
+ },
+ })
+}
+
+describe('管理员插件页二次验证', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ stepUpRun.mockImplementation((action: () => Promise) => action())
+ listPlugins.mockResolvedValue([plugin])
+ uploadPlugin.mockResolvedValue(plugin)
+ enablePlugin.mockResolvedValue(plugin)
+ savePluginConfig.mockResolvedValue({ enabled: true })
+ createUISession.mockResolvedValue({
+ url: '/api/v1/plugin-ui/token/index.html#bridge_token=bridge',
+ bridge_token: 'bridge',
+ ui_bridge_version: 1,
+ expires_at: '2026-08-22T01:00:00Z',
+ })
+ })
+
+ it('启用插件通过 step-up 控制器执行', async () => {
+ const wrapper = mountView()
+ await flushPromises()
+
+ const button = wrapper.findAll('button').find((item) => item.text().includes('admin.plugins.enable'))
+ expect(button).toBeDefined()
+ await button!.trigger('click')
+ await flushPromises()
+
+ expect(stepUpRun).toHaveBeenCalledTimes(1)
+ expect(enablePlugin).toHaveBeenCalledWith(7, 100, false)
+ })
+
+ it('上传插件通过 step-up 控制器执行', async () => {
+ const wrapper = mountView()
+ await flushPromises()
+ const input = wrapper.get('input[type="file"]')
+ Object.defineProperty(input.element, 'files', {
+ configurable: true,
+ value: [new File(['plugin'], 'transport.s2plugin', { type: 'application/zip' })],
+ })
+
+ await input.trigger('change')
+ await flushPromises()
+
+ expect(stepUpRun).toHaveBeenCalledTimes(1)
+ expect(uploadPlugin).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/views/admin/__tests__/ProxiesView.ipv6.spec.ts b/frontend/src/views/admin/__tests__/ProxiesView.ipv6.spec.ts
new file mode 100644
index 0000000000..6cea0ac86c
--- /dev/null
+++ b/frontend/src/views/admin/__tests__/ProxiesView.ipv6.spec.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+// parseProxyUrl is not exported; assert on the source to lock in the
+// bracketed-IPv6 host alternative and exercise the regex directly.
+const source = readFileSync(
+ resolve(process.cwd(), 'src/views/admin/ProxiesView.vue'),
+ 'utf8'
+)
+
+function extractRegex(): RegExp {
+ const match = source.match(/const regex =\s*\n?\s*(\/\^\(https\?[^;\n]+\/i)\n/)
+ expect(match, 'parseProxyUrl regex not found in ProxiesView.vue').toBeTruthy()
+ return new RegExp((match as RegExpMatchArray)[1].slice(1, -2), 'i')
+}
+
+describe('proxy batch URL parsing (IPv6 support)', () => {
+ it('keeps bracketed-IPv6 host alternative in the regex', () => {
+ expect(source).toContain('\\[[0-9a-f:.]+\\]')
+ })
+
+ const regex = extractRegex()
+
+ it.each([
+ ['socks5://[2001:db8::1]:1080', true],
+ ['socks5h://[2001:db8::1]:1080', true],
+ ['http://[::1]:8080', true],
+ ['socks5://user:pass@[2001:db8::1]:1080', true],
+ ['socks5://proxy.example.com:1080', true],
+ ['http://192.168.1.1:8080', true],
+ ['socks5://user:pass@proxy.example.com:1080', true],
+ // bare IPv6 without brackets is ambiguous with host:port — rejected
+ ['socks5://2001:db8::1:1080', false],
+ // unsupported schemes / malformed ports stay invalid
+ ['ftp://example.com:21', false],
+ ['socks5://example.com:port', false]
+ ])('%s => %s', (line, expected) => {
+ expect(regex.test(line)).toBe(expected)
+ })
+
+ it('extracts bare IPv6 host without brackets', () => {
+ const m = 'socks5://user:pass@[2001:db8::1]:1080'.match(regex)
+ expect(m).toBeTruthy()
+ const [, , username, password, rawHost, port] = m as RegExpMatchArray
+ expect(username).toBe('user')
+ expect(password).toBe('pass')
+ expect(rawHost.replace(/^\[|\]$/g, '')).toBe('2001:db8::1')
+ expect(port).toBe('1080')
+ })
+})
diff --git a/frontend/src/views/admin/__tests__/groupsMessagesDispatch.spec.ts b/frontend/src/views/admin/__tests__/groupsMessagesDispatch.spec.ts
index 15f422247a..e516cccb76 100644
--- a/frontend/src/views/admin/__tests__/groupsMessagesDispatch.spec.ts
+++ b/frontend/src/views/admin/__tests__/groupsMessagesDispatch.spec.ts
@@ -5,9 +5,16 @@ import {
messagesDispatchConfigToFormState,
messagesDispatchFormStateToConfig,
resetMessagesDispatchFormState,
+ supportsMessagesDispatchPlatform,
} from "../groupsMessagesDispatch";
describe("groupsMessagesDispatch", () => {
+ it("supports OpenAI and composite groups", () => {
+ expect(supportsMessagesDispatchPlatform("openai")).toBe(true);
+ expect(supportsMessagesDispatchPlatform("composite")).toBe(true);
+ expect(supportsMessagesDispatchPlatform("anthropic")).toBe(false);
+ });
+
it("returns the expected default form state", () => {
expect(createDefaultMessagesDispatchFormState()).toEqual({
allow_messages_dispatch: false,
diff --git a/frontend/src/views/admin/__tests__/platformFilterCatalogUsage.spec.ts b/frontend/src/views/admin/__tests__/platformFilterCatalogUsage.spec.ts
new file mode 100644
index 0000000000..cbf211fadd
--- /dev/null
+++ b/frontend/src/views/admin/__tests__/platformFilterCatalogUsage.spec.ts
@@ -0,0 +1,33 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+function readSource(path: string): string {
+ return readFileSync(resolve(path), 'utf8')
+}
+
+describe('admin platform filters', () => {
+ it('uses the group platform catalog on the subscriptions page', () => {
+ const source = readSource('src/views/admin/SubscriptionsView.vue')
+ expect(source).toContain("import { GROUP_PLATFORM_OPTIONS } from '@/constants/platforms'")
+ expect(source).toMatch(/const platformFilterOptions[\s\S]*?\.\.\.GROUP_PLATFORM_OPTIONS/)
+ })
+
+ it('uses the shared catalogs on the groups page', () => {
+ const source = readSource('src/views/admin/GroupsView.vue')
+ expect(source).toContain('...GROUP_PLATFORM_OPTIONS')
+ expect(source).toContain('...CONCRETE_PLATFORM_OPTIONS')
+ })
+
+ it('uses the concrete platform catalog wherever concrete platforms are selected', () => {
+ for (const path of [
+ 'src/components/admin/account/AccountTableFilters.vue',
+ 'src/components/admin/ErrorPassthroughRulesModal.vue',
+ 'src/views/admin/ops/components/OpsDashboardHeader.vue'
+ ]) {
+ const source = readSource(path)
+ expect(source).toContain("import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'")
+ expect(source).toMatch(/platformOptions\s*=.*CONCRETE_PLATFORM_OPTIONS|pOpts.*\.\.\.CONCRETE_PLATFORM_OPTIONS/s)
+ }
+ })
+})
diff --git a/frontend/src/views/admin/groupsMessagesDispatch.ts b/frontend/src/views/admin/groupsMessagesDispatch.ts
index b367091cd7..677a95e574 100644
--- a/frontend/src/views/admin/groupsMessagesDispatch.ts
+++ b/frontend/src/views/admin/groupsMessagesDispatch.ts
@@ -13,6 +13,10 @@ export interface MessagesDispatchFormState {
exact_model_mappings: MessagesDispatchMappingRow[];
}
+export function supportsMessagesDispatchPlatform(platform: string): boolean {
+ return platform === "openai" || platform === "composite";
+}
+
export function createDefaultMessagesDispatchFormState(): MessagesDispatchFormState {
return {
allow_messages_dispatch: false,
diff --git a/frontend/src/views/admin/ops/OpsDashboard.vue b/frontend/src/views/admin/ops/OpsDashboard.vue
index cd5c672963..dc482ab074 100644
--- a/frontend/src/views/admin/ops/OpsDashboard.vue
+++ b/frontend/src/views/admin/ops/OpsDashboard.vue
@@ -119,11 +119,12 @@
:platform="platform"
:group-id="groupId"
:error-type="errorDetailsType"
+ :resume-state="resumeListState"
@update:show="showErrorDetails = $event"
@openErrorDetail="openError"
/>
-
+
@@ -377,6 +379,13 @@ const requestDetailsPreset = ref({
sort: 'created_at_desc'
})
+// 记录单条错误详情来自哪个列表,便于"返回列表"时重新打开对应弹窗并保留状态。
+type DetailReturnTarget = 'errorList' | 'requestList' | null
+const detailReturnTarget = ref(null)
+
+// 从详情返回时,列表弹窗应保留上一次的筛选/分页状态而非重置。
+const resumeListState = ref(false)
+
const showSettingsDialog = ref(false)
const showAlertRulesCard = ref(false)
@@ -508,12 +517,34 @@ function onQueryModeChange(v: string | number | boolean | null) {
function openError(id: number) {
selectedErrorId.value = id
+ // 记录来源列表,便于详情页"返回列表"。
+ detailReturnTarget.value = showRequestDetails.value ? 'requestList' : showErrorDetails.value ? 'errorList' : null
// Ensure only one modal visible at a time.
showErrorDetails.value = false
showRequestDetails.value = false
showErrorModal.value = true
}
+// 从单条错误详情返回其来源列表,重新打开关联弹窗(保留筛选/分页状态)。
+function handleBackToList() {
+ const target = detailReturnTarget.value
+ resumeListState.value = true
+ if (target === 'requestList') {
+ showErrorModal.value = false
+ showErrorDetails.value = false
+ showRequestDetails.value = true
+ } else if (target === 'errorList') {
+ showErrorModal.value = false
+ showRequestDetails.value = false
+ showErrorDetails.value = true
+ }
+ detailReturnTarget.value = null
+ // 子组件 watch 在本次 show 变化中消费 resumeState 后复位,保证下次手动打开仍会重置筛选。
+ window.setTimeout(() => {
+ resumeListState.value = false
+ }, 0)
+}
+
function buildApiParams() {
const params: any = {
platform: platform.value || undefined,
diff --git a/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue b/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue
index 0275bfc117..c9849bc287 100644
--- a/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue
+++ b/frontend/src/views/admin/ops/components/OpsDashboardHeader.vue
@@ -2,6 +2,7 @@
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import Select from '@/components/common/Select.vue'
+import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'
import HelpTooltip from '@/components/common/HelpTooltip.vue'
import BaseDialog from '@/components/common/BaseDialog.vue'
import Icon from '@/components/icons/Icon.vue'
@@ -109,11 +110,7 @@ const groups = ref>([])
const platformOptions = computed(() => [
{ value: '', label: t('common.all') },
- { value: 'openai', label: 'OpenAI' },
- { value: 'anthropic', label: 'Anthropic' },
- { value: 'gemini', label: 'Gemini' },
- { value: 'antigravity', label: 'Antigravity' },
- { value: 'grok', label: 'Grok' }
+ ...CONCRETE_PLATFORM_OPTIONS
])
const timeRangeOptions = computed(() => [
diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue
index 348eba2979..8b0dc388f8 100644
--- a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue
+++ b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue
@@ -93,6 +93,15 @@
+
+
{{ t('admin.ops.errorDetail.upstreamStatus') }}
+
+
+ {{ detail.upstream_status_code ?? '—' }}
+
+
+
+
{{ t('admin.ops.errorDetail.requestType') }}
@@ -102,8 +111,8 @@
{{ t('admin.ops.errorDetail.message') }}
-
- {{ detail.message || '—' }}
+
+ {{ rootCauseMessage || '—' }}
@@ -116,10 +125,20 @@
-
+
+
{{ t('admin.ops.errorDetail.rootCause') }}
+
{{ rootCauseMessage }}
+
+
-
{{ t('admin.ops.errorDetail.responseBody') }}
-
{{ prettyJSON(primaryResponseBody || '') }}
+
{{ t('admin.ops.errorDetail.diagnosticPayloads') }}
+
{{ t('common.noData') }}
+
+
+
{{ diagnosticPayloadLabel(section.key) }}
+
{{ prettyJSON(section.value) }}
+
+
@@ -192,6 +211,16 @@
+
+
+ {{ t('admin.ops.errorDetail.backToList') }}
+
+
@@ -203,16 +232,18 @@ import Icon from '@/components/icons/Icon.vue'
import { useAppStore } from '@/stores'
import { opsAPI, type OpsErrorDetail } from '@/api/admin/ops'
import { formatDateTime } from '@/utils/format'
-import { resolvePrimaryResponseBody, resolveUpstreamPayload } from '../utils/errorDetailResponse'
+import { resolveUpstreamPayload } from '../utils/errorDetailResponse'
interface Props {
show: boolean
errorId: number | null
errorType?: 'request' | 'upstream'
+ backToList?: boolean
}
interface Emits {
(e: 'update:show', value: boolean): void
+ (e: 'back'): void
}
const props = defineProps
()
@@ -228,12 +259,41 @@ const showUpstreamList = computed(() => props.errorType === 'request')
const requestId = computed(() => detail.value?.request_id || detail.value?.client_request_id || '')
-const primaryResponseBody = computed(() => {
- return resolvePrimaryResponseBody(detail.value, props.errorType)
+type DiagnosticPayloadKey = 'client' | 'upstream_message' | 'upstream_detail' | 'upstream_events'
+
+const rootCauseMessage = computed(() => {
+ const current = detail.value
+ if (!current) return ''
+ for (const candidate of [current.upstream_error_message, current.upstream_error_detail, current.message, current.error_body]) {
+ const value = meaningfulPayload(candidate)
+ if (value) return value
+ }
+ return ''
})
+const diagnosticPayloadSections = computed(() => {
+ const current = detail.value
+ if (!current) return []
+ const candidates: Array<{ key: DiagnosticPayloadKey; value: string }> = [
+ { key: 'client', value: meaningfulPayload(current.error_body) },
+ { key: 'upstream_message', value: meaningfulPayload(current.upstream_error_message) },
+ { key: 'upstream_detail', value: meaningfulPayload(current.upstream_error_detail) },
+ { key: 'upstream_events', value: meaningfulPayload(current.upstream_errors) }
+ ]
+ return candidates.filter((section, index, all) => {
+ return section.value && all.findIndex(candidate => candidate.value === section.value) === index
+ })
+})
+function meaningfulPayload(candidate: unknown): string {
+ const value = String(candidate || '').trim()
+ if (!value || value === '[]' || value === '{}' || value.toLowerCase() === 'null') return ''
+ return value
+}
+function diagnosticPayloadLabel(key: DiagnosticPayloadKey): string {
+ return t(`admin.ops.errorDetail.payloads.${key}`)
+}
const title = computed(() => {
if (!props.errorId) return t('admin.ops.errorDetail.title')
@@ -315,6 +375,11 @@ function close() {
emit('update:show', false)
}
+function goBack() {
+ emit('update:show', false)
+ emit('back')
+}
+
function prettyJSON(raw?: string): string {
if (!raw) return 'N/A'
try {
@@ -358,12 +423,15 @@ watch(
{ immediate: true }
)
-const statusClass = computed(() => {
- const code = detail.value?.status_code ?? 0
+function statusBadgeClass(code: number): string {
if (code >= 500) return 'bg-red-50 text-red-700 ring-red-600/20 dark:bg-red-900/30 dark:text-red-400 dark:ring-red-500/30'
if (code === 429) return 'bg-purple-50 text-purple-700 ring-purple-600/20 dark:bg-purple-900/30 dark:text-purple-400 dark:ring-purple-500/30'
if (code >= 400) return 'bg-amber-50 text-amber-700 ring-amber-600/20 dark:bg-amber-900/30 dark:text-amber-400 dark:ring-amber-500/30'
return 'bg-gray-50 text-gray-700 ring-gray-600/20 dark:bg-gray-900/30 dark:text-gray-400 dark:ring-gray-500/30'
-})
+}
+
+const statusClass = computed(() => statusBadgeClass(detail.value?.status_code ?? 0))
+
+const upstreamStatusClass = computed(() => statusBadgeClass(detail.value?.upstream_status_code ?? 0))
diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue
index 0c513a5f1d..e97e919f6a 100644
--- a/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue
+++ b/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue
@@ -15,6 +15,7 @@ interface Props {
platform?: string
groupId?: number | null
errorType: 'request' | 'upstream'
+ resumeState?: boolean
}
const props = defineProps()
@@ -167,6 +168,7 @@ watch(
() => props.show,
(open) => {
if (!open) return
+ if (props.resumeState) return
page.value = 1
pageSize.value = 10
resetFilters()
diff --git a/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue b/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue
index 33ce058149..2d8e885a0c 100644
--- a/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue
+++ b/frontend/src/views/admin/ops/components/OpsRequestDetailsModal.vue
@@ -23,6 +23,7 @@ interface Props {
preset: OpsRequestDetailsPreset
platform?: string
groupId?: number | null
+ resumeState?: boolean
}
const props = defineProps()
@@ -98,6 +99,7 @@ watch(
() => props.modelValue,
(open) => {
if (open) {
+ if (props.resumeState) return
page.value = 1
pageSize.value = 10
fetchData()
@@ -142,7 +144,6 @@ async function handleCopyRequestId(requestId: string) {
function openErrorDetail(errorId: number | null | undefined) {
if (!errorId) return
- close()
emit('openErrorDetail', errorId)
}
diff --git a/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts
new file mode 100644
index 0000000000..188c150e07
--- /dev/null
+++ b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts
@@ -0,0 +1,79 @@
+import { flushPromises, shallowMount } from '@vue/test-utils'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import OpsErrorDetailModal from '../OpsErrorDetailModal.vue'
+
+const mocks = vi.hoisted(() => ({
+ getRequestErrorDetail: vi.fn(),
+ listRequestErrorUpstreamErrors: vi.fn()
+}))
+
+vi.mock('@/api/admin/ops', () => ({
+ opsAPI: {
+ getRequestErrorDetail: mocks.getRequestErrorDetail,
+ getUpstreamErrorDetail: vi.fn(),
+ listRequestErrorUpstreamErrors: mocks.listRequestErrorUpstreamErrors
+ }
+}))
+
+vi.mock('@/stores', () => ({
+ useAppStore: () => ({ showError: vi.fn() })
+}))
+
+vi.mock('vue-i18n', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ useI18n: () => ({ t: (key: string) => key })
+ }
+})
+
+describe('OpsErrorDetailModal', () => {
+ beforeEach(() => {
+ mocks.getRequestErrorDetail.mockReset()
+ mocks.listRequestErrorUpstreamErrors.mockReset()
+ mocks.listRequestErrorUpstreamErrors.mockResolvedValue({ items: [] })
+ })
+
+ it('prioritizes upstream root cause and deduplicates diagnostic payloads', async () => {
+ mocks.getRequestErrorDetail.mockResolvedValue({
+ id: 1,
+ created_at: '2026-08-19T00:00:00Z',
+ phase: 'request',
+ type: 'upstream_error',
+ error_owner: 'provider',
+ error_source: 'gateway',
+ severity: 'P1',
+ status_code: 502,
+ upstream_status_code: 429,
+ platform: 'openai',
+ model: 'gpt-5.6',
+ resolved: false,
+ request_id: 'rid-1',
+ message: 'All available accounts exhausted',
+ error_body: '{"error":"same"}',
+ upstream_error_message: 'provider rate limit exhausted',
+ upstream_error_detail: '{"error":"same"}',
+ upstream_errors: '[]',
+ account_name: 'account',
+ group_name: 'group',
+ is_business_limited: false
+ })
+
+ const wrapper = shallowMount(OpsErrorDetailModal, {
+ props: { show: true, errorId: 1, errorType: 'request' },
+ global: {
+ stubs: {
+ BaseDialog: { template: '
' },
+ Icon: true
+ }
+ }
+ })
+ await flushPromises()
+
+ expect(wrapper.text()).toContain('provider rate limit exhausted')
+ expect(wrapper.text()).toContain('admin.ops.errorDetail.upstreamStatus')
+ expect(wrapper.text()).toContain('429')
+ expect(wrapper.findAll('pre')).toHaveLength(2)
+ expect(wrapper.text()).not.toContain('admin.ops.errorDetail.payloads.upstream_detail')
+ })
+})
diff --git a/frontend/src/views/auth/RegisterView.vue b/frontend/src/views/auth/RegisterView.vue
index c4ccd9c98f..613ab4bd08 100644
--- a/frontend/src/views/auth/RegisterView.vue
+++ b/frontend/src/views/auth/RegisterView.vue
@@ -284,6 +284,7 @@
diff --git a/frontend/src/views/user/PaymentResultView.vue b/frontend/src/views/user/PaymentResultView.vue
index a5f32f0a8d..981377ce97 100644
--- a/frontend/src/views/user/PaymentResultView.vue
+++ b/frontend/src/views/user/PaymentResultView.vue
@@ -107,6 +107,7 @@ import {
readPaymentRecoverySnapshot,
} from '@/components/payment/paymentFlow'
import { usePaymentStore } from '@/stores/payment'
+import { useAuthStore } from '@/stores/auth'
import { paymentAPI } from '@/api/payment'
import type { PublicOrderVerifyResult } from '@/api/payment'
import type { OrderStatus, PaymentOrder } from '@/types/payment'
@@ -118,6 +119,7 @@ const { t } = i18n
const route = useRoute()
const router = useRouter()
const paymentStore = usePaymentStore()
+const authStore = useAuthStore()
type ResolvedOrder = PaymentOrder | PublicOrderVerifyResult
@@ -139,6 +141,7 @@ const STATUS_REFRESH_INTERVAL_MS = 2000
const STATUS_REFRESH_MAX_ATTEMPTS = 15
let statusRefreshTimer: ReturnType | null = null
+let userBalanceRefreshStarted = false
const refreshAttempts = ref(0)
/** 充值金额 = pay_amount / (1 + fee_rate/100),fee_rate=0 时等于 pay_amount */
@@ -197,6 +200,21 @@ function setResolvedOrder(nextOrder: ResolvedOrder | null): void {
if (nextOrder && 'currency' in nextOrder && nextOrder.currency) {
currency.value = normalizePaymentCurrency(nextOrder.currency)
}
+ refreshUserBalanceForSuccessfulOrder(nextOrder)
+}
+
+function refreshUserBalanceForSuccessfulOrder(nextOrder: ResolvedOrder | null): void {
+ if (!nextOrder || userBalanceRefreshStarted || normalizeOrderStatus(nextOrder.status) !== 'COMPLETED') {
+ return
+ }
+ if ('order_type' in nextOrder && nextOrder.order_type !== 'balance') {
+ return
+ }
+
+ userBalanceRefreshStarted = true
+ void authStore.refreshUser().catch(() => {
+ // The order result remains authoritative even if refreshing profile data fails.
+ })
}
function hasOrderId(nextOrder: ResolvedOrder | null): nextOrder is PaymentOrder {
diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue
index d836936a5a..70480d43a6 100644
--- a/frontend/src/views/user/UsageView.vue
+++ b/frontend/src/views/user/UsageView.vue
@@ -131,6 +131,7 @@
diff --git a/frontend/src/views/user/__tests__/PaymentResultView.spec.ts b/frontend/src/views/user/__tests__/PaymentResultView.spec.ts
index 5edae835c0..751e7d83c4 100644
--- a/frontend/src/views/user/__tests__/PaymentResultView.spec.ts
+++ b/frontend/src/views/user/__tests__/PaymentResultView.spec.ts
@@ -10,6 +10,7 @@ const pollOrderStatus = vi.hoisted(() => vi.fn())
const verifyOrder = vi.hoisted(() => vi.fn())
const verifyOrderPublic = vi.hoisted(() => vi.fn())
const resolveOrderPublicByResumeToken = vi.hoisted(() => vi.fn())
+const refreshUser = vi.hoisted(() => vi.fn())
vi.mock('vue-router', async () => {
const actual = await vi.importActual('vue-router')
@@ -36,6 +37,12 @@ vi.mock('@/stores/payment', () => ({
}),
}))
+vi.mock('@/stores/auth', () => ({
+ useAuthStore: () => ({
+ refreshUser,
+ }),
+}))
+
vi.mock('@/api/payment', () => ({
paymentAPI: {
verifyOrder,
@@ -91,6 +98,8 @@ describe('PaymentResultView', () => {
verifyOrder.mockReset()
verifyOrderPublic.mockReset()
resolveOrderPublicByResumeToken.mockReset()
+ refreshUser.mockReset()
+ refreshUser.mockResolvedValue({})
window.localStorage.clear()
})
@@ -171,7 +180,7 @@ describe('PaymentResultView', () => {
}))
resolveOrderPublicByResumeToken.mockResolvedValue({
data: {
- ...orderFactory('PAID'),
+ ...orderFactory('COMPLETED'),
amount: 100,
pay_amount: 103,
fee_rate: 3,
@@ -190,13 +199,14 @@ describe('PaymentResultView', () => {
expect(pollOrderStatus).not.toHaveBeenCalled()
expect(resolveOrderPublicByResumeToken).toHaveBeenCalledWith('resume-authoritative')
+ expect(refreshUser).toHaveBeenCalledTimes(1)
expect(wrapper.text()).toContain('payment.result.success')
expect(wrapper.text()).toContain('103.00')
expect(wrapper.text()).toContain('100.00')
expect(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY)).toBeNull()
})
- it('refreshes a pending resume-token result until the order becomes paid', async () => {
+ it('waits for completed fulfillment before refreshing the user balance', async () => {
vi.useFakeTimers()
routeState.query = {
resume_token: 'resume-77',
@@ -210,7 +220,7 @@ describe('PaymentResultView', () => {
data: orderFactory('PENDING'),
})
.mockResolvedValueOnce({
- data: orderFactory('PAID'),
+ data: orderFactory('COMPLETED'),
})
const wrapper = mount(PaymentResultView, {
@@ -224,6 +234,7 @@ describe('PaymentResultView', () => {
await flushPromises()
expect(resolveOrderPublicByResumeToken).toHaveBeenCalledTimes(1)
+ expect(refreshUser).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('payment.result.processing')
expect(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY)).not.toBeNull()
@@ -231,11 +242,36 @@ describe('PaymentResultView', () => {
await flushPromises()
expect(resolveOrderPublicByResumeToken).toHaveBeenCalledTimes(2)
+ expect(refreshUser).toHaveBeenCalledTimes(1)
expect(wrapper.text()).toContain('payment.result.success')
expect(wrapper.text()).not.toContain('payment.result.failed')
expect(window.localStorage.getItem(PAYMENT_RECOVERY_STORAGE_KEY)).toBeNull()
})
+ it('keeps the successful result when refreshing the user balance fails', async () => {
+ routeState.query = {
+ resume_token: 'resume-refresh-failure',
+ }
+ resolveOrderPublicByResumeToken.mockResolvedValue({
+ data: orderFactory('COMPLETED'),
+ })
+ refreshUser.mockRejectedValueOnce(new Error('profile refresh failed'))
+
+ const wrapper = mount(PaymentResultView, {
+ global: {
+ stubs: {
+ OrderStatusBadge: true,
+ },
+ },
+ })
+
+ await flushPromises()
+
+ expect(refreshUser).toHaveBeenCalledTimes(1)
+ expect(wrapper.text()).toContain('payment.result.success')
+ expect(wrapper.text()).not.toContain('payment.result.failed')
+ })
+
it('falls back to order_id polling when resume-token recovery fails', async () => {
routeState.query = {
resume_token: 'resume-fail',