diff --git a/src/composables/billing/useBillingContext.test.ts b/src/composables/billing/useBillingContext.test.ts index dd19f58c693..f0581fad9e1 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -1,10 +1,10 @@ import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' -import { effectScope, nextTick, computed } from 'vue' +import { effectScope, nextTick, computed, ref } from 'vue' import type { Ref } from 'vue' import { storeToRefs } from 'pinia' import { fromPartial } from '@total-typescript/shoehorn' import { useAuthActions } from '@/composables/auth/useAuthActions' -import { useAuthStore } from '@/stores/authStore' +import { AuthStoreError, useAuthStore } from '@/stores/authStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { workspaceApi } from '@/platform/workspace/api/workspaceApi' @@ -73,6 +73,7 @@ const { let mockIsPersonal: Ref let mockBillingRail: Ref +const mockHasActiveWorkspace = ref(true) vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) @@ -141,9 +142,24 @@ vi.mock(import('@/platform/workspace/api/workspaceApi'), () => ({ subscribe: vi.fn(async () => ({ status: 'subscribed' })), previewSubscribe: vi.fn(async () => ({ allowed: true })), createTopup: vi.fn(async () => undefined) + }, + WorkspaceApiError: class WorkspaceApiError extends Error { + constructor( + message: string, + public readonly status?: number, + public readonly code?: string + ) { + super(message) + this.name = 'WorkspaceApiError' + } } })) +const mockReportError = vi.hoisted(() => vi.fn()) +vi.mock(import('@/platform/telemetry/reportError'), () => ({ + reportError: mockReportError +})) + describe('useBillingContext', () => { beforeEach(() => { const workspaceStore = useTeamWorkspaceStore() @@ -152,10 +168,12 @@ describe('useBillingContext', () => { mockBillingRail = refs.activeWorkspaceBillingRail Object.assign(workspaceStore, { activeWorkspace: computed(() => - fromPartial>({ - id: mockIsPersonal.value ? 'personal-123' : 'team-456', - type: mockIsPersonal.value ? 'personal' : 'team' - }) + mockHasActiveWorkspace.value + ? fromPartial>({ + id: mockIsPersonal.value ? 'personal-123' : 'team-456', + type: mockIsPersonal.value ? 'personal' : 'team' + }) + : undefined ) }) const authStore = useAuthStore() @@ -165,6 +183,7 @@ describe('useBillingContext', () => { remoteConfig.value = {} remoteConfigState.value = 'unloaded' mockIsPersonal.value = true + mockHasActiveWorkspace.value = true mockBillingRail.value = undefined vi.mocked( useTeamWorkspaceStore().setWorkspaceBillingRail @@ -258,6 +277,81 @@ describe('useBillingContext', () => { await expect(initialize()).resolves.toBeUndefined() }) + it('recovers from a transient network failure during initialization', async () => { + mockHasActiveWorkspace.value = false + mockBillingRail.value = 'legacy_stripe' + mockLegacyFetchStatus + .mockRejectedValueOnce(new TypeError('Failed to fetch')) + .mockResolvedValue(undefined) + + const { initialize, isInitialized } = useBillingContext() + const initialization = initialize() + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(500) + await initialization + + expect(mockLegacyFetchStatus).toHaveBeenCalledTimes(2) + expect(isInitialized.value).toBe(true) + expect(mockReportError).not.toHaveBeenCalled() + }) + + it('reports a network failure after bounded initialization retries', async () => { + mockHasActiveWorkspace.value = false + mockBillingRail.value = 'legacy_stripe' + mockLegacyFetchStatus.mockRejectedValue(new TypeError('Failed to fetch')) + + const { initialize, isInitialized } = useBillingContext() + const initialization = initialize() + const result = initialization.catch((error: unknown) => error) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(2_500) + + expect(await result).toEqual(expect.any(TypeError)) + expect(mockLegacyFetchStatus).toHaveBeenCalledTimes(3) + expect(isInitialized.value).toBe(false) + expect(mockReportError).toHaveBeenCalledOnce() + expect(mockReportError).toHaveBeenCalledWith(expect.any(TypeError), { + errorType: 'billing_context_initialization_failure', + tags: { billing_backend: 'legacy' } + }) + + mockLegacyFetchStatus.mockResolvedValue(undefined) + await expect(initialize()).resolves.toBeUndefined() + expect(mockLegacyFetchStatus).toHaveBeenCalledTimes(4) + expect(isInitialized.value).toBe(true) + }) + + it('stops retrying when the billing adapter changes during backoff', async () => { + mockBillingRail.value = 'legacy_stripe' + mockLegacyFetchStatus + .mockRejectedValueOnce(new TypeError('Failed to fetch')) + .mockResolvedValue(undefined) + + useBillingContext() + await vi.advanceTimersByTimeAsync(0) + + mockBillingRail.value = undefined + await nextTick() + await vi.advanceTimersByTimeAsync(500) + + expect(mockLegacyFetchStatus).toHaveBeenCalledOnce() + expect(mockReportError).not.toHaveBeenCalled() + }) + + it('does not retry a legacy HTTP initialization failure', async () => { + mockHasActiveWorkspace.value = false + mockBillingRail.value = 'legacy_stripe' + mockLegacyFetchStatus.mockRejectedValue( + new AuthStoreError('Forbidden', 403) + ) + + const { initialize } = useBillingContext() + + await expect(initialize()).rejects.toThrow('Forbidden') + expect(mockLegacyFetchStatus).toHaveBeenCalledOnce() + expect(mockReportError).toHaveBeenCalledOnce() + }) + it('exposes fetchStatus action', async () => { const { fetchStatus } = useBillingContext() await expect(fetchStatus()).resolves.toBeUndefined() diff --git a/src/composables/billing/useBillingContext.ts b/src/composables/billing/useBillingContext.ts index 4d25ba306ff..e01602ae0e8 100644 --- a/src/composables/billing/useBillingContext.ts +++ b/src/composables/billing/useBillingContext.ts @@ -12,6 +12,8 @@ import type { PreviewSubscribeOptions, SubscribeOptions } from '@/platform/workspace/api/workspaceApi' +import { reportError } from '@/platform/telemetry/reportError' +import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import type { @@ -31,6 +33,7 @@ import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspa // new sub is never misrouted even before its credit stop is populated. const LEGACY_TEAM_PLAN_SLUG_PREFIX = 'team-' const PER_CREDIT_TEAM_PLAN_SLUG_PREFIX = 'team_per_credit_' +const INITIALIZATION_RETRY_DELAYS_MS = [500, 2_000] function isTeamPlanSlug(planSlug: string | null | undefined): boolean { const normalizedSlug = planSlug?.toLowerCase() @@ -240,15 +243,10 @@ function useBillingContextInternal(): BillingContext { // Reset and reinitialize when the active workspace or billing backend changes. watch( [() => store.activeWorkspace?.id, () => type.value], - async ([newWorkspaceId]) => { + ([newWorkspaceId]) => { resetBillingState() if (!newWorkspaceId) return - - try { - await initialize() - } catch (err) { - console.error('Failed to initialize billing context:', err) - } + void initialize().catch(() => {}) }, { immediate: true } ) @@ -260,13 +258,33 @@ function useBillingContextInternal(): BillingContext { isLoading.value = true error.value = null try { - await adapter.initialize() + for (let attempt = 0; ; attempt++) { + try { + await adapter.initialize() + break + } catch (err) { + if (activeContext.value !== adapter) return + if ( + attempt >= INITIALIZATION_RETRY_DELAYS_MS.length || + categorizeBillingApiError(err) !== 'network' + ) { + throw err + } + const retryDelay = INITIALIZATION_RETRY_DELAYS_MS[attempt] + await new Promise((resolve) => setTimeout(resolve, retryDelay)) + if (activeContext.value !== adapter) return + } + } if (activeContext.value !== adapter) return isInitialized.value = true } catch (err) { if (activeContext.value !== adapter) return error.value = err instanceof Error ? err.message : 'Failed to initialize billing' + reportError(err, { + errorType: 'billing_context_initialization_failure', + tags: { billing_backend: type.value } + }) throw err } finally { if (activeContext.value === adapter) isLoading.value = false diff --git a/src/platform/cloud/subscription/composables/useSubscription.test.ts b/src/platform/cloud/subscription/composables/useSubscription.test.ts index 885f466be9d..67e46f4a673 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.test.ts @@ -8,6 +8,7 @@ import { useAuthActions } from '@/composables/auth/useAuthActions' import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription' import { PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY } from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' +import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' const { mockGetAuthHeader, @@ -135,6 +136,16 @@ vi.mock( vi.mock(import('@/platform/workspace/api/workspaceApi'), () => ({ workspaceApi: { getBillingStatus: mockGetBillingStatus + }, + WorkspaceApiError: class WorkspaceApiError extends Error { + constructor( + message: string, + public readonly status?: number, + public readonly code?: string + ) { + super(message) + this.name = 'WorkspaceApiError' + } } })) @@ -321,6 +332,19 @@ describe('useSubscription', () => { ) }) + it('preserves the HTTP status of a rejected billing status request', async () => { + mockGetBillingStatus.mockRejectedValue( + new WorkspaceApiError('Forbidden', 403) + ) + + const { fetchStatus } = useSubscriptionWithScope() + + await expect(fetchStatus()).rejects.toMatchObject({ + name: 'AuthStoreError', + status: 403 + }) + }) + it('updates the active workspace billing rail from status', async () => { mockGetBillingStatus.mockResolvedValue({ is_active: true, diff --git a/src/platform/cloud/subscription/composables/useSubscription.ts b/src/platform/cloud/subscription/composables/useSubscription.ts index 370f024fb76..573518afb48 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.ts @@ -19,7 +19,10 @@ import type { ResubscribeClickMetadata } from '@/platform/telemetry/types' import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' -import { workspaceApi } from '@/platform/workspace/api/workspaceApi' +import { + WorkspaceApiError, + workspaceApi +} from '@/platform/workspace/api/workspaceApi' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { AuthStoreError, useAuthStore } from '@/stores/authStore' import { useDialogService } from '@/services/dialogService' @@ -393,7 +396,8 @@ function useSubscriptionInternal() { throw new AuthStoreError( t('toastMessages.failedToFetchSubscription', { error: error instanceof Error ? error.message : String(error) - }) + }), + error instanceof WorkspaceApiError ? error.status : undefined ) } if ( diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index c1dc046eeca..73eec9d12a4 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -281,6 +281,25 @@ describe('useAuthStore', () => { expect(await pending).toBeNull() expect(store.balance).toBeNull() }) + + it('preserves the HTTP status when a non-404 balance response fails', async () => { + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers/balance')) { + return Promise.resolve({ + ok: false, + status: 403, + statusText: 'Forbidden', + text: () => Promise.resolve('') + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + + await expect(store.fetchBalance()).rejects.toMatchObject({ + name: 'AuthStoreError', + status: 403 + }) + }) }) describe('password update', () => { diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index a553a6d8b15..155810c6837 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -445,7 +445,8 @@ export const useAuthStore = defineStore('auth', () => { throw new AuthStoreError( t('toastMessages.failedToFetchBalance', { error: message - }) + }), + response.status ) }