Skip to content
Merged
17 changes: 17 additions & 0 deletions src/components/topbar/CurrentUserPopoverLegacy.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion src/components/topbar/CurrentUserPopoverLegacy.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -253,6 +254,6 @@ const handleLogout = async () => {
}

onMounted(() => {
void fetchBalance()
void refreshBalanceInBackground(fetchBalance)
})
</script>
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -450,6 +451,6 @@ const handleCreateWorkspace = () => {
}

onMounted(() => {
if (!accountActionsOnly) void fetchBalance()
if (!accountActionsOnly) void refreshBalanceInBackground(fetchBalance)
})
</script>
50 changes: 50 additions & 0 deletions src/platform/billing/composables/useWorkspaceBilling.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof zeroBalance>()
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<typeof zeroBalance>()
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<typeof zeroBalance>()
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', () => {
Expand Down
23 changes: 15 additions & 8 deletions src/platform/billing/composables/useWorkspaceBilling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
}
Expand All @@ -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)
Expand All @@ -406,21 +410,24 @@ export function useWorkspaceBilling(): WorkspaceBilling {

async function fetchBalance(): Promise<void> {
const requestId = ++latestBillingReadIds.balance
const workspaceId = workspaceStore.activeWorkspace?.id
const rail: BillingReadRail | null = useBillingReadRail()
isLoading.value = true
error.value = null
try {
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
Expand Down
56 changes: 56 additions & 0 deletions src/platform/billing/refreshBalanceInBackground.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
23 changes: 23 additions & 0 deletions src/platform/billing/refreshBalanceInBackground.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>
): Promise<void> {
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'
})
}
)
}
34 changes: 34 additions & 0 deletions src/platform/settings/components/SettingDialog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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()
})
3 changes: 2 additions & 1 deletion src/platform/settings/components/SettingDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -307,7 +308,7 @@ watch(activeCategoryKey, (newKey, oldKey) => {
activeCategoryKey.value = oldKey
}
if (newKey === 'credits') {
void fetchBalance()
void refreshBalanceInBackground(fetchBalance)
}
if (newKey) {
void nextTick(() => {
Expand Down
Loading