feat(billing-probe): optionally sync account rate from upstream declared rate

Successful upstream billing probes already persist the upstream-declared
rate as a display-only snapshot. Add a per-account opt-in that writes
that declared rate back to the account's rate_multiplier, so the account
cost basis follows upstream repricing automatically instead of drifting
until an operator notices.

- new per-account flag upstream_billing_rate_sync_enabled stored next to
  the probe flag in account extra: enabling sync force-enables the
  probe, disabling the probe cascades sync off, and eligibility follows
  IsUpstreamBillingProbeIdentity (tightened from any non-empty platform
  to an explicit whitelist of the five supported API-key platforms so
  future platforms do not silently inherit probe/sync semantics)
- only a successful probe whose declared rate survives validation
  (finite, within bounds, not rounded to zero at the rate_multiplier
  decimal(10,4) scale) writes back; failed/unsupported/invalid probes
  leave rate_multiplier unchanged
- the writeback rides the existing snapshot CAS transaction:
  UpdateUpstreamBillingProbeSnapshot takes an optional rateMultiplier
  and applies it atomically with the snapshot under the same
  identity/snapshot compare-and-swap, so a probe result observed on a
  stale account cannot clobber a concurrent admin edit
- admin edit goes through UpdateWithAccountBillingSettings, which
  applies the form without overwriting a rate that a probe synchronized
  after the edit form was loaded (nil rateMultiplier = not edited);
  once sync is enabled the edit form shows the rate as managed
- bulk update rejects a manual rate_multiplier change when any target
  account has rate sync enabled (whole batch fails with a dedicated
  error so partial writes cannot bypass the sync ownership)
- frontend: sync toggle with hints in the edit modal (probe/sync
  enable/disable coupling enforced in the form), synced-rate tooltip on
  the rate cell, bulk edit modal warns and blocks rate edits that hit
  sync-enabled accounts; en/zh copy updated
- tests: service unit tests for sync gating/validation/cascade, sqlmock
  repo tests for the extended CAS, real-PostgreSQL integration tests
  (rate written only for successful+enabled accounts, manual rate
  protected after sync disabled, admin edit preserved across concurrent
  probe sync), handler/API contract updates, frontend specs for modal
  coupling, bulk rejection and rate cell
