Merge pull request #9135 from NDCCCCCC/pr/account-threshold-ui

feat(accounts): 让所有受支持平台都能配置账号级自动停调阈值
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-12-02 12:35:21 +08:00
commit 4cfeeb2396
6 files changed
+313 -1

No files matched your search

@@ -581,6 +581,40 @@
</div>
</div>
<!-- 账号级自动停调阈值覆盖(可选):留空/100 表示跟随系统平台阈值 -->
<div
v-if="supportsCreateSchedulingThresholdOverride"
class="border-t border-gray-200 pt-4 dark:border-dark-600"
data-testid="create-account-scheduling-threshold"
>
<div class="mb-2 flex items-center justify-between">
<div>
<label class="input-label mb-0">{{ t('admin.accounts.accountSchedulingThresholdOverride') }}</label>
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.accounts.cnProviders.schedulingThresholdCreateHint') }}
</p>
</div>
<input
v-model="createSchedulingThresholdOverrideEnabled"
data-testid="create-account-scheduling-threshold-enabled"
type="checkbox"
class="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
/>
</div>
<div v-if="createSchedulingThresholdOverrideEnabled">
<label class="input-label">{{ t('admin.accounts.accountSchedulingThresholdOverrideValue') }}</label>
<input
v-model.number="createSchedulingThresholdOverrideValue"
data-testid="create-account-scheduling-threshold-value"
type="number"
min="1"
max="100"
class="input"
/>
<p class="input-hint">{{ t('admin.accounts.accountSchedulingThresholdOverrideDisabledHint') }}</p>
</div>
</div>
<!-- Account Mode Selection (providers using the generic form) -->
<div v-if="isGenericMultiProtocolPlatform && genericAccountModes.length > 1" data-testid="generic-account-mode">
<label class="input-label">{{ t('admin.accounts.cnProviders.accountMode.title') }}</label>
@@ -4151,6 +4185,7 @@ import {
isValidWildcardPattern
} from '@/composables/useModelWhitelist'
import { adminAPI } from '@/api/admin'
import { SCHEDULING_THRESHOLD_PLATFORMS } from '@/api/admin/settings'
import { useQuotaNotifyState } from '@/composables/useQuotaNotifyState'
import {
useAccountOAuth,
@@ -4466,6 +4501,28 @@ const isGenericMultiProtocolPlatform = computed(
const extraMultiProtocolPlatforms = computed(() =>
listPlatforms().filter(spec => !!spec.multi_protocol && !isCNProviderPlatform(spec.id) && spec.id !== 'opencode_go')
)
// 账号级自动停调阈值覆盖(创建时可选):写入 credentials.account_scheduling_threshold。
// 仅对后端白名单平台显示;关闭/留空 = 跟随系统平台阈值。
const ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY = 'account_scheduling_threshold'
const createSchedulingThresholdOverrideEnabled = ref(false)
const createSchedulingThresholdOverrideValue = ref(100)
// handleSubmit 中走到通用 apikey 创建分支的条件:其余分支(OAuth 流程、Bedrock、
// Antigravity upstream、service_account)都会先行返回,不会写入阈值。
const submitsViaGenericApiKeyPath = computed(
() =>
!isOAuthFlow.value &&
!(form.platform === 'anthropic' && accountCategory.value === 'bedrock') &&
!(form.platform === 'antigravity' && antigravityAccountType.value === 'upstream') &&
!(
(form.platform === 'gemini' || form.platform === 'anthropic') &&
accountCategory.value === 'service_account'
)
)
const supportsCreateSchedulingThresholdOverride = computed(
() =>
(SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(form.platform) &&
submitsViaGenericApiKeyPath.value
)
const genericAccountModes = computed(() => providerAccountModes(form.platform))
// 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。
const routesByModel = computed(() => providerRoutesByModel(form.platform))
@@ -5692,6 +5749,8 @@ const resetForm = () => {
upstreamRequestIdHeader.value = ''
upstreamBillingAutoProbeEnabled.value = true
upstreamGroupSyncEnabled.value = false
createSchedulingThresholdOverrideEnabled.value = false
createSchedulingThresholdOverrideValue.value = 100
editQuotaLimit.value = null
editQuotaDailyLimit.value = null
editQuotaWeeklyLimit.value = null
@@ -6228,6 +6287,17 @@ const handleSubmit = async () => {
}
}
// 账号级自动停调阈值覆盖:仅白名单平台、勾选且值在 1..99 时写入
// (100 = 禁用当前账号自动停调,不写则跟随系统平台阈值)。
if (
supportsCreateSchedulingThresholdOverride.value &&
createSchedulingThresholdOverrideEnabled.value
) {
const numeric = Math.trunc(Number(createSchedulingThresholdOverrideValue.value) || 100)
const clamped = Math.min(100, Math.max(1, numeric))
credentials[ACCOUNT_SCHEDULING_THRESHOLD_CREDENTIAL_KEY] = clamped
}
// Add model mapping if configured(OpenAI 开启自动透传时不应用)
if (!isOpenAIModelRestrictionDisabled.value) {
const modelMapping = buildModelMappingObject(modelRestrictionMode.value, allowedModels.value, modelMappings.value)
@@ -3409,6 +3409,7 @@ import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { adminAPI } from '@/api/admin'
import { SCHEDULING_THRESHOLD_PLATFORMS } from '@/api/admin/settings'
import { useQuotaNotifyState } from '@/composables/useQuotaNotifyState'
import type {
Account,
@@ -5340,7 +5341,10 @@ const applyTempUnschedConfig = (credentials: Record<string, unknown>) => {
function supportsAccountSchedulingThresholdOverridePlatform(platform: Account['platform'] | undefined) {
return platform === 'openai' || platform === 'anthropic' || platform === 'grok'
// 与后端 AllowedSchedulingThresholdPlatforms 共用同一清单(系统设置页也用这份),
// 避免前端入口与后端白名单再次漂移。
if (!platform) return false
return (SCHEDULING_THRESHOLD_PLATFORMS as readonly string[]).includes(platform)
}
function normalizeAccountSchedulingThresholdOverride(value: unknown): number | null {
@@ -533,6 +533,53 @@ describe('CreateAccountModal OpenAI long-context billing', () => {
expect(probeUpstreamBillingMock).not.toHaveBeenCalled()
})
describe('account scheduling threshold override', () => {
const toggleSelector = '[data-testid="create-account-scheduling-threshold"]'
const enabledSelector = '[data-testid="create-account-scheduling-threshold-enabled"]'
const valueSelector = '[data-testid="create-account-scheduling-threshold-value"]'
it('is hidden for OAuth-based creation, which never writes the threshold', async () => {
const wrapper = mountModal()
await selectButtonByText(wrapper, 'OpenAI')
expect(wrapper.find(toggleSelector).exists()).toBe(false)
await selectButtonByText(wrapper, 'API Key')
expect(wrapper.find(toggleSelector).exists()).toBe(true)
})
it('writes the threshold into credentials for API key accounts', async () => {
const wrapper = mountModal()
await selectButtonByText(wrapper, 'OpenAI')
await selectButtonByText(wrapper, 'API Key')
await wrapper.get(enabledSelector).setValue(true)
await wrapper.get(valueSelector).setValue(80)
await wrapper.get('form#create-account-form input[type="text"]').setValue('threshold account')
await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key')
await wrapper.get('form#create-account-form').trigger('submit.prevent')
await flushPromises()
expect(createAccountMock).toHaveBeenCalledTimes(1)
expect(createAccountMock.mock.calls[0]?.[0]?.credentials?.account_scheduling_threshold).toBe(80)
})
it('does not carry the previous value over to the next created account', async () => {
const wrapper = mountModal()
await selectButtonByText(wrapper, 'OpenAI')
await selectButtonByText(wrapper, 'API Key')
await wrapper.get(enabledSelector).setValue(true)
await wrapper.get(valueSelector).setValue(80)
await wrapper.setProps({ show: false })
await wrapper.setProps({ show: true })
await selectButtonByText(wrapper, 'OpenAI')
await selectButtonByText(wrapper, 'API Key')
expect((wrapper.get(enabledSelector).element as HTMLInputElement).checked).toBe(false)
await wrapper.get(enabledSelector).setValue(true)
expect((wrapper.get(valueSelector).element as HTMLInputElement).value).toBe('100')
})
})
it('submits OpenCode Zen default protocol rules with adaptive endpoints', async () => {
const wrapper = mountModal()
await selectButtonByText(wrapper, 'OpenCode')
@@ -0,0 +1,189 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
// 账号级自动停调阈值覆盖:GLM / MiniMax / OpenCode / Command Code 等
// 套餐平台现在都能在账号编辑页设置该覆盖(此前仅 openai/anthropic/grok)。
const { updateAccountMock, checkMixedChannelRiskMock, authIsSimpleMode } = vi.hoisted(() => ({
updateAccountMock: vi.fn(),
checkMixedChannelRiskMock: vi.fn(),
authIsSimpleMode: { value: true }
}))
vi.mock('@/stores/app', () => ({
useAppStore: () => ({
showError: vi.fn(),
showSuccess: vi.fn(),
showInfo: vi.fn()
})
}))
vi.mock('@/stores/auth', () => ({
useAuthStore: () => ({
get isSimpleMode() {
return authIsSimpleMode.value
}
})
}))
vi.mock('@/api/admin', () => ({
adminAPI: {
accounts: {
update: updateAccountMock,
checkMixedChannelRisk: checkMixedChannelRiskMock,
previewUpstreamGroup: vi.fn()
},
settings: {
getWebSearchEmulationConfig: vi.fn().mockResolvedValue({ enabled: false, providers: [] }),
getSettings: vi.fn().mockResolvedValue({})
},
tlsFingerprintProfiles: {
list: vi.fn().mockResolvedValue([])
}
}
}))
vi.mock('@/api/admin/accounts', () => ({
getAntigravityDefaultModelMapping: vi.fn()
}))
vi.mock('vue-i18n', async () => {
const actual = await vi.importActual<typeof import('vue-i18n')>('vue-i18n')
return {
...actual,
useI18n: () => ({ t: (key: string) => key })
}
})
import EditAccountModal from '../EditAccountModal.vue'
const BaseDialogStub = defineComponent({
name: 'BaseDialog',
props: { show: { type: Boolean, default: false } },
template: '<div v-if="show"><slot /><slot name="footer" /></div>'
})
const GroupSelectorStub = defineComponent({
name: 'GroupSelector',
props: { modelValue: { type: Array, default: () => [] } },
emits: ['update:modelValue'],
template: '<div data-testid="group-selector" />'
})
const ModelWhitelistSelectorStub = defineComponent({
name: 'ModelWhitelistSelector',
props: { modelMappings: { type: Array, default: () => [] }, modelValue: { type: Array, default: () => [] } },
emits: ['update:modelValue'],
template: '<div />'
})
const SelectStub = defineComponent({
name: 'SelectStub',
props: {
modelValue: { type: [String, Number, Boolean, null], default: '' },
options: { type: Array, default: () => [] }
},
emits: ['update:modelValue'],
template: `
<select v-bind="$attrs" :value="modelValue" @change="$emit('update:modelValue', $event.target.value)">
<option v-for="option in options" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
`
})
function buildAccount(platform: string, credentials: Record<string, unknown> = {}) {
return {
id: 1,
name: `account-${platform}`,
notes: '',
platform,
type: 'apikey',
credentials: { api_key: 'key-test', base_url: '', ...credentials },
extra: {},
proxy_id: null,
concurrency: 1,
priority: 1,
rate_multiplier: 1,
status: 'active',
group_ids: [],
expires_at: null,
auto_pause_on_expired: false
} as any
}
function mountModal(account: any) {
return mount(EditAccountModal, {
props: { show: true, account, proxies: [], groups: [] },
global: {
stubs: {
BaseDialog: BaseDialogStub,
Select: SelectStub,
Icon: true,
ProxySelector: true,
GroupSelector: GroupSelectorStub,
ModelWhitelistSelector: ModelWhitelistSelectorStub
}
}
})
}
describe('EditAccountModal 账号自动停调阈值覆盖(套餐平台)', () => {
beforeEach(() => {
authIsSimpleMode.value = true
updateAccountMock.mockReset()
checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false })
})
it.each(['zhipu', 'minimax', 'opencode_go', 'command_code'])(
'%s 账号显示阈值覆盖区块并能提交 account_scheduling_threshold',
async (platform) => {
const account = buildAccount(platform, {
account_mode: platform === 'zhipu' ? 'coding' : 'payg'
})
updateAccountMock.mockResolvedValue(account)
const wrapper = mountModal(account)
expect(wrapper.find('[data-testid="account-scheduling-threshold-section"]').exists()).toBe(true)
await wrapper.get('[data-testid="account-scheduling-threshold-override-enabled"]').setValue(true)
await wrapper.get('[data-testid="account-scheduling-threshold-override-value"]').setValue('50')
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
await flushPromises()
expect(updateAccountMock).toHaveBeenCalledTimes(1)
expect(updateAccountMock.mock.calls[0]?.[1]?.credentials?.account_scheduling_threshold).toBe(50)
wrapper.unmount()
}
)
it('deepseek(余额型)不显示阈值覆盖区块', async () => {
const account = buildAccount('deepseek', { account_mode: 'payg' })
updateAccountMock.mockResolvedValue(account)
const wrapper = mountModal(account)
expect(wrapper.find('[data-testid="account-scheduling-threshold-section"]').exists()).toBe(false)
wrapper.unmount()
})
it('关闭覆盖后把 account_scheduling_threshold 置空(回退系统阈值)', async () => {
const account = buildAccount('zhipu', {
account_mode: 'coding',
account_scheduling_threshold: 50
})
updateAccountMock.mockResolvedValue(account)
const wrapper = mountModal(account)
const enabled = wrapper.get<HTMLInputElement>('[data-testid="account-scheduling-threshold-override-enabled"]')
expect(enabled.element.checked).toBe(true)
const value = wrapper.get<HTMLInputElement>('[data-testid="account-scheduling-threshold-override-value"]')
expect(value.element.value).toBe('50')
await enabled.setValue(false)
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
await flushPromises()
expect(updateAccountMock).toHaveBeenCalledTimes(1)
expect(updateAccountMock.mock.calls[0]?.[1]?.credentials?.account_scheduling_threshold).toBeNull()
wrapper.unmount()
})
})
@@ -154,6 +154,7 @@ export default {
example: 'Example: …/organization/org-0610bE2D…/projects/proj_0798F20…/api_keys → org-0610bE2D… goes into "Organization ID", proj_0798F20… into "Project ID"',
},
},
schedulingThresholdCreateHint: 'Optional: override the platform auto-pause threshold for this account (upstream usage-window percent). Leave unchecked to follow the system setting.',
balance: 'Balance --',
window5h: '5h',
windowWeekly: '7d',
@@ -367,6 +367,7 @@ export default {
example: '示例:…/organization/org-0610bE2D…/projects/proj_0798F20…/api_keys → org-0610bE2D… 填「组织 ID」,proj_0798F20… 填「项目 ID」',
},
},
schedulingThresholdCreateHint: '可选:为该账号覆盖平台级自动停调阈值(按上游原生窗口百分比)。不勾选则跟随系统设置。',
balance: '余额 --',
window5h: '5h',
windowWeekly: '7d',