From 6759259221e0d8341209fcc6bb35d8cc9e51f7dd Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 06:10:32 +0000 Subject: [PATCH] FRONT-3684 fix(billing): report a failed background balance read instead of leaving it unhandled (#22201) Opening the account menu (legacy or workspace) or the Credits settings section starts a balance read that nothing awaits. When it fails, the rejection is unhandled, so Sentry files it as a new high-priority error. Now: - the failure is reported as a `billing` warning (`error_refreshing_balance`), at most once every five minutes, so reopening the menu during an outage does not repeat it; - a workspace balance read that a newer read has replaced settles quietly instead of rejecting, matching the rail path's `SUPERSEDED` handling, so the warning only covers failures the billing state actually kept; - the same applies across a workspace switch. A balance read for the previous workspace could still land after the switch replaced the billing adapter, writing that workspace's balance into the discarded adapter or reporting a warning for a failure the billing state never kept. `fetchStatus` already captured and rechecked the workspace id, so `fetchBalance` now shares that guard rather than carrying a second copy. What the user sees is unchanged. Note that the two popovers still show 0 credits when the read fails; that display bug is tracked separately in https://linear.app/comfyorg/issue/FRONT-3164. Evidence: both events of Sentry `CLOUD-FRONTEND-PROD-2V0` ("AuthStoreError: Failed to fetch balance: Balance temporarily unavailable") are `onunhandledrejection` from `useLegacyBilling.fetchBalance`, right after a 503 from `/customers/balance`. #21322 now retries that 503; this covers the failure left after the retries run out. Linear: https://linear.app/comfyorg/issue/FRONT-3684 - Red before the fix, green after: one test per call site (`CurrentUserPopoverLegacy`, `CurrentUserPopoverWorkspace`, `SettingDialog` Credits section), the helper's five-minute report budget, `useWorkspaceBilling` settling a superseded failed read, and `useWorkspaceBilling` dropping a balance read on both paths once the workspace changed. - `pnpm typecheck`, oxlint, oxfmt and the pre-push fallow audit pass. - After release: `CLOUD-FRONTEND-PROD-2V0` gets no new unhandled events; a persistent balance outage shows up as `error_refreshing_balance` warnings instead. --- .../topbar/CurrentUserPopoverLegacy.test.ts | 19 ++++++ .../topbar/CurrentUserPopoverLegacy.vue | 3 +- .../composables/useWorkspaceBilling.test.ts | 50 ++++++++++++++++ .../composables/useWorkspaceBilling.ts | 23 +++++--- .../refreshBalanceInBackground.test.ts | 58 +++++++++++++++++++ .../billing/refreshBalanceInBackground.ts | 23 ++++++++ .../settings/components/SettingDialog.test.ts | 36 ++++++++++++ .../settings/components/SettingDialog.vue | 3 +- .../CurrentUserPopoverWorkspace.test.ts | 19 ++++++ .../CurrentUserPopoverWorkspace.vue | 3 +- 10 files changed, 226 insertions(+), 11 deletions(-) create mode 100644 src/platform/billing/refreshBalanceInBackground.test.ts create mode 100644 src/platform/billing/refreshBalanceInBackground.ts diff --git a/src/components/topbar/CurrentUserPopoverLegacy.test.ts b/src/components/topbar/CurrentUserPopoverLegacy.test.ts index 65d526d52e6..a64ca37aa28 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 '@/platform/telemetry/reportError' import { getActivePinia } from 'pinia' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' @@ -20,6 +21,8 @@ import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspace import CurrentUserPopoverLegacy from './CurrentUserPopoverLegacy.vue' +vi.mock(import('@/platform/telemetry/reportError')) + vi.mock(import('@/platform/settings/composables/useSettingsDialog')) const originalWindowOpen = window.open @@ -140,6 +143,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 497796d83f8..0fefa73039f 100644 --- a/src/components/topbar/CurrentUserPopoverLegacy.vue +++ b/src/components/topbar/CurrentUserPopoverLegacy.vue @@ -160,6 +160,7 @@ import Popover from '@/components/ui/Popover.vue' import Skeleton from '@/components/ui/skeleton/Skeleton.vue' 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 '@/platform/telemetry' import { paymentIntentSourceForAddCreditsClick } from '@/platform/telemetry/utils/paymentIntentSource' @@ -250,6 +251,6 @@ const handleLogout = async () => { } onMounted(() => { - void fetchBalance() + void refreshBalanceInBackground(fetchBalance) }) diff --git a/src/platform/billing/composables/useWorkspaceBilling.test.ts b/src/platform/billing/composables/useWorkspaceBilling.test.ts index ba7b5c1a5a9..35f541aa792 100644 --- a/src/platform/billing/composables/useWorkspaceBilling.test.ts +++ b/src/platform/billing/composables/useWorkspaceBilling.test.ts @@ -836,6 +836,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 5f313e54a99..ca5e4d5cb3f 100644 --- a/src/platform/billing/composables/useWorkspaceBilling.ts +++ b/src/platform/billing/composables/useWorkspaceBilling.ts @@ -359,12 +359,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 ) } @@ -385,7 +386,10 @@ export function useWorkspaceBilling(): WorkspaceBilling { const status = rail ? await readOnRail(rail.readStatus, 'getBillingStatus') : await workspaceApi.getBillingStatus() - if (status === undefined || isStaleStatusRead(requestId, workspaceId)) + if ( + status === undefined || + isStaleBillingRead('status', requestId, workspaceId) + ) return seatCapacity.value = seatCapacityFrom(status) @@ -409,6 +413,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 @@ -416,14 +421,16 @@ export function useWorkspaceBilling(): WorkspaceBilling { const balance = rail ? await readOnRail(rail.readBalance, 'getBillingBalance') : await workspaceApi.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..82b39eae550 --- /dev/null +++ b/src/platform/billing/refreshBalanceInBackground.test.ts @@ -0,0 +1,58 @@ +import { reportError } from '@/platform/telemetry/reportError' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { refreshBalanceInBackground } from '@/platform/billing/refreshBalanceInBackground' + +vi.mock(import('@/platform/telemetry/reportError')) + +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..6557f2d1aa6 --- /dev/null +++ b/src/platform/billing/refreshBalanceInBackground.ts @@ -0,0 +1,23 @@ +import { reportError } from '@/platform/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 2e0348368bc..1146f2c59d5 100644 --- a/src/platform/settings/components/SettingDialog.test.ts +++ b/src/platform/settings/components/SettingDialog.test.ts @@ -5,11 +5,15 @@ import { nextTick, ref } from 'vue' import type { Ref } from 'vue' import { i18n } from '@/i18n' +import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { reportError } from '@/platform/telemetry/reportError' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import type { NavGroupData } from '@/types/navTypes' import SettingDialog from './SettingDialog.vue' +vi.mock(import('@/platform/telemetry/reportError')) + const settingUiMocks = vi.hoisted(() => ({ navGroups: null as unknown as Ref })) @@ -300,3 +304,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 6c2287192d3..45ccc4df062 100644 --- a/src/platform/settings/components/SettingDialog.vue +++ b/src/platform/settings/components/SettingDialog.vue @@ -123,6 +123,7 @@ import BaseModalLayout from '@/components/widget/layout/BaseModalLayout.vue' import NavItem from '@/components/widget/nav/NavItem.vue' import NavTitle from '@/components/widget/nav/NavTitle.vue' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { refreshBalanceInBackground } from '@/platform/billing/refreshBalanceInBackground' import { useSettingsHeaderCollapse } from '@/platform/settings/composables/useSettingsHeaderCollapse' import { cn } from '@comfyorg/tailwind-utils' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -304,7 +305,7 @@ watch(activeCategoryKey, (newKey, oldKey) => { activeCategoryKey.value = oldKey } if (newKey === 'credits') { - void fetchBalance() + void refreshBalanceInBackground(fetchBalance) } if (newKey) { void nextTick(() => { diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 6b4a02f64c9..62e85b32bae 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -12,6 +12,7 @@ import { createI18n } from 'vue-i18n' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useBillingContext } from '@/platform/billing/composables/useBillingContext' +import { reportError } from '@/platform/telemetry/reportError' import { useBillingRouting } from '@/platform/billing/composables/useBillingRouting' import type { BalanceInfo, @@ -31,6 +32,8 @@ import type { BillingStatus } from '@/platform/workspace/api/workspaceApi' import CurrentUserPopoverWorkspace from './CurrentUserPopoverWorkspace.vue' +vi.mock(import('@/platform/telemetry/reportError')) + const state = vi.hoisted(() => { function initialPlanSlug(): string | null { return 'pro-monthly' @@ -258,6 +261,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/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index 17feba3c998..4591faf975e 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -265,6 +265,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' @@ -443,6 +444,6 @@ const handleCreateWorkspace = () => { } onMounted(() => { - if (!accountActionsOnly) void fetchBalance() + if (!accountActionsOnly) void refreshBalanceInBackground(fetchBalance) })