diff --git a/src/components/topbar/CurrentUserPopoverLegacy.test.ts b/src/components/topbar/CurrentUserPopoverLegacy.test.ts index 6e74b09e6c9..cec98f42530 100644 --- a/src/components/topbar/CurrentUserPopoverLegacy.test.ts +++ b/src/components/topbar/CurrentUserPopoverLegacy.test.ts @@ -1,6 +1,7 @@ import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities' import { useBillingDialogs } from '@/platform/billing/composables/useBillingDialogs' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { reportError } from '@comfyorg/telemetry/reportError' import { getActivePinia } from 'pinia' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' @@ -140,6 +141,22 @@ describe('CurrentUserPopoverLegacy', () => { expect(useBillingContext().fetchBalance).toHaveBeenCalled() }) + it('reports a failed balance read once instead of leaving it unhandled', async () => { + const failure = new Error('Balance temporarily unavailable') + vi.mocked(useBillingContext().fetchBalance).mockRejectedValueOnce(failure) + + renderComponent() + + await vi.waitFor(() => + expect(reportError).toHaveBeenCalledWith(failure, { + surface: 'billing', + errorType: 'error_refreshing_balance', + level: 'warning' + }) + ) + expect(reportError).toHaveBeenCalledOnce() + }) + describe('subscription tier badge', () => { it('renders the tier name derived from the facade tier', () => { renderComponent() diff --git a/src/components/topbar/CurrentUserPopoverLegacy.vue b/src/components/topbar/CurrentUserPopoverLegacy.vue index 68493ba5134..7788888c48d 100644 --- a/src/components/topbar/CurrentUserPopoverLegacy.vue +++ b/src/components/topbar/CurrentUserPopoverLegacy.vue @@ -163,6 +163,7 @@ import PopoverContent from '@comfyorg/design-system/popover/PopoverContent' import Skeleton from '@comfyorg/design-system/skeleton/Skeleton' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { refreshBalanceInBackground } from '@/platform/billing/refreshBalanceInBackground' import { useExternalLink } from '@/composables/useExternalLink' import { useTelemetry } from '@comfyorg/telemetry' import { paymentIntentSourceForAddCreditsClick } from '@/platform/telemetry/utils/paymentIntentSource' @@ -253,6 +254,6 @@ const handleLogout = async () => { } onMounted(() => { - void fetchBalance() + void refreshBalanceInBackground(fetchBalance) }) diff --git a/src/platform/account/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/account/components/CurrentUserPopoverWorkspace.test.ts index 7fd18fc4830..e780a540340 100644 --- a/src/platform/account/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/account/components/CurrentUserPopoverWorkspace.test.ts @@ -15,6 +15,7 @@ import { setImmediate } from 'node:timers/promises' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { reportError } from '@comfyorg/telemetry/reportError' import { useBillingRouting } from '@/platform/billing/composables/useBillingRouting' import type { BalanceInfo, @@ -268,6 +269,22 @@ describe('CurrentUserPopoverWorkspace', () => { expect(screen.queryByRole('tooltip')).not.toBeInTheDocument() }) + it('reports a failed balance read once instead of leaving it unhandled', async () => { + const failure = new Error('Balance temporarily unavailable') + vi.mocked(useBillingContext().fetchBalance).mockRejectedValueOnce(failure) + + renderComponent() + + await vi.waitFor(() => + expect(reportError).toHaveBeenCalledWith(failure, { + surface: 'billing', + errorType: 'error_refreshing_balance', + level: 'warning' + }) + ) + expect(reportError).toHaveBeenCalledOnce() + }) + it('keeps account actions available without workspace context', () => { renderComponent('personal', true) diff --git a/src/platform/account/components/CurrentUserPopoverWorkspace.vue b/src/platform/account/components/CurrentUserPopoverWorkspace.vue index 4a75758ae96..6695b9d717d 100644 --- a/src/platform/account/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/account/components/CurrentUserPopoverWorkspace.vue @@ -268,6 +268,7 @@ import { import { useExternalLink } from '@/composables/useExternalLink' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { refreshBalanceInBackground } from '@/platform/billing/refreshBalanceInBackground' import SubscribeButton from '@/platform/billing/subscription/components/SubscribeButton.vue' import { useSubscriptionDialog } from '@/platform/billing/subscription/composables/useSubscriptionDialog' import { isCloud } from '@/platform/distribution/types' @@ -450,6 +451,6 @@ const handleCreateWorkspace = () => { } onMounted(() => { - if (!accountActionsOnly) void fetchBalance() + if (!accountActionsOnly) void refreshBalanceInBackground(fetchBalance) }) diff --git a/src/platform/billing/composables/useWorkspaceBilling.test.ts b/src/platform/billing/composables/useWorkspaceBilling.test.ts index d908b11062a..5f150c28a3e 100644 --- a/src/platform/billing/composables/useWorkspaceBilling.test.ts +++ b/src/platform/billing/composables/useWorkspaceBilling.test.ts @@ -796,6 +796,56 @@ describe('useWorkspaceBilling', () => { expect(billing.balance.value?.amountMicros).toBe(5_000_000) }) + + it('settles an older failed balance read quietly once a newer read replaced it', async () => { + const olderBalance = createDeferred() + mockWorkspaceApi.getBillingBalance + .mockReturnValueOnce(olderBalance.promise) + .mockResolvedValueOnce(positiveBalance) + const billing = setupBilling() + + const olderRequest = billing.fetchBalance() + await billing.fetchBalance() + olderBalance.reject(new Error('stale balance failed')) + + await expect(olderRequest).resolves.toBeUndefined() + expect(billing.error.value).toBeNull() + expect(billing.balance.value?.amountMicros).toBe(5_000_000) + }) + + it('settles a failed balance read quietly once the workspace changed', async () => { + const balanceRead = createDeferred() + mockWorkspaceApi.getBillingBalance.mockReturnValueOnce( + balanceRead.promise + ) + const billing = setupBilling() + + const read = billing.fetchBalance() + Object.assign(useTeamWorkspaceStore(), { + activeWorkspace: { id: 'workspace-2' } + }) + balanceRead.reject(new Error('stale workspace balance failed')) + + await expect(read).resolves.toBeUndefined() + expect(billing.error.value).toBeNull() + }) + + it('does not keep a balance from a stale workspace response', async () => { + const balanceRead = createDeferred() + mockWorkspaceApi.getBillingBalance.mockReturnValueOnce( + balanceRead.promise + ) + const billing = setupBilling() + + const read = billing.fetchBalance() + Object.assign(useTeamWorkspaceStore(), { + activeWorkspace: { id: 'workspace-2' } + }) + balanceRead.resolve(zeroBalance) + await read + + expect(billing.balance.value).toBeNull() + }) }) describe('subscribe', () => { diff --git a/src/platform/billing/composables/useWorkspaceBilling.ts b/src/platform/billing/composables/useWorkspaceBilling.ts index 717f29e69c2..0a47666011b 100644 --- a/src/platform/billing/composables/useWorkspaceBilling.ts +++ b/src/platform/billing/composables/useWorkspaceBilling.ts @@ -355,12 +355,13 @@ export function useWorkspaceBilling(): WorkspaceBilling { return true } - function isStaleStatusRead( + function isStaleBillingRead( + billingResource: keyof typeof latestBillingReadIds, requestId: number, workspaceId: string | undefined ): boolean { return ( - requestId !== latestBillingReadIds.status || + requestId !== latestBillingReadIds[billingResource] || workspaceId !== workspaceStore.activeWorkspace?.id ) } @@ -381,7 +382,10 @@ export function useWorkspaceBilling(): WorkspaceBilling { const status = rail ? await readOnRail(rail.readStatus, 'getBillingStatus') : await billingApi.getBillingStatus() - if (status === undefined || isStaleStatusRead(requestId, workspaceId)) + if ( + status === undefined || + isStaleBillingRead('status', requestId, workspaceId) + ) return seatCapacity.value = seatCapacityFrom(status) @@ -406,6 +410,7 @@ export function useWorkspaceBilling(): WorkspaceBilling { async function fetchBalance(): Promise { const requestId = ++latestBillingReadIds.balance + const workspaceId = workspaceStore.activeWorkspace?.id const rail: BillingReadRail | null = useBillingReadRail() isLoading.value = true error.value = null @@ -413,14 +418,16 @@ export function useWorkspaceBilling(): WorkspaceBilling { const balance = rail ? await readOnRail(rail.readBalance, 'getBillingBalance') : await billingApi.getBillingBalance() - if (balance !== undefined && requestId === latestBillingReadIds.balance) { + if ( + balance !== undefined && + !isStaleBillingRead('balance', requestId, workspaceId) + ) { balanceData.value = balance } } catch (err) { - if (requestId === latestBillingReadIds.balance) { - error.value = - err instanceof Error ? err.message : 'Failed to fetch balance' - } + if (isStaleBillingRead('balance', requestId, workspaceId)) return + error.value = + err instanceof Error ? err.message : 'Failed to fetch balance' throw err } finally { if (requestId === latestBillingReadIds.balance) isLoading.value = false diff --git a/src/platform/billing/refreshBalanceInBackground.test.ts b/src/platform/billing/refreshBalanceInBackground.test.ts new file mode 100644 index 00000000000..3b2fcd1a607 --- /dev/null +++ b/src/platform/billing/refreshBalanceInBackground.test.ts @@ -0,0 +1,56 @@ +import { reportError } from '@comfyorg/telemetry/reportError' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { refreshBalanceInBackground } from '@/platform/billing/refreshBalanceInBackground' + +const FIVE_MINUTES_MS = 5 * 60_000 + +function fail() { + return Promise.reject(new Error('Balance temporarily unavailable')) +} + +function succeed() { + return Promise.resolve() +} + +describe('refreshBalanceInBackground', () => { + let testStart = Date.now() + + beforeEach(() => { + testStart += 2 * FIVE_MINUTES_MS + vi.setSystemTime(testStart) + }) + + it('reports nothing when the read succeeds', async () => { + await refreshBalanceInBackground(succeed) + + expect(reportError).not.toHaveBeenCalled() + }) + + it('reports a failed read as a billing warning', async () => { + const failure = new Error('Balance temporarily unavailable') + + await refreshBalanceInBackground(() => Promise.reject(failure)) + + expect(reportError).toHaveBeenCalledExactlyOnceWith(failure, { + surface: 'billing', + errorType: 'error_refreshing_balance', + level: 'warning' + }) + }) + + it('reports at most one failure every five minutes, whatever succeeds in between', async () => { + await Promise.all([ + refreshBalanceInBackground(fail), + refreshBalanceInBackground(fail) + ]) + await refreshBalanceInBackground(succeed) + await refreshBalanceInBackground(fail) + expect(reportError).toHaveBeenCalledOnce() + + vi.setSystemTime(Date.now() + FIVE_MINUTES_MS) + await refreshBalanceInBackground(fail) + + expect(reportError).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/platform/billing/refreshBalanceInBackground.ts b/src/platform/billing/refreshBalanceInBackground.ts new file mode 100644 index 00000000000..35476071649 --- /dev/null +++ b/src/platform/billing/refreshBalanceInBackground.ts @@ -0,0 +1,23 @@ +import { reportError } from '@comfyorg/telemetry/reportError' + +const REPORT_INTERVAL_MS = 5 * 60_000 +let lastReportedAt = Number.NEGATIVE_INFINITY + +/** Reads the balance for a caller that does not await it; reports a failure at most every 5 minutes and never rejects. */ +export function refreshBalanceInBackground( + fetchBalance: () => Promise +): Promise { + return fetchBalance().then( + () => undefined, + (error: unknown) => { + const now = Date.now() + if (now - lastReportedAt < REPORT_INTERVAL_MS) return + lastReportedAt = now + reportError(error, { + surface: 'billing', + errorType: 'error_refreshing_balance', + level: 'warning' + }) + } + ) +} diff --git a/src/platform/settings/components/SettingDialog.test.ts b/src/platform/settings/components/SettingDialog.test.ts index b5e8eecd0c5..e2ba0cc3795 100644 --- a/src/platform/settings/components/SettingDialog.test.ts +++ b/src/platform/settings/components/SettingDialog.test.ts @@ -5,6 +5,8 @@ import { nextTick, ref } from 'vue' import type { Ref } from 'vue' import { i18n } from '@/i18n' +import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { reportError } from '@comfyorg/telemetry/reportError' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import type { NavGroupData } from '@comfyorg/design-system/lib/navigation/types' @@ -297,3 +299,35 @@ it('restores the collapsed header when switching sections', async () => { await screen.findByRole('heading', { name: 'Acme Team' }) ).toBeInTheDocument() }) + +it('reports a failed balance read from the Credits section once instead of leaving it unhandled', async () => { + const failure = new Error('Balance temporarily unavailable') + const billing = useBillingContext() + vi.mocked(billing.fetchBalance).mockRejectedValueOnce(failure) + vi.mocked(useBillingContext).mockReturnValue(billing) + settingUiMocks.navGroups.value = [ + { + title: 'Workspace', + items: [ + { + id: 'workspace-allowlist', + label: 'Allowlist', + icon: 'icon-[lucide--list-checks]' + }, + { id: 'credits', label: 'Credits', icon: 'icon-[lucide--coins]' } + ] + } + ] + renderDialog() + + await userEvent.click(screen.getByRole('button', { name: 'Credits' })) + + await vi.waitFor(() => + expect(reportError).toHaveBeenCalledWith(failure, { + surface: 'billing', + errorType: 'error_refreshing_balance', + level: 'warning' + }) + ) + expect(reportError).toHaveBeenCalledOnce() +}) diff --git a/src/platform/settings/components/SettingDialog.vue b/src/platform/settings/components/SettingDialog.vue index 89f46a8e4ae..12315f7af84 100644 --- a/src/platform/settings/components/SettingDialog.vue +++ b/src/platform/settings/components/SettingDialog.vue @@ -126,6 +126,7 @@ import BaseModalLayout from '@comfyorg/design-system/layout/BaseModalLayout' import NavItem from '@comfyorg/design-system/navigation/NavItem' import NavTitle from '@comfyorg/design-system/navigation/NavTitle' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { refreshBalanceInBackground } from '@/platform/billing/refreshBalanceInBackground' import { useWorkspaceBillingStateStore } from '@/platform/billing/stores/workspaceBillingStateStore' import { useSettingsHeaderCollapse } from '@/platform/settings/composables/useSettingsHeaderCollapse' import { cn } from '@comfyorg/tailwind-utils' @@ -307,7 +308,7 @@ watch(activeCategoryKey, (newKey, oldKey) => { activeCategoryKey.value = oldKey } if (newKey === 'credits') { - void fetchBalance() + void refreshBalanceInBackground(fetchBalance) } if (newKey) { void nextTick(() => {