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
70 changes: 70 additions & 0 deletions src/platform/workspace/stores/billingOperationStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ vi.mock<unknown>(import('@/composables/useFeatureFlags'), () => ({
})
}))

const mockReportError = vi.hoisted(() => vi.fn())

vi.mock<unknown>(import('@/platform/telemetry/reportError'), () => ({
reportError: mockReportError
}))

vi.mock<unknown>(import('@/platform/workspace/api/workspaceApi'), () => ({
workspaceApi: {
getBillingOpStatus: vi.fn()
Expand Down Expand Up @@ -755,6 +761,70 @@ describe('billingOperationStore', () => {

expect(useToastStore().remove).toHaveBeenCalledWith(receivedToast)
})

it('resolves the terminal promise even if a success side effect throws', async () => {
vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({
id: 'op-1',
status: 'succeeded',
started_at: new Date().toISOString()
})
const error = new Error('toast rendering failed')
vi.mocked(useToastStore().add).mockImplementation((toast) => {
if (toast.severity === 'success') throw error
})

const store = useBillingOperationStore()
const terminal = store.startOperation('op-1', 'topup')

await vi.advanceTimersByTimeAsync(0)

await expect(terminal).resolves.toMatchObject({ status: 'succeeded' })
expect(mockReportError).toHaveBeenCalledWith(error, {
errorType: 'failure_handling_billing_operation_success',
context: { billing_op_id: 'op-1' }
})
})

it('resolves the terminal promise even if cleanup throws', async () => {
vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({
id: 'op-1',
status: 'succeeded',
started_at: new Date().toISOString()
})
const error = new Error('toast cleanup failed')
vi.mocked(useToastStore().remove).mockImplementationOnce(() => {
throw error
})

const store = useBillingOperationStore()
const terminal = store.startOperation('op-1', 'subscription')

await vi.advanceTimersByTimeAsync(0)

await expect(terminal).resolves.toMatchObject({ status: 'succeeded' })
expect(mockReportError).toHaveBeenCalledWith(error, {
errorType: 'failure_handling_billing_operation_success',
context: { billing_op_id: 'op-1' }
})
})

it('resolves the terminal promise even if reconciliation throws synchronously', async () => {
vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({
id: 'op-1',
status: 'succeeded',
started_at: new Date().toISOString()
})
mockReconcileSubscriptionSuccess.mockImplementationOnce(() => {
throw new Error('reconcile failed')
})

const store = useBillingOperationStore()
const terminal = store.startOperation('op-1', 'subscription')

await vi.advanceTimersByTimeAsync(0)

await expect(terminal).resolves.toMatchObject({ status: 'succeeded' })

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion (non-blocking): could this case assert mockReportError too?

Its two siblings above pin both halves of the new contract (terminal resolution and the report), and this is the case where a silent regression is easiest to introduce. The throw only reaches the catch because it happens while the arguments to Promise.allSettled are being evaluated; if reconcileSubscriptionSuccess ever becomes a rejected promise instead of a synchronous throw, allSettled swallows it, the terminal promise still resolves succeeded, and this test keeps passing while the reporting path is no longer exercised at all.

})
})

describe('polling failure', () => {
Expand Down
198 changes: 104 additions & 94 deletions src/platform/workspace/stores/billingOperationStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type { BillingCycle } from '@/platform/cloud/subscription/utils/subscript
import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog'
import { isCloud } from '@/platform/distribution/types'
import { useTelemetry } from '@/platform/telemetry'
import { reportError } from '@/platform/telemetry/reportError'
import type {
BillingFailure,
PaymentIntentSource,
Expand Down Expand Up @@ -670,121 +671,130 @@ export const useBillingOperationStore = defineStore('billingOperation', () => {
if (!operation) return

updateOperationStatus(opId, 'succeeded', null)
cleanup(opId)

const telemetry = useTelemetry()
const now = Date.now()
const operationDurationMs = now - operation.operationStartedAt
telemetry?.trackBillingEvent({
operation: 'operation',
stage: 'succeeded',
outcome: 'success',
billing_op_id: opId,
operation_type: operation.type,
tier: operation.tier,
cycle: operation.cycle,
checkout_type: operation.checkoutType,
payment_intent_source: operation.paymentIntentSource,
duration_ms: operationDurationMs
})
try {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

question: the try starts wider than the summary describes, and I want to check that is deliberate.

The summary says it wraps "the success-path side-effects block (closeDialog, settingsDialog.show, toastStore.add)". The try actually opens here and covers cleanup(opId), every trackBillingEvent call, trackMonthlySubscriptionSucceeded, the useBillingContext() / useBillingCapabilities() lookups and the await Promise.allSettled(...) refreshes, and the cancel branch — well before the three calls named.

I think wider is correct here: a throw from useTelemetry() or useBillingContext() stranded the caller just as thoroughly as a throw from toastStore.add, so narrowing it would leave the bug half-fixed. My concern is that the description understates it, which matters for what the change now guarantees: after this, a throw in cleanup resolves the terminal promise as succeeded while telemetry, the balance refresh, and the success toast never ran. The caller cannot distinguish that from a clean success. Given updateOperationStatus(opId, 'succeeded', null) already ran on line 619 that is defensible, but it is a real semantic the summary does not mention.

Could the summary be updated to say the whole post-status block is wrapped? And is a partial-success outcome something the callers of startOperation() need to be able to see, or is the Sentry/reportError signal considered sufficient?

On coverage: the new test throws from the second mockToastAdd, which exercises the tail of the block. Nothing covers a throw from cleanup or from the telemetry calls, which are the parts this widening newly protects — one more case throwing from cleanup would pin the wider contract you actually shipped.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed deliberate. The PR summary now states that the whole post-status block is protected and documents the partial-success contract: callers receive the authoritative succeeded result, while reportError records later side-effect failures. fc3464c adds the requested cleanup-throw regression.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deliberate, and your enumeration is exact. Re-read it at dabc3c9: the try opens at cleanup(opId), immediately after updateOperationStatus(opId, 'succeeded', null), and runs to toastStore.add. Covered: cleanup(), the useTelemetry() lookup and all four trackBillingEvent calls, trackMonthlySubscriptionSucceeded, the useBillingContext() / useBillingCapabilities() lookups and their Promise.allSettled refreshes (the array literal can still throw synchronously even though allSettled itself never rejects), the cancel early return, closeDialog / settingsDialog.show, and toastStore.add.

updateOperationStatus is the one statement deliberately left outside. resolveTerminal() resolves with whatever the operation map holds, so the status write has to land before anything can reach the finally, otherwise the promise would resolve with a still-pending operation.

Your poll point checks out. pollOnce's catch takes no binding, and by the time it runs operations.value.get(opId) is the replaced succeeded entry, so the currentOperation !== operation guard returns early. Nothing reschedules, nothing surfaces, and poll() does not rethrow either. The reportError call really is the only signal, which is why the sink question in the other thread mattered.

On whether callers need to see partial success: today, no. The only caller is TopUpCreditsDialogContentWorkspace.vue:564, and its .then() does nothing but clear paymentSubmitted. It never reads the resolved operation. The pre-fix failure was that dialog sitting in a submitting state forever because the promise never settled. If a caller ever does need to branch on it, that wants an explicit field on the operation rather than a rejected terminal promise, since the operation did succeed.

Fixed the description rather than the code: it now has a "Scope of the guarded block" section naming the real boundary instead of the three tail calls, and spells out the pollOnce swallow. Also merged main into the branch, which was conflicting.

cleanup(opId)

if (
operation.type === 'subscription' &&
operation.businessAttemptStartedAt !== undefined
) {
const durationMs = now - operation.businessAttemptStartedAt
const telemetry = useTelemetry()
const now = Date.now()
const operationDurationMs = now - operation.operationStartedAt
telemetry?.trackBillingEvent({

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion (non-blocking): one try guarantees the promise, but it does not isolate the effects from each other — the first thrower still skips every effect after it.

telemetry?.trackBillingEvent() is the most plausible synchronous thrower in this block, since useTelemetry() fans out to whatever providers happen to be registered. A throw here skips the billingContext.fetchStatus() / fetchBalance() / capabilities.refresh() refreshes at L751-L763 and the success toast at L784, so the caller gets a resolved succeeded operation while the plan and credit balance rendered in the UI stay stale and no success toast ever appears.

This is not a regression — main skips the same effects, it just also hangs — so it should not block the PR. But if the property you want is "an authoritative success is always fully applied", the telemetry calls are the cheapest thing to move into their own guard, since nothing downstream of them depends on them.

operation: 'subscription_checkout',
operation: 'operation',
stage: 'succeeded',
outcome: 'success',
billing_op_id: opId,
operation_type: operation.type,
tier: operation.tier,
cycle: operation.cycle,
checkout_type: operation.checkoutType,
payment_intent_source: operation.paymentIntentSource,
billing_op_id: opId,
duration_ms: durationMs
duration_ms: operationDurationMs
})
// Also fires the legacy event for providers (Mixpanel, GTM) that don't
// implement trackBillingEvent. Gated to actual new/upgraded
// subscriptions — a downgrade-to-personal is churn, not a conversion,
// and this event drives a GA4 "subscription succeeded" conversion goal.
if (!operation.downgradeToPersonal) {
telemetry?.trackMonthlySubscriptionSucceeded({

if (
operation.type === 'subscription' &&
operation.businessAttemptStartedAt !== undefined
) {
const durationMs = now - operation.businessAttemptStartedAt
telemetry?.trackBillingEvent({
operation: 'subscription_checkout',
stage: 'succeeded',
outcome: 'success',
tier: operation.tier,
cycle: operation.cycle,
checkout_type: operation.checkoutType,
payment_intent_source: operation.paymentIntentSource,
billing_op_id: opId
billing_op_id: opId,
duration_ms: durationMs
})
// Also fires the legacy event for providers (Mixpanel, GTM) that don't
// implement trackBillingEvent. Gated to actual new/upgraded
// subscriptions — a downgrade-to-personal is churn, not a conversion,
// and this event drives a GA4 "subscription succeeded" conversion goal.
if (!operation.downgradeToPersonal) {
telemetry?.trackMonthlySubscriptionSucceeded({
tier: operation.tier,
cycle: operation.cycle,
checkout_type: operation.checkoutType,
payment_intent_source: operation.paymentIntentSource,
billing_op_id: opId
})
}
} else if (
operation.type === 'topup' &&
operation.businessAttemptStartedAt !== undefined
) {
telemetry?.trackBillingEvent({
operation: 'topup',
stage: 'succeeded',
outcome: 'success',
billing_op_id: opId,
duration_ms: now - operation.businessAttemptStartedAt
})
}
// Mirrors handleFailure's structure: not gated on businessAttemptStartedAt,
// since a downgrade always has its own startedAt for duration_ms below.
if (operation.downgradeToPersonal) {
telemetry?.trackBillingEvent({
operation: 'downgrade_to_personal',
stage: 'succeeded',
outcome: 'success',
member_removal_count:
operation.downgradeToPersonal.memberRemovalCount,
member_removal_failures:
operation.downgradeToPersonal.memberRemovalFailures,
target_tier: operation.downgradeToPersonal.targetTier,
duration_ms: now - operation.downgradeToPersonal.startedAt
})
}
} else if (
operation.type === 'topup' &&
operation.businessAttemptStartedAt !== undefined
) {
telemetry?.trackBillingEvent({
operation: 'topup',
stage: 'succeeded',
outcome: 'success',
billing_op_id: opId,
duration_ms: now - operation.businessAttemptStartedAt
})
}
// Mirrors handleFailure's structure: not gated on businessAttemptStartedAt,
// since a downgrade always has its own startedAt for duration_ms below.
if (operation.downgradeToPersonal) {
telemetry?.trackBillingEvent({
operation: 'downgrade_to_personal',
stage: 'succeeded',
outcome: 'success',
member_removal_count: operation.downgradeToPersonal.memberRemovalCount,
member_removal_failures:
operation.downgradeToPersonal.memberRemovalFailures,
target_tier: operation.downgradeToPersonal.targetTier,
duration_ms: now - operation.downgradeToPersonal.startedAt
})
}

const billingContext = useBillingContext()
const capabilities = useBillingCapabilities()
if (operation.type === 'subscription') {
await Promise.allSettled([
billingContext.reconcileSubscriptionSuccess(),
capabilities.refresh()
])
} else {
await Promise.allSettled([
billingContext.fetchStatus(),
billingContext.fetchBalance(),
capabilities.refresh()
])
}

if (operation.type === 'cancel') {
useTeamWorkspaceStore().updateActiveWorkspace({ isSubscribed: false })
resolveTerminal(opId)
return
}
const billingContext = useBillingContext()
const capabilities = useBillingCapabilities()
if (operation.type === 'subscription') {
await Promise.allSettled([
billingContext.reconcileSubscriptionSuccess(),
capabilities.refresh()
])
} else {
await Promise.allSettled([
billingContext.fetchStatus(),
billingContext.fetchBalance(),
capabilities.refresh()
])
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// A subscription checkout shows its own success step in the pricing dialog,
// so leave it open. Top-ups have no such step: close and surface settings.
if (operation.type === 'topup') {
useDialogStore().closeDialog({ key: 'top-up-credits' })
useSettingsDialog().show(isCloud ? 'workspace' : 'credits')
}
if (operation.type === 'cancel') {
useTeamWorkspaceStore().updateActiveWorkspace({ isSubscribed: false })
return
}

const toastStore = useToastStore()
const messageKey =
operation.type === 'subscription'
? 'billingOperation.subscriptionSuccess'
: 'billingOperation.topupSuccess'
// A subscription checkout shows its own success step in the pricing dialog,
// so leave it open. Top-ups have no such step: close and surface settings.
if (operation.type === 'topup') {
useDialogStore().closeDialog({ key: 'top-up-credits' })
useSettingsDialog().show(isCloud ? 'workspace' : 'credits')
}

toastStore.add({
severity: 'success',
summary: t(messageKey),
life: 5000
})
const toastStore = useToastStore()
const messageKey =
operation.type === 'subscription'
? 'billingOperation.subscriptionSuccess'
: 'billingOperation.topupSuccess'

resolveTerminal(opId)
toastStore.add({
severity: 'success',
summary: t(messageKey),
life: 5000
})
} catch (error) {
reportError(error, {
errorType: 'failure_handling_billing_operation_success',
context: { billing_op_id: opId }
})
throw error

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit-pick (non-blocking): worth a one-line comment saying this rethrow is deliberately inert.

pollOnce()'s bare catch is its only consumer, and that handler returns immediately because updateOperationStatus replaced the operation object, so this throw neither surfaces the failure nor reschedules a poll — the reportError() above it is the only sink. Your PR description explains this well, but the description is not where the next reader will be when they wonder whether removing the rethrow changes anything.

} finally {
resolveTerminal(opId)
}
}

function handleFailure(opId: string, errorMessage: string | null) {
Expand Down
Loading