From d9d84bb43f46339295ca283950d36fdd322aab06 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 27 Aug 2026 18:30:33 +0000 Subject: [PATCH 1/3] fix(billing): retry transient context initialization failures Amp-Thread-ID: https://ampcode.com/threads/T-01a04465-a84d-722b-a0e9-fa6a68b3861c Co-authored-by: Amp --- .../billing/useBillingContext.test.ts | 69 ++++++++++++++++++- src/composables/billing/useBillingContext.ts | 33 ++++++--- 2 files changed, 92 insertions(+), 10 deletions(-) diff --git a/src/composables/billing/useBillingContext.test.ts b/src/composables/billing/useBillingContext.test.ts index df6af53161c..59b4b907f4b 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -26,6 +26,7 @@ const DEFAULT_BILLING_STATUS: BillingStatusResponse = { const { mockIsPersonal, + mockHasActiveWorkspace, mockBillingRail, mockPlans, mockFetchPlans, @@ -36,9 +37,11 @@ const { mockUpdateActiveWorkspace, mockSetWorkspaceBillingRail, mockLegacyStatus, - mockBillingStatus + mockBillingStatus, + mockReportError } = vi.hoisted(() => ({ mockIsPersonal: { value: true }, + mockHasActiveWorkspace: { value: true }, mockBillingRail: { value: undefined as BillingRail | undefined }, mockPlans: { value: [] as Plan[] }, mockFetchPlans: vi.fn(async () => undefined), @@ -62,7 +65,8 @@ const { subscription_tier: 'PRO', subscription_duration: 'MONTHLY' } as Partial - } + }, + mockReportError: vi.fn() })) vi.mock('@vueuse/core', async (importOriginal) => { @@ -75,6 +79,10 @@ vi.mock('@vueuse/core', async (importOriginal) => { vi.mock('@/platform/distribution/types', () => ({ isCloud: true })) +vi.mock('@/platform/telemetry/reportError', () => ({ + reportError: mockReportError +})) + vi.mock('@/platform/workspace/stores/teamWorkspaceStore', async () => { const { ref } = await import('vue') const billingRailRef = ref(mockBillingRail.value) @@ -90,6 +98,7 @@ vi.mock('@/platform/workspace/stores/teamWorkspaceStore', async () => { return mockIsPersonal.value }, get activeWorkspace() { + if (!mockHasActiveWorkspace.value) return undefined return mockIsPersonal.value ? { id: 'personal-123', type: 'personal' } : { id: 'team-456', type: 'team' } @@ -142,6 +151,7 @@ vi.mock('@/composables/auth/useAuthActions', () => ({ })) vi.mock('@/stores/authStore', () => ({ + AuthStoreError: class extends Error {}, useAuthStore: () => ({ balance: { amount_micros: 5000000 }, fetchBalance: mockLegacyFetchBalance @@ -162,6 +172,7 @@ vi.mock('@/platform/cloud/subscription/composables/useBillingPlans', () => ({ })) vi.mock('@/platform/workspace/api/workspaceApi', () => ({ + WorkspaceApiError: class extends Error {}, workspaceApi: { getBillingStatus: vi.fn(() => Promise.resolve({ ...DEFAULT_BILLING_STATUS, ...mockBillingStatus.value }) @@ -181,6 +192,7 @@ describe('useBillingContext', () => { remoteConfig.value = {} remoteConfigState.value = 'unloaded' mockIsPersonal.value = true + mockHasActiveWorkspace.value = true mockBillingRail.value = undefined mockSetWorkspaceBillingRail.mockImplementation( (_workspaceId: string, billingRail: BillingRail) => { @@ -272,6 +284,59 @@ describe('useBillingContext', () => { await expect(initialize()).resolves.toBeUndefined() }) + it('recovers from a transient network failure during initialization', async () => { + vi.useFakeTimers() + 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 () => { + vi.useFakeTimers() + 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' } + }) + }) + + it('does not retry a non-network initialization failure', async () => { + mockHasActiveWorkspace.value = false + mockBillingRail.value = 'legacy_stripe' + mockLegacyFetchStatus.mockRejectedValue(new Error('Forbidden')) + + 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 f6675171099..a60abcf65b1 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() @@ -243,15 +246,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 } ) @@ -263,13 +261,32 @@ 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 + const retryDelay = INITIALIZATION_RETRY_DELAYS_MS[attempt] + if ( + retryDelay === undefined || + categorizeBillingApiError(err) !== 'network' + ) { + throw err + } + await new Promise((resolve) => setTimeout(resolve, retryDelay)) + } + } 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 From 9e4a8c9a05fcb88d9a9e83806b5c3fdb2df8fcc3 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 27 Aug 2026 18:59:28 +0000 Subject: [PATCH 2/3] fix(billing): stop stale initialization retries Amp-Thread-ID: https://ampcode.com/threads/T-01a04465-a84d-722b-a0e9-fa6a68b3861c Co-authored-by: Amp --- .../billing/useBillingContext.test.ts | 23 +++++++++++++++++++ src/composables/billing/useBillingContext.ts | 1 + 2 files changed, 24 insertions(+) diff --git a/src/composables/billing/useBillingContext.test.ts b/src/composables/billing/useBillingContext.test.ts index 59b4b907f4b..170463a4940 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -323,6 +323,29 @@ describe('useBillingContext', () => { 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 () => { + vi.useFakeTimers() + 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 non-network initialization failure', async () => { diff --git a/src/composables/billing/useBillingContext.ts b/src/composables/billing/useBillingContext.ts index a60abcf65b1..c9d98db80f8 100644 --- a/src/composables/billing/useBillingContext.ts +++ b/src/composables/billing/useBillingContext.ts @@ -275,6 +275,7 @@ function useBillingContextInternal(): BillingContext { throw err } await new Promise((resolve) => setTimeout(resolve, retryDelay)) + if (activeContext.value !== adapter) return } } if (activeContext.value !== adapter) return From a4cfd535f2d377200d44713c9274f329370c96d7 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 31 Aug 2026 19:04:45 +0000 Subject: [PATCH 3/3] fix(billing): preserve HTTP status on legacy billing failures fetchBalance and performFetchSubscriptionStatus wrapped failed responses in a status-less AuthStoreError. categorizeBillingApiError treats a status-less AuthStoreError as a transport failure, so 403/500 responses were classified as network and ran both initialization backoffs instead of failing on the first attempt. Carry response.status through the balance wrapper and WorkspaceApiError status through the subscription-status wrapper, so HTTP rejections stay api_rejected and fail immediately. --- .../billing/useBillingContext.test.ts | 20 +++++++---- .../composables/useSubscription.test.ts | 33 ++++++++++++++++++- .../composables/useSubscription.ts | 8 +++-- src/stores/authStore.test.ts | 19 +++++++++++ src/stores/authStore.ts | 3 +- 5 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/composables/billing/useBillingContext.test.ts b/src/composables/billing/useBillingContext.test.ts index 170463a4940..d95cb560ebd 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -11,6 +11,7 @@ import { remoteConfig, remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { AuthStoreError } from '@/stores/authStore' import { useBillingContext } from './useBillingContext' @@ -151,7 +152,15 @@ vi.mock('@/composables/auth/useAuthActions', () => ({ })) vi.mock('@/stores/authStore', () => ({ - AuthStoreError: class extends Error {}, + AuthStoreError: class extends Error { + constructor( + message: string, + readonly status?: number + ) { + super(message) + this.name = 'AuthStoreError' + } + }, useAuthStore: () => ({ balance: { amount_micros: 5000000 }, fetchBalance: mockLegacyFetchBalance @@ -285,7 +294,6 @@ describe('useBillingContext', () => { }) it('recovers from a transient network failure during initialization', async () => { - vi.useFakeTimers() mockHasActiveWorkspace.value = false mockBillingRail.value = 'legacy_stripe' mockLegacyFetchStatus @@ -304,7 +312,6 @@ describe('useBillingContext', () => { }) it('reports a network failure after bounded initialization retries', async () => { - vi.useFakeTimers() mockHasActiveWorkspace.value = false mockBillingRail.value = 'legacy_stripe' mockLegacyFetchStatus.mockRejectedValue(new TypeError('Failed to fetch')) @@ -331,7 +338,6 @@ describe('useBillingContext', () => { }) it('stops retrying when the billing adapter changes during backoff', async () => { - vi.useFakeTimers() mockBillingRail.value = 'legacy_stripe' mockLegacyFetchStatus .mockRejectedValueOnce(new TypeError('Failed to fetch')) @@ -348,10 +354,12 @@ describe('useBillingContext', () => { expect(mockReportError).not.toHaveBeenCalled() }) - it('does not retry a non-network initialization failure', async () => { + it('does not retry a legacy HTTP initialization failure', async () => { mockHasActiveWorkspace.value = false mockBillingRail.value = 'legacy_stripe' - mockLegacyFetchStatus.mockRejectedValue(new Error('Forbidden')) + mockLegacyFetchStatus.mockRejectedValue( + new AuthStoreError('Forbidden', 403) + ) const { initialize } = useBillingContext() diff --git a/src/platform/cloud/subscription/composables/useSubscription.test.ts b/src/platform/cloud/subscription/composables/useSubscription.test.ts index 41a548ddc14..e4761601b5d 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.test.ts @@ -3,6 +3,7 @@ import { effectScope } from 'vue' 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 { mockIsLoggedIn, @@ -142,6 +143,15 @@ vi.mock('@/platform/telemetry/utils/checkoutAttribution', () => ({ })) vi.mock('@/platform/workspace/api/workspaceApi', () => ({ + WorkspaceApiError: class extends Error { + constructor( + message: string, + readonly status?: number + ) { + super(message) + this.name = 'WorkspaceApiError' + } + }, workspaceApi: { getBillingStatus: mockGetBillingStatus } @@ -174,7 +184,15 @@ vi.mock('@/stores/authStore', () => ({ return mockUserId.value } })), - AuthStoreError: class extends Error {} + AuthStoreError: class extends Error { + constructor( + message: string, + readonly status?: number + ) { + super(message) + this.name = 'AuthStoreError' + } + } })) // Mock fetch @@ -344,6 +362,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 d40d84bef7a..4a504d0c7af 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' @@ -394,7 +397,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 637e6df2636..62f05b20000 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -372,6 +372,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('user-scoped billing endpoints with API-key sessions', () => { diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index 59d105f4a5c..45139339d84 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -453,7 +453,8 @@ export const useAuthStore = defineStore('auth', () => { throw new AuthStoreError( t('toastMessages.failedToFetchBalance', { error: message - }) + }), + response.status ) }