This commit is contained in:
Brisbanehuang
2026-08-01 22:11:09 +08:00
committed by shaw
parent 56f3d3c9b0
commit b0f5007f04
34 changed files with 1382 additions and 146 deletions
@@ -750,6 +750,14 @@
aria-labelledby="bulk-edit-rate-multiplier-label"
/>
<p class="input-hint">{{ t('admin.accounts.billingRateMultiplierHint') }}</p>
<p
v-if="enableRateMultiplier"
class="mt-2 flex items-start gap-1 text-xs text-amber-700 dark:text-amber-300"
data-testid="bulk-rate-sync-warning"
>
<Icon name="exclamationTriangle" size="xs" class="mt-0.5 flex-shrink-0" />
<span>{{ t('admin.accounts.bulkEdit.rateSyncWarning') }}</span>
</p>
</div>
</div>
@@ -1985,6 +1993,10 @@ const submitBulkUpdate = async (baseUpdates: Record<string, unknown>) => {
pendingUpdatesForConfirm.value = baseUpdates
mixedChannelWarningMessage.value = error.message
showMixedChannelWarning.value = true
} else if (error.reason === 'UPSTREAM_BILLING_RATE_SYNC_BULK_CONFLICT') {
appStore.showError(t('admin.accounts.bulkEdit.rateSyncConflict', {
count: error.metadata?.count ?? 1
}))
} else {
appStore.showError(error.message || t('admin.accounts.bulkEdit.failed'))
console.error('Error bulk updating accounts:', error)
@@ -1441,8 +1441,43 @@
</div>
<div>
<label class="input-label">{{ t('admin.accounts.billingRateMultiplier') }}</label>
<input v-model.number="form.rate_multiplier" type="number" min="0" step="0.001" class="input" />
<p class="input-hint">{{ t('admin.accounts.billingRateMultiplierHint') }}</p>
<input
v-model.number="form.rate_multiplier"
type="number"
min="0"
step="0.001"
class="input disabled:cursor-not-allowed disabled:opacity-60"
data-testid="account-rate-multiplier"
:disabled="upstreamBillingRateSyncEnabled"
/>
<p class="input-hint">
{{
t(
upstreamBillingRateSyncEnabled
? 'admin.accounts.upstreamBilling.syncRateManagedHint'
: 'admin.accounts.billingRateMultiplierHint'
)
}}
</p>
<div
v-if="account?.type === 'apikey'"
class="mt-3 flex items-center justify-between gap-3"
>
<div class="min-w-0">
<p class="text-xs font-medium text-gray-700 dark:text-gray-200">
{{ t('admin.accounts.upstreamBilling.syncRate') }}
</p>
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.accounts.upstreamBilling.syncRateHint') }}
</p>
</div>
<Toggle
:model-value="upstreamBillingRateSyncEnabled"
data-testid="upstream-billing-rate-sync"
:aria-label="t('admin.accounts.upstreamBilling.syncRate')"
@update:model-value="handleUpstreamBillingRateSyncChange"
/>
</div>
</div>
</div>
<div class="border-t border-gray-200 pt-4 dark:border-dark-600">
@@ -1660,9 +1695,10 @@
</p>
</div>
<Toggle
v-model="upstreamBillingAutoProbeEnabled"
:model-value="upstreamBillingAutoProbeEnabled"
data-testid="upstream-billing-auto-probe"
:aria-label="t('admin.accounts.upstreamBilling.autoProbe')"
@update:model-value="handleUpstreamBillingAutoProbeChange"
/>
</div>
@@ -2822,6 +2858,7 @@ const autoPause7dThreshold = ref<number | null>(null)
const autoPause5hDisabled = ref(false)
const autoPause7dDisabled = ref(false)
const upstreamBillingAutoProbeEnabled = ref(false)
const upstreamBillingRateSyncEnabled = ref(false)
const mixedScheduling = ref(false) // For antigravity accounts: enable mixed scheduling
const allowOverages = ref(false) // For antigravity accounts: enable AI Credits overages
const antigravityProjectId = ref('')
@@ -3191,6 +3228,20 @@ const form = reactive({
expires_at: null as number | null
})
const handleUpstreamBillingRateSyncChange = (enabled: boolean) => {
upstreamBillingRateSyncEnabled.value = enabled
if (enabled) {
upstreamBillingAutoProbeEnabled.value = true
}
}
const handleUpstreamBillingAutoProbeChange = (enabled: boolean) => {
upstreamBillingAutoProbeEnabled.value = enabled
if (!enabled) {
upstreamBillingRateSyncEnabled.value = false
}
}
const statusOptions = computed(() => {
const options = [
{ value: 'active', label: t('common.active') },
@@ -3306,6 +3357,8 @@ const syncFormFromAccount = (newAccount: Account | null) => {
autoPause5hDisabled.value = extra?.auto_pause_5h_disabled === true
autoPause7dDisabled.value = extra?.auto_pause_7d_disabled === true
upstreamBillingAutoProbeEnabled.value = extra?.upstream_billing_probe_enabled === true
upstreamBillingRateSyncEnabled.value =
upstreamBillingAutoProbeEnabled.value && extra?.upstream_billing_rate_sync_enabled === true
// Load OpenAI passthrough toggle (OpenAI OAuth/SetupToken/API Key)
openaiPassthroughEnabled.value = false
@@ -4086,6 +4139,13 @@ const handleSubmit = async () => {
updatePayload.load_factor = 0
}
updatePayload.auto_pause_on_expired = autoPauseOnExpired.value
if (props.account.type === 'apikey') {
updatePayload.upstream_billing_probe_enabled = upstreamBillingAutoProbeEnabled.value
updatePayload.upstream_billing_rate_sync_enabled = upstreamBillingRateSyncEnabled.value
if (upstreamBillingRateSyncEnabled.value) {
delete updatePayload.rate_multiplier
}
}
// For apikey type, handle credentials update
if (props.account.type === 'apikey') {
@@ -4651,7 +4711,8 @@ const handleSubmit = async () => {
// 上游倍率自动探测对全部 API-key 平台开放(sub2api 上游即可应答),
// Bedrock 凭证无静态 Key 不参与。
if (props.account.type === 'apikey') {
newExtra.upstream_billing_probe_enabled = upstreamBillingAutoProbeEnabled.value
delete newExtra.upstream_billing_probe_enabled
delete newExtra.upstream_billing_rate_sync_enabled
}
// Total quota
if (editQuotaLimit.value != null && editQuotaLimit.value > 0) {
@@ -88,6 +88,7 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import HelpTooltip from '@/components/common/HelpTooltip.vue'
import Icon from '@/components/icons/Icon.vue'
import { formatMultiplier } from '@/utils/formatters'
import type { Account, UpstreamBillingProbeSnapshot } from '@/types'
const props = withDefaults(defineProps<{
@@ -191,7 +192,7 @@ const elapsedSinceLastSuccess = computed(() => {
const effectiveRate = computed(() => {
if (!validTimestamps.value || stale.value || !['ok', 'failed'].includes(snapshot.value?.status ?? '')) return '-'
const value = currentEffectiveRate.value
return value == null ? '-' : `${Number(value.toPrecision(12))}x`
return value == null ? '-' : `${formatMultiplier(value)}x`
})
const statusLabel = computed(() => {
if (!snapshot.value) return t('admin.accounts.upstreamBilling.notProbed')
@@ -4,9 +4,13 @@ import BulkEditAccountModal from '../BulkEditAccountModal.vue'
import ModelWhitelistSelector from '../ModelWhitelistSelector.vue'
import { adminAPI } from '@/api/admin'
const { showError } = vi.hoisted(() => ({
showError: vi.fn()
}))
vi.mock('@/stores/app', () => ({
useAppStore: () => ({
showError: vi.fn(),
showError,
showSuccess: vi.fn(),
showInfo: vi.fn()
})
@@ -77,6 +81,7 @@ describe('BulkEditAccountModal', () => {
beforeEach(() => {
vi.mocked(adminAPI.accounts.bulkUpdate).mockReset()
vi.mocked(adminAPI.accounts.checkMixedChannelRisk).mockReset()
showError.mockReset()
vi.mocked(adminAPI.accounts.bulkUpdate).mockResolvedValue({
success: 2,
@@ -88,6 +93,33 @@ describe('BulkEditAccountModal', () => {
} as any)
})
it('批量修改倍率时提示自动同步账号需要先关闭同步', async () => {
const wrapper = mountModal()
expect(wrapper.find('[data-testid="bulk-rate-sync-warning"]').exists()).toBe(false)
await wrapper.get('#bulk-edit-rate-multiplier-enabled').setValue(true)
expect(wrapper.get('[data-testid="bulk-rate-sync-warning"]').text()).toContain(
'admin.accounts.bulkEdit.rateSyncWarning'
)
})
it('后端拒绝修改同步账号倍率时展示专用错误', async () => {
vi.mocked(adminAPI.accounts.bulkUpdate).mockRejectedValueOnce({
status: 409,
reason: 'UPSTREAM_BILLING_RATE_SYNC_BULK_CONFLICT',
metadata: { count: '2' },
message: 'conflict'
})
const wrapper = mountModal()
await wrapper.get('#bulk-edit-rate-multiplier-enabled').setValue(true)
await wrapper.get('#bulk-edit-account-form').trigger('submit.prevent')
await flushPromises()
expect(showError).toHaveBeenCalledWith('admin.accounts.bulkEdit.rateSyncConflict')
})
it('antigravity 白名单包含 Gemini 图片模型且过滤掉普通 GPT 模型', async () => {
const wrapper = mountModal()
const selector = wrapper.findComponent(ModelWhitelistSelector)
@@ -654,7 +654,10 @@ describe('EditAccountModal', () => {
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
expect(updateAccountMock).toHaveBeenCalledTimes(1)
expect(updateAccountMock.mock.calls[0]?.[1]?.extra?.upstream_billing_probe_enabled).toBe(true)
expect(updateAccountMock.mock.calls[0]?.[1]?.upstream_billing_probe_enabled).toBe(true)
expect(updateAccountMock.mock.calls[0]?.[1]?.extra).not.toHaveProperty(
'upstream_billing_probe_enabled'
)
})
it('exposes the upstream billing auto-probe toggle for non-OpenAI API-key accounts', async () => {
@@ -676,7 +679,92 @@ describe('EditAccountModal', () => {
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
expect(updateAccountMock).toHaveBeenCalledTimes(1)
expect(updateAccountMock.mock.calls[0]?.[1]?.extra?.upstream_billing_probe_enabled).toBe(true)
expect(updateAccountMock.mock.calls[0]?.[1]?.upstream_billing_probe_enabled).toBe(true)
})
it('enabling rate sync also enables probing and stops submitting a manual rate', async () => {
const account = buildAccount()
updateAccountMock.mockReset()
checkMixedChannelRiskMock.mockReset()
checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false })
updateAccountMock.mockResolvedValue(account)
const wrapper = mountModal(account)
const syncToggle = wrapper.get('[data-testid="upstream-billing-rate-sync"]')
const probeToggle = wrapper.get('[data-testid="upstream-billing-auto-probe"]')
const rateInput = wrapper.get<HTMLInputElement>('[data-testid="account-rate-multiplier"]')
expect(syncToggle.attributes('aria-checked')).toBe('false')
expect(probeToggle.attributes('aria-checked')).toBe('false')
expect(rateInput.element.disabled).toBe(false)
expect(wrapper.text()).toContain('admin.accounts.billingRateMultiplierHint')
expect(wrapper.text()).not.toContain('admin.accounts.upstreamBilling.syncRateManagedHint')
await syncToggle.trigger('click')
expect(syncToggle.attributes('aria-checked')).toBe('true')
expect(probeToggle.attributes('aria-checked')).toBe('true')
expect(rateInput.element.disabled).toBe(true)
expect(wrapper.text()).toContain('admin.accounts.upstreamBilling.syncRateManagedHint')
expect(wrapper.text()).not.toContain('admin.accounts.billingRateMultiplierHint')
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
const payload = updateAccountMock.mock.calls[0]?.[1]
expect(payload?.upstream_billing_probe_enabled).toBe(true)
expect(payload?.upstream_billing_rate_sync_enabled).toBe(true)
expect(payload).not.toHaveProperty('rate_multiplier')
})
it('disabling probing also disables rate sync and restores manual rate editing', async () => {
const account = buildAccount()
account.extra = {
upstream_billing_probe_enabled: true,
upstream_billing_rate_sync_enabled: true
}
updateAccountMock.mockReset()
checkMixedChannelRiskMock.mockReset()
checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false })
updateAccountMock.mockResolvedValue(account)
const wrapper = mountModal(account)
const syncToggle = wrapper.get('[data-testid="upstream-billing-rate-sync"]')
const probeToggle = wrapper.get('[data-testid="upstream-billing-auto-probe"]')
const rateInput = wrapper.get<HTMLInputElement>('[data-testid="account-rate-multiplier"]')
expect(syncToggle.attributes('aria-checked')).toBe('true')
expect(rateInput.element.disabled).toBe(true)
await probeToggle.trigger('click')
expect(probeToggle.attributes('aria-checked')).toBe('false')
expect(syncToggle.attributes('aria-checked')).toBe('false')
expect(rateInput.element.disabled).toBe(false)
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
const payload = updateAccountMock.mock.calls[0]?.[1]
expect(payload?.upstream_billing_probe_enabled).toBe(false)
expect(payload?.upstream_billing_rate_sync_enabled).toBe(false)
expect(payload?.rate_multiplier).toBe(1)
})
it('disabling only rate sync keeps automatic probing enabled', async () => {
const account = buildAccount()
account.extra = {
upstream_billing_probe_enabled: true,
upstream_billing_rate_sync_enabled: true
}
updateAccountMock.mockReset()
checkMixedChannelRiskMock.mockReset()
checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false })
updateAccountMock.mockResolvedValue(account)
const wrapper = mountModal(account)
await wrapper.get('[data-testid="upstream-billing-rate-sync"]').trigger('click')
expect(wrapper.get('[data-testid="upstream-billing-auto-probe"]').attributes('aria-checked')).toBe(
'true'
)
await wrapper.get('form#edit-account-form').trigger('submit.prevent')
const payload = updateAccountMock.mock.calls[0]?.[1]
expect(payload?.upstream_billing_probe_enabled).toBe(true)
expect(payload?.upstream_billing_rate_sync_enabled).toBe(false)
expect(payload?.rate_multiplier).toBe(1)
})
it('clears OpenAI APIKey Responses override when set back to auto', async () => {
@@ -88,11 +88,11 @@ describe('UpstreamBillingRateCell', () => {
}
})
expect(wrapper.text()).toContain('0.6x')
expect(wrapper.text()).toContain('0.60x')
await wrapper.setProps({ now: Date.parse('2026-07-13T01:00:00Z') })
expect(wrapper.text()).toContain('0.9x')
expect(wrapper.text()).toContain('0.90x')
await wrapper.setProps({ now: Date.parse('2026-07-13T10:00:00Z') })
expect(wrapper.text()).toContain('0.6x')
expect(wrapper.text()).toContain('0.60x')
expect(wrapper.text()).not.toContain('admin.accounts.upstreamBilling.latest')
expect(wrapper.get('[data-testid="upstream-billing-probe"]').text()).toBe('')
expect(wrapper.get('[data-testid="upstream-billing-probe"]').attributes('aria-label')).toBe(
@@ -132,11 +132,11 @@ describe('UpstreamBillingRateCell', () => {
}
})
})
expect(wrapper.text()).toContain('0.6x')
expect(wrapper.text()).toContain('0.60x')
expect(wrapper.text()).toContain('admin.accounts.upstreamBilling.failed')
await wrapper.setProps({ now: Date.parse('2026-07-13T01:00:00Z') })
expect(wrapper.text()).toContain('0.9x')
expect(wrapper.text()).toContain('0.90x')
expect(wrapper.text()).not.toContain('admin.accounts.upstreamBilling.stale')
await wrapper.setProps({ now: Date.parse('2026-07-13T01:00:00.001Z') })
@@ -312,7 +312,7 @@ describe('UpstreamBillingRateCell', () => {
await wrapper.setProps({ account: malformedAccount({}, { received_at: 'not-a-time' }) })
expect(wrapper.get('[data-testid="upstream-billing-rate"]').text()).toBe('admin.accounts.upstreamBilling.stale')
await wrapper.setProps({ account: malformedAccount({}, { received_at: '2026-07-13T00:31:00Z' }) })
expect(wrapper.get('[data-testid="upstream-billing-rate"]').text()).toBe('0.6x')
expect(wrapper.get('[data-testid="upstream-billing-rate"]').text()).toBe('0.60x')
await wrapper.setProps({ account: malformedAccount({}, { received_at: '2026-07-13T00:36:00Z' }) })
expect(wrapper.get('[data-testid="upstream-billing-rate"]').text()).toBe('admin.accounts.upstreamBilling.stale')
await wrapper.setProps({ account: malformedAccount({}, { fresh_until: '2026-07-12T23:59:00Z' }) })
@@ -225,7 +225,11 @@ export default {
upstreamBilling: {
trustWarning: 'This rate is declared by the upstream site for the current API key. Sub2API cannot verify that it matches actual charges. The upstream site or an intermediary may return forged, stale, or modified data. Verify it against bills, balance changes, and actual usage.',
autoProbe: 'Automatically probe upstream declared rate',
autoProbeHint: 'Probe this account\'s upstream declared rate on the global interval when global probing is enabled.',
autoProbeHint: 'Refresh the upstream declared rate on the global interval. This switch alone does not change the account rate.',
syncRate: 'Sync upstream declared rate',
syncRateHint: 'Update the account rate after each successful probe. Failed or invalid declarations leave it unchanged.',
syncRateManagedHint: 'The current rate is maintained automatically from the upstream declared rate.',
syncedRateTooltip: 'This account rate is synchronized from the upstream declared rate',
manualProbe: 'Probe upstream rate now',
stale: 'Stale',
unsupported: 'Unsupported',
@@ -420,6 +424,8 @@ export default {
failed: 'Bulk update failed',
noSelection: 'Please select accounts to edit',
noFieldsSelected: 'Select at least one field to update',
rateSyncWarning: 'Accounts with upstream rate sync enabled cannot be changed in bulk. Disable sync in the account editor first.',
rateSyncConflict: 'Cannot change account rates: {count} target account(s) have upstream rate sync enabled.',
mixedPlatformWarning: 'Selected accounts span multiple platforms ({platforms}). Model mapping presets shown are combined — ensure mappings are appropriate for each platform.'
},
bulkDeleteTitle: 'Bulk Delete Accounts',
@@ -361,7 +361,7 @@ export default {
},
upstreamBillingProbe: {
title: 'Upstream Rate Auto Detection',
description: 'Periodically retrieve billing rates declared by upstream Sub2API sites connected to API key accounts.',
description: 'Periodically retrieve rates declared by upstream Sub2API sites. Account rates change only when the separate sync switch is enabled.',
enabled: 'Enable global auto detection',
enabledHint: 'When enabled, scheduled detection runs only for accounts that also enable automatic detection. Disabling stops all scheduled detection; manual detection remains available.',
intervalMinutes: 'Detection interval (minutes)',
@@ -178,7 +178,11 @@ export default {
upstreamBilling: {
trustWarning: '此倍率由上游站点针对当前 API Key 自行声明。Sub2API 无法验证该值是否与实际扣费一致;上游站点或中间代理可能返回伪造、过期或被篡改的数据。请结合账单、余额变化和实际用量自行核验。',
autoProbe: '自动探测上游声明倍率',
autoProbeHint: '启用后按全局探测周期查询此账号的上游声明倍率;全局探测关闭时不会执行。',
autoProbeHint: '启用后按全局周期刷新上游声明倍率;此开关本身不会修改账号倍率。',
syncRate: '同步上游声明倍率',
syncRateHint: '成功探测后自动更新账号倍率;探测失败或声明无效时保持不变。',
syncRateManagedHint: '当前倍率由上游声明倍率自动维护。',
syncedRateTooltip: '该账号倍率由上游声明倍率自动同步',
manualProbe: '立即探测上游倍率',
stale: '已过期',
unsupported: '不支持',
@@ -488,6 +492,8 @@ export default {
failed: '批量更新失败',
noSelection: '请选择要编辑的账号',
noFieldsSelected: '请至少选择一个要更新的字段',
rateSyncWarning: '已开启上游倍率同步的账号不能批量手工修改倍率,请先在账号编辑页关闭同步。',
rateSyncConflict: '无法修改账号倍率:{count} 个目标账号已开启上游倍率同步。',
mixedPlatformWarning: '所选账号跨越多个平台({platforms})。显示的模型映射预设为合并结果——请确保映射对每个平台都适用。'
},
bulkDeleteTitle: '批量删除账号',
@@ -354,7 +354,7 @@ export default {
},
upstreamBillingProbe: {
title: '上游倍率自动探测',
description: '定期获取 API Key 账号所连接上游 Sub2API 站点声明的计费倍率。',
description: '定期获取 API Key 账号所连接上游 Sub2API 站点声明的计费倍率;只有另行开启“同步上游声明倍率”的账号才会更新账号倍率。',
enabled: '启用全局自动探测',
enabledHint: '开启后,仅对账号自身已启用自动检测的账号执行定时探测;关闭后停止所有定时探测,手动探测不受影响。',
intervalMinutes: '探测周期(分钟)',
+3
View File
@@ -1051,6 +1051,7 @@ export interface Account {
model_rate_limits?: Record<string, { rate_limited_at: string; rate_limit_reset_at: string }>
antigravity_credits_overages?: Record<string, { activated_at: string; active_until: string }>
upstream_billing_probe_enabled?: boolean
upstream_billing_rate_sync_enabled?: boolean
upstream_billing_probe?: UpstreamBillingProbeSnapshot
} & Record<string, unknown>)
proxy_id: number | null
@@ -1354,6 +1355,8 @@ export interface UpdateAccountRequest {
group_ids?: number[]
expires_at?: number | null
auto_pause_on_expired?: boolean
upstream_billing_probe_enabled?: boolean
upstream_billing_rate_sync_enabled?: boolean
confirm_mixed_channel_risk?: boolean
}
+21 -4
View File
@@ -342,8 +342,17 @@
</div>
</template>
<template #cell-rate_multiplier="{ row }">
<span class="text-sm font-mono text-gray-700 dark:text-gray-300">
{{ (row.rate_multiplier ?? 1).toFixed(2) }}x
<span class="inline-flex items-center gap-1 text-sm font-mono text-gray-700 dark:text-gray-300">
<span>{{ formatMultiplier(row.rate_multiplier ?? 1) }}x</span>
<span
v-if="row.extra?.upstream_billing_rate_sync_enabled === true"
class="inline-flex cursor-help text-emerald-600 dark:text-emerald-400"
:aria-label="t('admin.accounts.upstreamBilling.syncedRateTooltip')"
:title="t('admin.accounts.upstreamBilling.syncedRateTooltip')"
data-testid="account-rate-sync-indicator"
>
<Icon name="sync" size="xs" />
</span>
</span>
</template>
<template #header-upstream_billing_rate="{ column }">
@@ -516,6 +525,7 @@ import { proxyExpiryBadgeClass, proxyExpiryLabelKey } from '@/utils/proxyExpiry'
import { extractApiErrorMessage } from '@/utils/apiError'
import { sanitizeUrl } from '@/utils/url'
import { getFloatingPanelPosition } from '@/utils/floatingPanel'
import { formatMultiplier } from '@/utils/formatters'
import type { Account, AccountPlatform, AccountSchedulerGroupScore, AccountType, Proxy as AccountProxy, AdminGroup, WindowStats, ClaudeModel, UpstreamBillingProbeSnapshot } from '@/types'
const { t } = useI18n()
@@ -1591,7 +1601,7 @@ const handleBulkProbeUpstreamBilling = async () => {
patched = true
}
})
if (patched) await refreshUpstreamBillingSortedList(true)
if (patched) await refreshAccountsAfterUpstreamBillingProbe()
const failed = results.filter(result => result.error).length
if (failed > 0) {
appStore.showError(t('admin.accounts.upstreamBilling.batchPartial', { success: results.length - failed, failed }))
@@ -1890,6 +1900,13 @@ const patchUpstreamBillingSnapshot = (accountID: number, snapshot: UpstreamBilli
extra: { ...account.extra, upstream_billing_probe: snapshot }
})
}
const refreshAccountsAfterUpstreamBillingProbe = async () => {
try {
await load()
} catch (error) {
console.error('Failed to refresh accounts after upstream billing probe:', error)
}
}
const handleProbeUpstreamBilling = async (account: Account) => {
if (probingUpstreamBilling.has(account.id)) return
probingUpstreamBilling.add(account.id)
@@ -1897,7 +1914,7 @@ const handleProbeUpstreamBilling = async (account: Account) => {
const result = await adminAPI.accounts.probeUpstreamBilling(account.id)
if (result.snapshot) {
patchUpstreamBillingSnapshot(account.id, result.snapshot)
await refreshUpstreamBillingSortedList(true)
await refreshAccountsAfterUpstreamBillingProbe()
}
} catch (error) {
console.error('Failed to probe upstream billing:', error)
@@ -10,7 +10,10 @@ const {
getUpstreamBillingProbeSettings,
getAllProxies,
getAllGroups,
probeUpstreamBillingBatch
probeUpstreamBilling,
probeUpstreamBillingBatch,
showError,
showSuccess
} = vi.hoisted(() => ({
listAccounts: vi.fn(),
listWithEtag: vi.fn(),
@@ -18,7 +21,10 @@ const {
getUpstreamBillingProbeSettings: vi.fn(),
getAllProxies: vi.fn(),
getAllGroups: vi.fn(),
probeUpstreamBillingBatch: vi.fn()
probeUpstreamBilling: vi.fn(),
probeUpstreamBillingBatch: vi.fn(),
showError: vi.fn(),
showSuccess: vi.fn()
}))
vi.mock('@/api/admin', () => ({
@@ -31,6 +37,7 @@ vi.mock('@/api/admin', () => ({
delete: vi.fn(),
batchClearError: vi.fn(),
batchRefresh: vi.fn(),
probeUpstreamBilling,
probeUpstreamBillingBatch,
toggleSchedulable: vi.fn()
},
@@ -45,8 +52,8 @@ vi.mock('@/api/admin', () => ({
vi.mock('@/stores/app', () => ({
useAppStore: () => ({
showError: vi.fn(),
showSuccess: vi.fn(),
showError,
showSuccess,
showInfo: vi.fn()
})
}))
@@ -75,6 +82,19 @@ const DataTableStub = {
<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 data-test="account-rate"><slot name="cell-rate_multiplier" :row="row" /></div>
</div>
</div>
`
}
const ProbeDataTableStub = {
props: ['data'],
template: `
<div>
<div v-for="row in data" :key="row.id">
<div data-test="account-rate"><slot name="cell-rate_multiplier" :row="row" /></div>
<slot name="cell-upstream_billing_rate" :row="row" />
</div>
</div>
`
@@ -111,7 +131,10 @@ describe('admin AccountsView bulk edit scope', () => {
getUpstreamBillingProbeSettings.mockReset()
getAllProxies.mockReset()
getAllGroups.mockReset()
probeUpstreamBilling.mockReset()
probeUpstreamBillingBatch.mockReset()
showError.mockReset()
showSuccess.mockReset()
listAccounts.mockResolvedValue({
items: [],
@@ -129,6 +152,7 @@ describe('admin AccountsView bulk edit scope', () => {
getUpstreamBillingProbeSettings.mockResolvedValue({ enabled: true, interval_minutes: 30 })
getAllProxies.mockResolvedValue([])
getAllGroups.mockResolvedValue([])
probeUpstreamBilling.mockResolvedValue({})
probeUpstreamBillingBatch.mockResolvedValue([])
})
@@ -376,33 +400,110 @@ describe('admin AccountsView bulk edit scope', () => {
expect(probeUpstreamBillingBatch).toHaveBeenCalledWith([7, 11])
})
it('reloads the server-sorted list after a batch probe changes a snapshot', async () => {
localStorage.setItem('account-table-sort', JSON.stringify({ key: 'upstream_billing_rate', order: 'asc' }))
const account = (id: number) => ({
it('refreshes the current page after a batch probe and displays the synced rate', async () => {
const account = (id: number, rateMultiplier: number) => ({
id,
name: `account-${id}`,
platform: 'openai',
type: 'apikey',
status: 'active',
schedulable: true,
rate_multiplier: rateMultiplier,
created_at: '2026-07-13T00:00:00Z',
updated_at: '2026-07-13T00:00:00Z'
})
listAccounts
.mockResolvedValueOnce({ items: [account(7)], total: 1, page: 1, page_size: 20, pages: 1 })
.mockResolvedValueOnce({ items: [account(7)], total: 1, page: 1, page_size: 20, pages: 1 })
.mockResolvedValueOnce({ items: [account(7, 0.25)], total: 2, page: 1, page_size: 1, pages: 2 })
.mockResolvedValueOnce({ items: [account(11, 0.25)], total: 2, page: 2, page_size: 1, pages: 2 })
.mockResolvedValueOnce({ items: [account(11, 0.065)], total: 2, page: 2, page_size: 1, pages: 2 })
probeUpstreamBillingBatch.mockResolvedValue([
{
account_id: 7,
account_id: 11,
snapshot: {
status: 'ok',
data: { effective_rate_multiplier: 0.5 },
data: { effective_rate_multiplier: 0.065 },
last_attempt_at: '2026-07-13T00:00:00Z',
next_probe_at: '2026-07-13T00:30:00Z'
}
}
])
const wrapper = mount(AccountsView, {
global: {
stubs: {
AppLayout: { template: '<div><slot /></div>' },
TablePageLayout: { template: '<div><slot name="table" /><slot name="pagination" /></div>' },
DataTable: DataTableStub,
AccountBulkActionsBar: AccountBulkActionsBarStub,
AccountTableActions: true,
AccountTableFilters: true,
AccountActionMenu: true,
Pagination: PaginationStub,
ConfirmDialog: 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="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([11])
expect(listAccounts).toHaveBeenCalledTimes(3)
expect(listAccounts.mock.calls[2]?.[0]).toBe(2)
expect(wrapper.get('[data-test="account-rate"]').text()).toBe('0.065x')
})
it('does not report a successful batch probe as failed when the list refresh fails', async () => {
const account = {
id: 7,
name: 'account-7',
platform: 'openai',
type: 'apikey',
status: 'active',
schedulable: true,
rate_multiplier: 0.25,
created_at: '2026-07-13T00:00:00Z',
updated_at: '2026-07-13T00:00:00Z'
}
listAccounts
.mockResolvedValueOnce({ items: [account], total: 1, page: 1, page_size: 20, pages: 1 })
.mockRejectedValueOnce(new Error('refresh failed'))
probeUpstreamBillingBatch.mockResolvedValue([
{
account_id: 7,
snapshot: {
status: 'ok',
data: { effective_rate_multiplier: 0.065 },
last_attempt_at: '2026-07-13T00:00:00Z',
next_probe_at: '2026-07-13T00:30:00Z'
}
}
])
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const wrapper = mount(AccountsView, {
global: {
stubs: {
@@ -443,7 +544,78 @@ describe('admin AccountsView bulk edit scope', () => {
await wrapper.get('[data-test="probe-upstream-billing"]').trigger('click')
await flushPromises()
expect(probeUpstreamBillingBatch).toHaveBeenCalledWith([7])
expect(showError).not.toHaveBeenCalled()
expect(showSuccess).toHaveBeenCalledWith('admin.accounts.upstreamBilling.batchCompleted')
consoleError.mockRestore()
})
it('refreshes the account row after a successful single-account probe', async () => {
const account = (rateMultiplier: number) => ({
id: 7,
name: 'account-7',
platform: 'openai',
type: 'apikey',
status: 'active',
schedulable: true,
rate_multiplier: rateMultiplier,
extra: { upstream_billing_probe_enabled: true },
created_at: '2026-07-13T00:00:00Z',
updated_at: '2026-07-13T00:00:00Z'
})
listAccounts
.mockResolvedValueOnce({ items: [account(0.25)], total: 1, page: 1, page_size: 20, pages: 1 })
.mockResolvedValueOnce({ items: [account(0.065)], total: 1, page: 1, page_size: 20, pages: 1 })
probeUpstreamBilling.mockResolvedValue({
account_id: 7,
snapshot: {
status: 'ok',
data: { effective_rate_multiplier: 0.065 },
last_attempt_at: '2026-07-13T00:00:00Z',
next_probe_at: '2026-07-13T00:30:00Z'
}
})
const wrapper = mount(AccountsView, {
global: {
stubs: {
AppLayout: { template: '<div><slot /></div>' },
TablePageLayout: { template: '<div><slot name="table" /></div>' },
DataTable: ProbeDataTableStub,
AccountBulkActionsBar: true,
AccountTableActions: true,
AccountTableFilters: true,
AccountActionMenu: true,
Pagination: true,
ConfirmDialog: 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,
Icon: true
}
}
})
await flushPromises()
await wrapper.get('[data-testid="upstream-billing-probe"]').trigger('click')
await flushPromises()
expect(probeUpstreamBilling).toHaveBeenCalledWith(7)
expect(listAccounts).toHaveBeenCalledTimes(2)
expect(wrapper.get('[data-test="account-rate"]').text()).toBe('0.065x')
})
})
@@ -75,6 +75,9 @@ const DataTableStub = {
<slot :name="'header-' + column.key" :column="column" />
</div>
</template>
<div v-for="row in data" :key="row.id" data-test="account-rate">
<slot name="cell-rate_multiplier" :row="row" />
</div>
</div>
`
}
@@ -189,4 +192,35 @@ describe('admin AccountsView usage windows hint', () => {
const columns = wrapper.getComponent(DataTableStub).props('columns') as Array<{ key: string; sortable: boolean }>
expect(columns.find(column => column.key === 'upstream_billing_rate')?.sortable).toBe(true)
})
it('shows account multipliers with enough precision to match declared rates', async () => {
listAccounts.mockResolvedValueOnce({
items: [{
id: 7,
name: 'precision-account',
platform: 'gemini',
type: 'apikey',
status: 'active',
schedulable: true,
rate_multiplier: 0.065,
extra: {
upstream_billing_probe_enabled: true,
upstream_billing_rate_sync_enabled: true
},
created_at: '2026-07-13T00:00:00Z',
updated_at: '2026-07-13T00:00:00Z'
}],
total: 1,
page: 1,
page_size: 20,
pages: 1
})
const wrapper = mountView()
await flushPromises()
expect(wrapper.get('[data-test="account-rate"]').text()).toBe('0.065x')
const indicator = wrapper.get('[data-testid="account-rate-sync-indicator"]')
expect(indicator.attributes('title')).toBe('admin.accounts.upstreamBilling.syncedRateTooltip')
})
})