From 2ad419706d4cd52bd34b6afd928722cc9feac32e Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 27 Nov 2026 14:39:04 +0800 Subject: [PATCH] fix(accounts): keep older proxy counts when a newer refresh fails Review follow-up for the proxy account count refresh: - Apply a proxy list response only if it is newer than the last applied one. Previously a failed newer refresh also discarded a slower older success, which could leave the selector empty. - Refresh proxy counts on every `created` event. Batch creation can partially succeed and keep the dialog open, so opening the dialog was not enough. - Test ProxySelector with the real vue-i18n and locale files instead of a hand-written mock of the plural rule. --- .../ProxySelector.accountCount.spec.ts | 44 ++++++-------- frontend/src/views/admin/AccountsView.vue | 21 +++++-- .../admin/__tests__/AccountsView.lite.spec.ts | 58 +++++++++++++++++++ 3 files changed, 93 insertions(+), 30 deletions(-) diff --git a/frontend/src/components/common/__tests__/ProxySelector.accountCount.spec.ts b/frontend/src/components/common/__tests__/ProxySelector.accountCount.spec.ts index dddb4168ee..3911029d74 100644 --- a/frontend/src/components/common/__tests__/ProxySelector.accountCount.spec.ts +++ b/frontend/src/components/common/__tests__/ProxySelector.accountCount.spec.ts @@ -1,34 +1,27 @@ 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() } } })) -// vitest resolves vue-i18n to the runtime-only build, which cannot compile raw -// locale strings. Resolve keys against the real locale files instead and apply -// vue-i18n's two-choice plural rule ("one | other": 1 -> first, else second). -const { locale } = vi.hoisted(() => ({ locale: { current: 'zh' as 'zh' | 'en' } })) -vi.mock('vue-i18n', () => ({ - useI18n: () => ({ - t: (key: string, plural?: number): string => { - const messages = locale.current === 'zh' ? zhResources : enResources - const value = key.split('.').slice(1).reduce( - (node: unknown, part: string) => (node as Record | undefined)?.[part], - { proxies: messages.proxies } - ) - if (typeof value !== 'string') return key - const choices = value.split('|').map((choice: string) => choice.trim()) - const message = typeof plural === 'number' && choices.length === 2 ? choices[plural === 1 ? 0 : 1] : value - return typeof plural === 'number' ? message.replace(/\{(count|n)\}/g, String(plural)) : message - } - }) -})) enableAutoUnmount(afterEach) -async function openSelector(lang: 'zh' | 'en', accountCounts: Array): Promise { - locale.current = lang +async function openSelector(locale: 'zh' | 'en', accountCounts: Array): Promise { + // 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}`, @@ -42,7 +35,7 @@ async function openSelector(lang: 'zh' | 'en', accountCounts: Array { 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 = rows[1].element.children - const badgeIndex = Array.from(children).findIndex((el: Element) => el.getAttribute('data-test') === 'proxy-account-count') - const testButtonIndex = Array.from(children).findIndex((el: Element) => el.classList.contains('test-btn')) + 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) }) @@ -75,6 +68,7 @@ describe('ProxySelector account counts', () => { 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 () => { diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index fabf9bea1c..6c79d925fa 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -467,7 +467,7 @@ - + @@ -624,15 +624,20 @@ 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. The -// sequence guard drops responses that arrive after a newer request; a failed -// refresh keeps the previous list so the selector never goes empty. +// 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 => { const seq = ++proxiesLoadSeq try { const list: AccountProxy[] = await adminAPI.proxies.getAllWithCount() - if (seq === proxiesLoadSeq) proxies.value = list + if (seq > proxiesAppliedSeq) { + proxiesAppliedSeq = seq + proxies.value = list + } } catch (error: unknown) { console.error('Failed to load proxies:', error) } @@ -640,6 +645,12 @@ const loadProxies = async (): Promise => { 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(null) const tempUnschedAcc = ref(null) diff --git a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts index 4f82ca754b..652089f369 100644 --- a/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts +++ b/frontend/src/views/admin/__tests__/AccountsView.lite.spec.ts @@ -229,6 +229,64 @@ describe('admin AccountsView lite account list', () => { 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((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } + } + vi.spyOn(console, 'error').mockImplementation(() => {}) + const createModal = (wrapper: ReturnType) => 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 })