Merge pull request #4385 from yardbirds0/feat/upstream-billing-probe

feat: 增加上游 Sub2API 计费倍率探测与账号展示
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-07-16 10:27:45 +08:00
commit ab978e615e
49 files changed
+5747 -74

No files matched your search

+141 -1
View File
@@ -132,6 +132,41 @@
<span class="flex-1 text-left">{{ t('admin.tlsFingerprintProfiles.title') }}</span>
</button>
<div class="my-2 border-t border-gray-100 dark:border-gray-700"></div>
<div class="space-y-2 px-3 py-2">
<div class="flex items-center justify-between gap-3">
<span class="text-sm font-medium text-gray-700 dark:text-gray-200">
{{ t('admin.accounts.upstreamBilling.autoProbeSettings') }}
</span>
<Toggle
v-model="upstreamBillingProbeSettings.enabled"
:aria-label="t('admin.accounts.upstreamBilling.autoProbeSettings')"
/>
</div>
<div class="flex items-center gap-2">
<label class="flex-1 text-xs text-gray-500 dark:text-gray-400" for="upstream-billing-probe-interval">
{{ t('admin.accounts.upstreamBilling.intervalMinutes') }}
</label>
<input
id="upstream-billing-probe-interval"
v-model.number="upstreamBillingProbeSettings.interval_minutes"
type="number"
min="5"
max="1440"
class="input h-8 w-20 px-2 text-sm"
/>
<button
type="button"
class="btn btn-secondary h-8 px-2"
:disabled="upstreamBillingSettingsLoading || upstreamBillingSettingsSaving"
:title="t('common.save')"
@click="saveUpstreamBillingProbeSettings"
>
<Icon name="check" size="sm" />
</button>
</div>
</div>
<div class="my-2 border-t border-gray-100 dark:border-gray-700"></div>
<div class="px-2 py-2">
<div class="flex items-center justify-between gap-3">
@@ -177,6 +212,7 @@
@delete="handleBulkDelete"
@reset-status="handleBulkResetStatus"
@refresh-token="handleBulkRefreshToken"
@probe-upstream-billing="handleBulkProbeUpstreamBilling"
@edit-selected="openBulkEditSelected"
@edit-filtered="openBulkEditFiltered"
@clear="clearSelection"
@@ -321,6 +357,21 @@
{{ (row.rate_multiplier ?? 1).toFixed(2) }}x
</span>
</template>
<template #header-upstream_billing_rate="{ column }">
<div class="flex items-center">
<span>{{ column.label }}</span>
<HelpTooltip :content="t('admin.accounts.upstreamBilling.trustWarning')" width-class="w-80" />
</div>
</template>
<template #cell-upstream_billing_rate="{ row }">
<UpstreamBillingRateCell
:account="row"
:interval-minutes="upstreamBillingProbeSettings.interval_minutes"
:now="upstreamBillingNow"
:probing="probingUpstreamBilling.has(row.id)"
@probe="handleProbeUpstreamBilling(row)"
/>
</template>
<template #cell-priority="{ value }">
<span class="text-sm text-gray-700 dark:text-gray-300">{{ value }}</span>
</template>
@@ -441,6 +492,7 @@ import AppLayout from '@/components/layout/AppLayout.vue'
import TablePageLayout from '@/components/layout/TablePageLayout.vue'
import DataTable from '@/components/common/DataTable.vue'
import HelpTooltip from '@/components/common/HelpTooltip.vue'
import Toggle from '@/components/common/Toggle.vue'
import Pagination from '@/components/common/Pagination.vue'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'
import { CreateAccountModal, EditAccountModal, BulkEditAccountModal, SyncFromCrsModal, TempUnschedStatusModal } from '@/components/account'
@@ -459,6 +511,7 @@ import AccountUsageCell from '@/components/account/AccountUsageCell.vue'
import AccountTodayStatsCell from '@/components/account/AccountTodayStatsCell.vue'
import AccountGroupsCell from '@/components/account/AccountGroupsCell.vue'
import AccountCapacityCell from '@/components/account/AccountCapacityCell.vue'
import UpstreamBillingRateCell from '@/components/account/UpstreamBillingRateCell.vue'
import PlatformTypeBadge from '@/components/common/PlatformTypeBadge.vue'
import Icon from '@/components/icons/Icon.vue'
import ErrorPassthroughRulesModal from '@/components/admin/ErrorPassthroughRulesModal.vue'
@@ -466,7 +519,8 @@ import TLSFingerprintProfilesModal from '@/components/admin/TLSFingerprintProfil
import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh'
import { formatDateTime, formatRelativeTime } from '@/utils/format'
import { proxyExpiryBadgeClass, proxyExpiryLabelKey } from '@/utils/proxyExpiry'
import type { Account, AccountPlatform, AccountSchedulerGroupScore, AccountType, Proxy as AccountProxy, AdminGroup, WindowStats, ClaudeModel } from '@/types'
import { extractApiErrorMessage } from '@/utils/apiError'
import type { Account, AccountPlatform, AccountSchedulerGroupScore, AccountType, Proxy as AccountProxy, AdminGroup, WindowStats, ClaudeModel, UpstreamBillingProbeSettings, UpstreamBillingProbeSnapshot } from '@/types'
const { t } = useI18n()
const appStore = useAppStore()
@@ -544,6 +598,15 @@ const scheduleModelOptions = ref<SelectOption[]>([])
const togglingSchedulable = ref<number | null>(null)
const menu = reactive<{show:boolean, acc:Account|null, pos:{top:number, left:number}|null}>({ show: false, acc: null, pos: null })
const exportingData = ref(false)
const upstreamBillingProbeSettings = reactive<UpstreamBillingProbeSettings>({
enabled: true,
interval_minutes: 30
})
const upstreamBillingSettingsLoading = ref(false)
const upstreamBillingSettingsSaving = ref(false)
const probingUpstreamBilling = reactive(new Set<number>())
const upstreamBillingNow = ref(Date.now())
useIntervalFn(() => { upstreamBillingNow.value = Date.now() }, 60_000)
// Account tools dropdown
const showAccountToolsDropdown = ref(false)
@@ -1113,6 +1176,31 @@ const openTLSFingerprintProfiles = () => {
showTLSFingerprintProfiles.value = true
}
const loadUpstreamBillingProbeSettings = async () => {
upstreamBillingSettingsLoading.value = true
try {
Object.assign(upstreamBillingProbeSettings, await adminAPI.accounts.getUpstreamBillingProbeSettings())
} catch (error) {
console.error('Failed to load upstream billing probe settings:', error)
} finally {
upstreamBillingSettingsLoading.value = false
}
}
const saveUpstreamBillingProbeSettings = async () => {
upstreamBillingSettingsSaving.value = true
try {
const saved = await adminAPI.accounts.updateUpstreamBillingProbeSettings({ ...upstreamBillingProbeSettings })
Object.assign(upstreamBillingProbeSettings, saved)
appStore.showSuccess(t('admin.accounts.upstreamBilling.settingsSaved'))
} catch (error) {
console.error('Failed to save upstream billing probe settings:', error)
appStore.showError(extractApiErrorMessage(error, t('admin.accounts.upstreamBilling.settingsFailed')))
} finally {
upstreamBillingSettingsSaving.value = false
}
}
const syncPendingListChanges = async () => {
hasPendingListSync.value = false
await load()
@@ -1282,6 +1370,7 @@ const allColumns = computed(() => {
{ key: 'priority', label: t('admin.accounts.columns.priority'), sortable: true },
{ key: 'scheduler_score', label: t('admin.accounts.columns.schedulerScore'), sortable: false },
{ key: 'rate_multiplier', label: t('admin.accounts.columns.billingRateMultiplier'), sortable: true },
{ key: 'upstream_billing_rate', label: t('admin.accounts.columns.upstreamBillingRate'), sortable: false },
{ key: 'last_used_at', label: t('admin.accounts.columns.lastUsed'), sortable: true },
{ key: 'created_at', label: t('admin.accounts.columns.createdAt'), sortable: true },
{ key: 'expires_at', label: t('admin.accounts.columns.expiresAt'), sortable: true },
@@ -1392,6 +1481,35 @@ const handleBulkRefreshToken = async () => {
appStore.showError(String(error))
}
}
const handleBulkProbeUpstreamBilling = async () => {
const accountIDs = [...selIds.value]
if (accountIDs.length === 0) {
appStore.showError(t('admin.accounts.upstreamBilling.noEligibleAccounts'))
return
}
if (accountIDs.length > 20) {
appStore.showError(t('admin.accounts.upstreamBilling.batchLimit'))
return
}
accountIDs.forEach(id => probingUpstreamBilling.add(id))
try {
const results = await adminAPI.accounts.probeUpstreamBillingBatch(accountIDs)
results.forEach(result => {
if (result.snapshot) patchUpstreamBillingSnapshot(result.account_id, result.snapshot)
})
const failed = results.filter(result => result.error).length
if (failed > 0) {
appStore.showError(t('admin.accounts.upstreamBilling.batchPartial', { success: results.length - failed, failed }))
} else {
appStore.showSuccess(t('admin.accounts.upstreamBilling.batchCompleted', { count: results.length }))
}
} catch (error) {
console.error('Failed to probe upstream billing in batch:', error)
appStore.showError(extractApiErrorMessage(error, t('admin.accounts.upstreamBilling.probeFailed')))
} finally {
accountIDs.forEach(id => probingUpstreamBilling.delete(id))
}
}
const updateSchedulableInList = (accountIds: number[], schedulable: boolean) => {
if (accountIds.length === 0) return
const idSet = new Set(accountIds)
@@ -1641,6 +1759,27 @@ const patchAccountInList = (updatedAccount: Account) => {
accounts.value = nextAccounts
syncAccountRefs(mergedAccount)
}
const patchUpstreamBillingSnapshot = (accountID: number, snapshot: UpstreamBillingProbeSnapshot) => {
const account = accounts.value.find(item => item.id === accountID)
if (!account) return
patchAccountInList({
...account,
extra: { ...account.extra, upstream_billing_probe: snapshot }
})
}
const handleProbeUpstreamBilling = async (account: Account) => {
if (probingUpstreamBilling.has(account.id)) return
probingUpstreamBilling.add(account.id)
try {
const result = await adminAPI.accounts.probeUpstreamBilling(account.id)
if (result.snapshot) patchUpstreamBillingSnapshot(account.id, result.snapshot)
} catch (error) {
console.error('Failed to probe upstream billing:', error)
appStore.showError(extractApiErrorMessage(error, t('admin.accounts.upstreamBilling.probeFailed')))
} finally {
probingUpstreamBilling.delete(account.id)
}
}
const handleAccountUpdated = (updatedAccount: Account) => {
patchAccountInList(updatedAccount)
enterAutoRefreshSilentWindow()
@@ -1885,6 +2024,7 @@ const handleClickOutside = (event: MouseEvent) => {
onMounted(async () => {
load()
loadUpstreamBillingProbeSettings()
try {
const [p, g] = await Promise.all([adminAPI.proxies.getAll(), adminAPI.groups.getAll()])
proxies.value = p
@@ -8,13 +8,15 @@ const {
listWithEtag,
getBatchTodayStats,
getAllProxies,
getAllGroups
getAllGroups,
probeUpstreamBillingBatch
} = vi.hoisted(() => ({
listAccounts: vi.fn(),
listWithEtag: vi.fn(),
getBatchTodayStats: vi.fn(),
getAllProxies: vi.fn(),
getAllGroups: vi.fn()
getAllGroups: vi.fn(),
probeUpstreamBillingBatch: vi.fn()
}))
vi.mock('@/api/admin', () => ({
@@ -23,9 +25,11 @@ vi.mock('@/api/admin', () => ({
list: listAccounts,
listWithEtag,
getBatchTodayStats,
getUpstreamBillingProbeSettings: vi.fn().mockResolvedValue({ enabled: true, interval_minutes: 30 }),
delete: vi.fn(),
batchClearError: vi.fn(),
batchRefresh: vi.fn(),
probeUpstreamBillingBatch,
toggleSchedulable: vi.fn()
},
proxies: {
@@ -67,6 +71,7 @@ const DataTableStub = {
<div data-test="data-table">
<span v-for="column in columns" :key="column.key" data-test="column-key">{{ column.key }}</span>
<div v-for="row in data" :key="row.id">
<div data-test="select-row"><slot name="cell-select" :row="row" /></div>
<slot name="cell-created_at" :value="row.created_at" :row="row" />
</div>
</div>
@@ -75,8 +80,18 @@ const DataTableStub = {
const AccountBulkActionsBarStub = {
props: ['selectedIds'],
emits: ['edit-filtered'],
template: '<button data-test="edit-filtered" @click="$emit(\'edit-filtered\')">edit filtered</button>'
emits: ['edit-filtered', 'probe-upstream-billing'],
template: `
<div>
<button data-test="edit-filtered" @click="$emit('edit-filtered')">edit filtered</button>
<button data-test="probe-upstream-billing" @click="$emit('probe-upstream-billing')">probe</button>
</div>
`
}
const PaginationStub = {
emits: ['update:page'],
template: '<button data-test="next-page" @click="$emit(\'update:page\', 2)">next</button>'
}
const BulkEditAccountModalStub = {
@@ -93,6 +108,7 @@ describe('admin AccountsView bulk edit scope', () => {
getBatchTodayStats.mockReset()
getAllProxies.mockReset()
getAllGroups.mockReset()
probeUpstreamBillingBatch.mockReset()
listAccounts.mockResolvedValue({
items: [],
@@ -109,6 +125,7 @@ describe('admin AccountsView bulk edit scope', () => {
getBatchTodayStats.mockResolvedValue({ stats: {} })
getAllProxies.mockResolvedValue([])
getAllGroups.mockResolvedValue([])
probeUpstreamBillingBatch.mockResolvedValue([])
})
it('opens bulk edit in filtered-results mode from the bulk actions dropdown', async () => {
@@ -224,4 +241,65 @@ describe('admin AccountsView bulk edit scope', () => {
sortable: true
})
})
it('submits selected account IDs from every page for backend eligibility checks', async () => {
const account = (id: number) => ({
id,
name: `account-${id}`,
platform: 'openai',
type: 'apikey',
status: 'active',
schedulable: true,
created_at: '2026-07-13T00:00:00Z',
updated_at: '2026-07-13T00:00:00Z'
})
listAccounts
.mockResolvedValueOnce({ items: [account(7)], total: 2, page: 1, page_size: 1, pages: 2 })
.mockResolvedValueOnce({ items: [account(11)], total: 2, page: 2, page_size: 1, pages: 2 })
const wrapper = mount(AccountsView, {
global: {
stubs: {
AppLayout: { template: '<div><slot /></div>' },
TablePageLayout: { template: '<div><slot name="table" /><slot name="pagination" /></div>' },
DataTable: DataTableStub,
Pagination: PaginationStub,
ConfirmDialog: true,
AccountTableActions: true,
AccountTableFilters: true,
AccountBulkActionsBar: AccountBulkActionsBarStub,
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: BulkEditAccountModalStub,
PlatformTypeBadge: true,
AccountCapacityCell: true,
AccountStatusIndicator: true,
AccountTodayStatsCell: true,
AccountGroupsCell: true,
AccountUsageCell: true,
Icon: true
}
}
})
await flushPromises()
await wrapper.get('[data-test="select-row"] input').trigger('change')
await wrapper.get('[data-test="next-page"]').trigger('click')
await flushPromises()
await wrapper.get('[data-test="select-row"] input').trigger('change')
await wrapper.get('[data-test="probe-upstream-billing"]').trigger('click')
await flushPromises()
expect(probeUpstreamBillingBatch).toHaveBeenCalledWith([7, 11])
})
})
@@ -23,6 +23,7 @@ vi.mock('@/api/admin', () => ({
list: listAccounts,
listWithEtag,
getBatchTodayStats,
getUpstreamBillingProbeSettings: vi.fn().mockResolvedValue({ enabled: true, interval_minutes: 30 }),
delete: vi.fn(),
batchClearError: vi.fn(),
batchRefresh: vi.fn(),
@@ -37,6 +37,7 @@ vi.mock('@/api/admin', () => ({
listWithEtag,
getBatchTodayStats,
duplicate: duplicateAccount,
getUpstreamBillingProbeSettings: vi.fn().mockResolvedValue({ enabled: true, interval_minutes: 30 }),
createSparkShadow,
delete: vi.fn(),
batchClearError: vi.fn(),
@@ -23,6 +23,7 @@ vi.mock('@/api/admin', () => ({
list: listAccounts,
listWithEtag,
getBatchTodayStats,
getUpstreamBillingProbeSettings: vi.fn().mockResolvedValue({ enabled: true, interval_minutes: 30 }),
delete: vi.fn(),
batchClearError: vi.fn(),
batchRefresh: vi.fn(),
@@ -70,6 +71,9 @@ const DataTableStub = {
<div v-if="column.key === 'usage'" data-test="usage-header">
<slot :name="'header-' + column.key" :column="column" />
</div>
<div v-if="column.key === 'upstream_billing_rate'" data-test="upstream-billing-header">
<slot :name="'header-' + column.key" :column="column" />
</div>
</template>
</div>
`
@@ -161,4 +165,16 @@ describe('admin AccountsView usage windows hint', () => {
expect(hint.exists()).toBe(true)
expect(hint.text()).toBe('admin.accounts.usageWindowsHint')
})
it('renders the upstream billing trust warning next to the declared-rate column', async () => {
const wrapper = mountView()
await flushPromises()
const header = wrapper.find('[data-test="upstream-billing-header"]')
expect(header.exists()).toBe(true)
expect(header.text()).toContain('admin.accounts.columns.upstreamBillingRate')
expect(wrapper.findAll('[data-test="usage-windows-hint"]').some(node =>
node.text() === 'admin.accounts.upstreamBilling.trustWarning'
)).toBe(true)
})
})