Merge pull request #9118 from Wei-Shaw/fix/proxy-selector-account-count

fix(accounts): 代理下拉框右侧显示账号数并在打开弹窗时刷新
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-11-27 15:07:05 +08:00
commit e38f8ad784
7 files changed
+220 -35

No files matched your search

@@ -85,13 +85,6 @@
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="truncate font-medium">{{ proxy.name }}</span>
<!-- Account count badge -->
<span
v-if="proxy.account_count !== undefined"
class="inline-flex flex-shrink-0 items-center rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600 dark:bg-dark-600 dark:text-gray-400"
>
{{ proxy.account_count }}
</span>
<!-- Test result badges -->
<template v-if="testResults[proxy.id]">
<span
@@ -118,6 +111,16 @@
</div>
</div>
<!-- Account count: accounts currently bound to this proxy -->
<span
v-if="proxy.account_count !== undefined"
class="account-count-badge"
:title="t('admin.proxies.selectorAccountCountTitle')"
data-test="proxy-account-count"
>
{{ t('admin.proxies.selectorAccountCount', proxy.account_count) }}
</span>
<!-- Individual test button -->
<button
type="button"
@@ -399,6 +402,11 @@ onUnmounted(() => {
@apply text-gray-500 dark:text-dark-400;
}
.account-count-badge {
@apply inline-flex flex-shrink-0 items-center whitespace-nowrap rounded px-1.5 py-0.5 text-xs tabular-nums;
@apply bg-gray-100 text-gray-600 dark:bg-dark-600 dark:text-gray-400;
}
.test-btn {
@apply flex-shrink-0 rounded p-1;
@apply text-gray-400 hover:text-emerald-600 dark:hover:text-emerald-400;
@@ -0,0 +1,81 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { enableAutoUnmount, mount, type VueWrapper } from '@vue/test-utils'
import { createI18n } from 'vue-i18n'
import ProxySelector from '../ProxySelector.vue'
import enResources from '@/i18n/locales/en/admin/resources'
import zhResources from '@/i18n/locales/zh/admin/resources'
import type { Proxy } from '@/types'
vi.mock('@/api/admin', () => ({ adminAPI: { proxies: { testProxy: vi.fn() } } }))
enableAutoUnmount(afterEach)
async function openSelector(locale: 'zh' | 'en', accountCounts: Array<number | undefined>): Promise<VueWrapper> {
// Real vue-i18n with the real locale files: pluralization and interpolation
// are exercised exactly as in the app.
const i18n = createI18n({
legacy: false,
locale,
missingWarn: false,
fallbackWarn: false,
messages: {
en: { admin: { proxies: enResources.proxies } },
zh: { admin: { proxies: zhResources.proxies } }
}
})
const proxies: Proxy[] = accountCounts.map((count: number | undefined, i: number) => ({
id: i + 1,
name: `Proxy ${i + 1}`,
host: '127.0.0.1',
port: 11000 + i,
protocol: 'socks5h',
username: null,
status: 'active',
expires_at: null,
account_count: count
} as Proxy))
const wrapper = mount(ProxySelector, {
props: { modelValue: null, proxies },
global: { plugins: [i18n], stubs: { Icon: true } }
})
await wrapper.get('.select-trigger').trigger('click')
return wrapper
}
function proxyRows(wrapper: VueWrapper) {
// First option is "no proxy".
return wrapper.findAll('.select-option').slice(1)
}
describe('ProxySelector account counts', () => {
it('shows the bound account count on the right side of each proxy row (zh)', async () => {
const wrapper = await openSelector('zh', [0, 7])
const rows = proxyRows(wrapper)
expect(rows[0].get('[data-test="proxy-account-count"]').text()).toBe('0 个账号')
expect(rows[1].get('[data-test="proxy-account-count"]').text()).toBe('7 个账号')
expect(rows[1].get('[data-test="proxy-account-count"]').attributes('title')).toBe('当前绑定此代理的账号数')
// The badge sits on the right: after the name/address block, before the test button.
const children = Array.from(rows[1].element.children)
const badgeIndex = children.findIndex((el: Element) => el.getAttribute('data-test') === 'proxy-account-count')
const testButtonIndex = children.findIndex((el: Element) => el.classList.contains('test-btn'))
expect(badgeIndex).toBeGreaterThan(0)
expect(testButtonIndex).toBe(badgeIndex + 1)
})
it('pluralizes the count in English', async () => {
const wrapper = await openSelector('en', [0, 1, 3])
const texts = proxyRows(wrapper).map((row) => row.get('[data-test="proxy-account-count"]').text())
expect(texts).toEqual(['0 accounts', '1 account', '3 accounts'])
expect(proxyRows(wrapper)[0].get('[data-test="proxy-account-count"]').attributes('title')).toBe('Accounts currently using this proxy')
})
it('omits the badge when the list was loaded without counts', async () => {
const wrapper = await openSelector('zh', [undefined, 2])
const rows = proxyRows(wrapper)
expect(rows[0].find('[data-test="proxy-account-count"]').exists()).toBe(false)
expect(rows[1].get('[data-test="proxy-account-count"]').text()).toBe('2 个账号')
})
})
@@ -9,11 +9,10 @@ vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
enableAutoUnmount(afterEach)
beforeEach(() => { vi.clearAllMocks() })
async function openSelector(accountCounts?: number[]) {
async function openSelector() {
const wrapper = mount(ProxySelector, {
props: { modelValue: null, proxies: [1, 2].map(id => ({
id, name: `Proxy ${id}`, host: 'localhost', port: 8080, protocol: 'http',
account_count: accountCounts?.[id - 1]
id, name: `Proxy ${id}`, host: 'localhost', port: 8080, protocol: 'http'
} as Proxy)) },
global: { stubs: { Icon: true } }
})
@@ -21,22 +20,6 @@ async function openSelector(accountCounts?: number[]) {
return wrapper
}
describe('proxy account counts', () => {
it('displays zero and nonzero counts in dropdown options', async () => {
const wrapper = await openSelector([0, 7])
const options = wrapper.findAll('.select-option').slice(1)
expect(options[0].get('.bg-gray-100').text()).toBe('0')
expect(options[1].get('.bg-gray-100').text()).toBe('7')
})
it('does not display a count when it is unavailable', async () => {
const wrapper = await openSelector()
expect(wrapper.findAll('.select-option .bg-gray-100')).toHaveLength(0)
})
})
describe('proxy connection tests', () => {
it('does not restart an individual test when a batch is started', async () => {
let finish!: (result: object) => void
@@ -76,6 +76,8 @@ export default {
copyProxyUrl: 'Copy Proxy URL',
urlCopied: 'Proxy URL copied',
searchProxies: 'Search proxies...',
selectorAccountCount: '{count} account | {count} accounts',
selectorAccountCountTitle: 'Accounts currently using this proxy',
allProtocols: 'All Protocols',
allStatus: 'All Status',
protocols: {
@@ -112,6 +112,8 @@ export default {
allProtocols: '全部协议',
allStatus: '全部状态',
searchProxies: '搜索代理...',
selectorAccountCount: '{count} 个账号',
selectorAccountCountTitle: '当前绑定此代理的账号数',
protocols: {
http: 'HTTP',
https: 'HTTPS',
+33 -8
View File
@@ -467,7 +467,7 @@
</template>
<template #pagination><Pagination v-if="pagination.total > 0" :page="pagination.page" :total="pagination.total" :page-size="pagination.page_size" @update:page="handlePageChange" @update:pageSize="handlePageSizeChange" /></template>
</TablePageLayout>
<CreateAccountModal :show="showCreate" :proxies="proxies" :groups="groups" @close="showCreate = false" @created="reload" />
<CreateAccountModal :show="showCreate" :proxies="proxies" :groups="groups" @close="showCreate = false" @created="handleAccountsCreated" />
<EditAccountModal :show="showEdit" :account="edAcc" :proxies="proxies" :groups="groups" @close="showEdit = false" @updated="handleAccountUpdated" />
<ReAuthAccountModal :show="showReAuth" :account="reAuthAcc" @close="closeReAuthModal" @reauthorized="handleAccountUpdated" />
<AccountTestModal :show="showTest" :account="testingAcc" @close="closeTestModal" />
@@ -622,6 +622,36 @@ const showTest = ref(false)
const showStats = ref(false)
const showErrorPassthrough = ref(false)
const showTLSFingerprintProfiles = ref(false)
// Proxy account counts change whenever accounts are created, deleted, imported
// or rebound, so reload them each time a proxy-picking dialog opens. Only a
// response newer than the last applied one is used, so a slow older response
// never overwrites fresher counts, while a failed newer request does not
// discard an older success; a failed refresh keeps the previous list.
let proxiesLoadSeq = 0
let proxiesAppliedSeq = 0
const loadProxies = async (): Promise<void> => {
const seq = ++proxiesLoadSeq
try {
const list: AccountProxy[] = await adminAPI.proxies.getAllWithCount()
if (seq > proxiesAppliedSeq) {
proxiesAppliedSeq = seq
proxies.value = list
}
} catch (error: unknown) {
console.error('Failed to load proxies:', error)
}
}
watch([showCreate, showEdit, showBulkEdit], (open: boolean[], wasOpen: boolean[] | undefined) => {
if (open.some((isOpen: boolean, i: number) => isOpen && !wasOpen?.[i])) void loadProxies()
})
// Batch creation can partially succeed and keep the dialog open for the
// remaining items, so refresh counts on every successful creation too.
const handleAccountsCreated = (): void => {
void reload()
void loadProxies()
}
const edAcc = ref<Account | null>(null)
const tempUnschedAcc = ref<Account | null>(null)
const deletingAcc = ref<Account | null>(null)
@@ -2621,15 +2651,10 @@ onMounted(async () => {
load()
loadUpstreamBillingProbeGlobalState()
const [proxiesResult, groupsResult] = await Promise.allSettled([
adminAPI.proxies.getAllWithCount(),
const [, groupsResult] = await Promise.allSettled([
loadProxies(),
adminAPI.groups.getAll()
])
if (proxiesResult.status === 'fulfilled') {
proxies.value = proxiesResult.value
} else {
console.error('Failed to load proxies:', proxiesResult.reason)
}
if (groupsResult.status === 'fulfilled') {
groups.value = groupsResult.value
} else {
@@ -112,7 +112,7 @@ function mountView(stubActionMenu = true, realUsageCell = false) {
AppLayout: { template: '<div><slot /></div>' },
TablePageLayout: { template: '<div><slot name="filters" /><slot name="table" /><slot name="pagination" /></div>' },
DataTable: DataTableStub,
AccountTableActions: { template: `<div><button data-test="manual-refresh" @click="$emit('refresh')">refresh</button><slot name="after" /></div>` },
AccountTableActions: { template: `<div><button data-test="manual-refresh" @click="$emit('refresh')">refresh</button><button data-test="open-create" @click="$emit('create')">create</button><slot name="after" /></div>` },
AccountTableFilters: true,
AccountBulkActionsBar: true,
Pagination: true,
@@ -203,6 +203,90 @@ describe('admin AccountsView lite account list', () => {
wrapper.unmount()
})
it('reloads proxy account counts each time the create dialog opens and keeps them on failure', async () => {
const initial = [{ id: 2, name: 'Shared proxy', account_count: 7 }]
const refreshed = [{ id: 2, name: 'Shared proxy', account_count: 8 }]
getAllProxies.mockResolvedValueOnce(initial).mockResolvedValueOnce(refreshed).mockRejectedValueOnce(new Error('offline'))
vi.spyOn(console, 'error').mockImplementation(() => {})
const wrapper = mountView()
await flushPromises()
const createModal = () => wrapper.findComponent({ name: 'CreateAccountModal' })
expect(createModal().props('proxies')).toEqual(initial)
await wrapper.get('[data-test="open-create"]').trigger('click')
await flushPromises()
expect(getAllProxies).toHaveBeenCalledTimes(2)
expect(createModal().props('proxies')).toEqual(refreshed)
createModal().vm.$emit('close')
await flushPromises()
expect(getAllProxies).toHaveBeenCalledTimes(2)
await wrapper.get('[data-test="open-create"]').trigger('click')
await flushPromises()
expect(getAllProxies).toHaveBeenCalledTimes(3)
expect(createModal().props('proxies')).toEqual(refreshed)
wrapper.unmount()
})
it('applies an older proxy response when a newer refresh fails, but never lets it overwrite a newer one', async () => {
type ProxyList = Array<{ id: number; name: string; account_count: number }>
const deferred = () => {
let resolve!: (value: ProxyList) => void
let reject!: (reason: Error) => void
const promise = new Promise<ProxyList>((res, rej) => { resolve = res; reject = rej })
return { promise, resolve, reject }
}
vi.spyOn(console, 'error').mockImplementation(() => {})
const createModal = (wrapper: ReturnType<typeof mountView>) => wrapper.findComponent({ name: 'CreateAccountModal' })
// Mount request is slow; the dialog-open request fails first.
const mountLoad = deferred()
const openLoad = deferred()
getAllProxies.mockReturnValueOnce(mountLoad.promise).mockReturnValueOnce(openLoad.promise)
let wrapper = mountView()
await flushPromises()
await wrapper.get('[data-test="open-create"]').trigger('click')
openLoad.reject(new Error('offline'))
await flushPromises()
mountLoad.resolve([{ id: 1, name: 'Shared proxy', account_count: 3 }])
await flushPromises()
expect(createModal(wrapper).props('proxies')).toEqual([{ id: 1, name: 'Shared proxy', account_count: 3 }])
wrapper.unmount()
// Mount request is slow; the dialog-open request succeeds first with newer counts.
const slowMount = deferred()
const fastOpen = deferred()
getAllProxies.mockReset().mockReturnValueOnce(slowMount.promise).mockReturnValueOnce(fastOpen.promise)
wrapper = mountView()
await flushPromises()
await wrapper.get('[data-test="open-create"]').trigger('click')
fastOpen.resolve([{ id: 1, name: 'Shared proxy', account_count: 4 }])
await flushPromises()
slowMount.resolve([{ id: 1, name: 'Shared proxy', account_count: 3 }])
await flushPromises()
expect(createModal(wrapper).props('proxies')).toEqual([{ id: 1, name: 'Shared proxy', account_count: 4 }])
wrapper.unmount()
})
it('refreshes proxy account counts after accounts are created while the dialog stays open', async () => {
const before = [{ id: 2, name: 'Shared proxy', account_count: 7 }]
const after = [{ id: 2, name: 'Shared proxy', account_count: 9 }]
getAllProxies.mockResolvedValueOnce(before).mockResolvedValueOnce(before).mockResolvedValueOnce(after)
const wrapper = mountView()
await flushPromises()
await wrapper.get('[data-test="open-create"]').trigger('click')
await flushPromises()
const createModal = wrapper.findComponent({ name: 'CreateAccountModal' })
expect(createModal.props('proxies')).toEqual(before)
createModal.vm.$emit('created')
await flushPromises()
expect(getAllProxies).toHaveBeenCalledTimes(3)
expect(createModal.props('proxies')).toEqual(after)
wrapper.unmount()
})
it('syncs the selected row without clearing notes missing from the upstream', async () => {
const account = { ...listRow, type: 'apikey', notes: 'local notes' }
listAccounts.mockResolvedValue({ items: [account], total: 1, page: 1, page_size: 20, pages: 1 })