Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 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 '@/platform/telemetry/reportError'

Check warning on line 4 in src/components/topbar/CurrentUserPopoverLegacy.test.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'authentication/presentation' to zone 'error-reporting/application' is not allowed. src/components/topbar/CurrentUserPopoverLegacy.test.ts -> src/platform/telemetry/reportError.ts Route the import through an allowed zone or restructure the dependency.
import { getActivePinia } from 'pinia'
import { render, screen } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
Expand All @@ -20,6 +21,8 @@

import CurrentUserPopoverLegacy from './CurrentUserPopoverLegacy.vue'

vi.mock(import('@/platform/telemetry/reportError'))

Check warning on line 24 in src/components/topbar/CurrentUserPopoverLegacy.test.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'authentication/presentation' to zone 'error-reporting/application/outer-1' is not allowed. src/components/topbar/CurrentUserPopoverLegacy.test.ts -> src/platform/telemetry/__mocks__/reportError.ts Route the import through an allowed zone or restructure the dependency.

vi.mock(import('@/platform/settings/composables/useSettingsDialog'))

const originalWindowOpen = window.open
Expand Down Expand Up @@ -140,6 +143,22 @@
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 @@ -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'
Expand Down Expand Up @@ -250,6 +251,6 @@ const handleLogout = async () => {
}

onMounted(() => {
void fetchBalance()
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 @@ -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<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 @@ -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
)
}
Expand All @@ -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)
Expand All @@ -409,21 +413,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 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
Expand Down
58 changes: 58 additions & 0 deletions src/platform/billing/refreshBalanceInBackground.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
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 '@/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<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'
})
}
)
}
36 changes: 36 additions & 0 deletions src/platform/settings/components/SettingDialog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
import type { Ref } from 'vue'

import { i18n } from '@/i18n'
import { useBillingContext } from '@/platform/billing/composables/useBillingContext'

Check warning on line 8 in src/platform/settings/components/SettingDialog.test.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'settings/presentation' to zone 'billing/application' is not allowed. src/platform/settings/components/SettingDialog.test.ts -> src/platform/billing/composables/useBillingContext.ts Route the import through an allowed zone or restructure the dependency.
import { reportError } from '@/platform/telemetry/reportError'

Check warning on line 9 in src/platform/settings/components/SettingDialog.test.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'settings/presentation' to zone 'error-reporting/application' is not allowed. src/platform/settings/components/SettingDialog.test.ts -> src/platform/telemetry/reportError.ts Route the import through an allowed zone or restructure the dependency.
import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
import type { NavGroupData } from '@/types/navTypes'

import SettingDialog from './SettingDialog.vue'

vi.mock(import('@/platform/telemetry/reportError'))

Check warning on line 15 in src/platform/settings/components/SettingDialog.test.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'settings/presentation' to zone 'error-reporting/application/outer-1' is not allowed. src/platform/settings/components/SettingDialog.test.ts -> src/platform/telemetry/__mocks__/reportError.ts Route the import through an allowed zone or restructure the dependency.

const settingUiMocks = vi.hoisted(() => ({
navGroups: null as unknown as Ref<NavGroupData[]>
}))
Expand Down Expand Up @@ -300,3 +304,35 @@
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 @@ -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'
Expand Down Expand Up @@ -304,7 +305,7 @@ watch(activeCategoryKey, (newKey, oldKey) => {
activeCategoryKey.value = oldKey
}
if (newKey === 'credits') {
void fetchBalance()
void refreshBalanceInBackground(fetchBalance)
}
if (newKey) {
void nextTick(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import { useCurrentUser } from '@/composables/auth/useCurrentUser'
import { useBillingContext } from '@/platform/billing/composables/useBillingContext'
import { reportError } from '@/platform/telemetry/reportError'

Check warning on line 15 in src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'workspace/presentation' to zone 'error-reporting/application' is not allowed. src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts -> src/platform/telemetry/reportError.ts Route the import through an allowed zone or restructure the dependency.
import { useBillingRouting } from '@/platform/billing/composables/useBillingRouting'
import type {
BalanceInfo,
Expand All @@ -31,6 +32,8 @@

import CurrentUserPopoverWorkspace from './CurrentUserPopoverWorkspace.vue'

vi.mock(import('@/platform/telemetry/reportError'))

Check warning on line 35 in src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts

View workflow job for this annotation

GitHub Actions / fallow / fallow

Boundary violation

Import from zone 'workspace/presentation' to zone 'error-reporting/application/outer-1' is not allowed. src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts -> src/platform/telemetry/__mocks__/reportError.ts Route the import through an allowed zone or restructure the dependency.

const state = vi.hoisted(() => {
function initialPlanSlug(): string | null {
return 'pro-monthly'
Expand Down Expand Up @@ -258,6 +261,22 @@
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 @@ -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'
Expand Down Expand Up @@ -443,6 +444,6 @@ const handleCreateWorkspace = () => {
}

onMounted(() => {
if (!accountActionsOnly) void fetchBalance()
if (!accountActionsOnly) void refreshBalanceInBackground(fetchBalance)
})
</script>
Loading