Skip to content
Closed
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
106 changes: 100 additions & 6 deletions src/composables/billing/useBillingContext.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -73,6 +73,7 @@ const {

let mockIsPersonal: Ref<boolean>
let mockBillingRail: Ref<BillingRail | null | undefined>
const mockHasActiveWorkspace = ref(true)

vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true }))

Expand Down Expand Up @@ -141,9 +142,24 @@ vi.mock<unknown>(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()
Expand All @@ -152,10 +168,12 @@ describe('useBillingContext', () => {
mockBillingRail = refs.activeWorkspaceBillingRail
Object.assign(workspaceStore, {
activeWorkspace: computed(() =>
fromPartial<NonNullable<typeof workspaceStore.activeWorkspace>>({
id: mockIsPersonal.value ? 'personal-123' : 'team-456',
type: mockIsPersonal.value ? 'personal' : 'team'
})
mockHasActiveWorkspace.value
? fromPartial<NonNullable<typeof workspaceStore.activeWorkspace>>({
id: mockIsPersonal.value ? 'personal-123' : 'team-456',
type: mockIsPersonal.value ? 'personal' : 'team'
})
: undefined
)
})
const authStore = useAuthStore()
Expand All @@ -165,6 +183,7 @@ describe('useBillingContext', () => {
remoteConfig.value = {}
remoteConfigState.value = 'unloaded'
mockIsPersonal.value = true
mockHasActiveWorkspace.value = true
mockBillingRail.value = undefined
vi.mocked(
useTeamWorkspaceStore().setWorkspaceBillingRail
Expand Down Expand Up @@ -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()
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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()
Expand Down
34 changes: 26 additions & 8 deletions src/composables/billing/useBillingContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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()
Expand Down Expand Up @@ -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 }
)
Expand All @@ -260,13 +258,33 @@ function useBillingContextInternal(): BillingContext {
isLoading.value = true
error.value = null
try {
await adapter.initialize()
for (let attempt = 0; ; attempt++) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isInitialized remains false for the entire backoff, so the immediate watcher and an explicit caller can enter separate retry loops against the same adapter and both report the terminal failure. Could we cache and return an adapter-scoped in-flight initialization promise here, following the existing fetchSubscriptionStatus coalescing pattern? Current-head visual evidence.

try {
await adapter.initialize()
break
} catch (err) {
if (activeContext.value !== adapter) return
if (
attempt >= INITIALIZATION_RETRY_DELAYS_MS.length ||
categorizeBillingApiError(err) !== 'network'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we preserve the HTTP status when fetchBalance() wraps non-404 responses in AuthStoreError? Those errors are currently status-less, so categorizeBillingApiError(err) classifies 403/500 responses as network here and runs both backoffs (three initialization attempts) instead of failing immediately. Please add a regression test through the real legacy AuthStoreError HTTP path. Visual evidence for this head.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in a4cfd53 — thanks, this was a real misclassification.

Root cause. AuthStoreError has always accepted a status, but the two legacy initialization paths dropped it when wrapping:

  • authStore.fetchBalance() (src/stores/authStore.ts:453) threw the non-404 wrapper without response.status.
  • performFetchSubscriptionStatus() (src/platform/cloud/subscription/composables/useSubscription.ts:397) wrapped the underlying WorkspaceApiError without carrying its status.

categorizeBillingApiError() treats a status-less AuthStoreError/WorkspaceApiError as network (no status ⇒ never reached the backend), so a 403/500 on the legacy rail was categorized network and ran both backoffs — three attempts against a request the server had already rejected.

Fix. Carry the server-provided status through both wrappers. Nothing is inferred client-side: response.status for the balance path, error.status off the real WorkspaceApiError for the status path. HTTP rejections now categorize as api_rejected and fail on the first attempt; genuine transport failures still have no status and still retry.

Regression coverage — both new tests fail on the parent commit with status: undefined, which is exactly the reported symptom:

  • src/stores/authStore.test.ts — real HTTP path: mocked 403 balance response ⇒ AuthStoreError with status: 403.
  • src/platform/cloud/subscription/composables/useSubscription.test.ts — real WorkspaceApiError('Forbidden', 403) ⇒ rethrown AuthStoreError retains status: 403.
  • src/composables/billing/useBillingContext.test.ts — the former does not retry a non-network initialization failure now drives the legacy AuthStoreError('Forbidden', 403) and asserts a single attempt.

I checked the rest of the initialization surface for the same class of bug: the workspace rail propagates raw WorkspaceApiError (status intact) from getBillingStatus/getBillingBalance, and the remaining status-less AuthStoreError throws are unauthenticated/checkout paths that are not on the init path.

Also folded in CodeRabbit's non-blocking timer nit: the three in-test vi.useFakeTimers() calls were redundant — vitest.timer.setup.ts (wired at vite.config.mts:793) already installs fake timers in beforeEach and restores them in afterEach.

Verification: pnpm test:unit across src/stores/authStore.test.ts src/composables/billing src/platform/cloud/subscription src/platform/workspace src/platform/telemetry — 122 files, 2245 passed. pnpm typecheck clean; oxfmt, type-aware oxlint, and ESLint clean via pre-commit hooks.

) {
throw err
}
const retryDelay = INITIALIZATION_RETRY_DELAYS_MS[attempt]
await new Promise((resolve) => setTimeout(resolve, retryDelay))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -135,6 +136,16 @@ vi.mock<unknown>(
vi.mock<unknown>(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'
}
}
}))

Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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 (
Expand Down
19 changes: 19 additions & 0 deletions src/stores/authStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
3 changes: 2 additions & 1 deletion src/stores/authStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,8 @@ export const useAuthStore = defineStore('auth', () => {
throw new AuthStoreError(
t('toastMessages.failedToFetchBalance', {
error: message
})
}),
response.status
)
}

Expand Down
Loading