From 62c65ad664ccf59350bb15b87228c0b9af95752b Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 30 Jul 2026 15:12:47 -0700 Subject: [PATCH 1/2] refactor: convert billingOperationStore to discriminated union + owned transition BillingOperation had a status field but wasn't a true discriminated union, and handleSuccess/handleFailure/handleTimeout each independently duplicated status update, cleanup, telemetry, and toast logic. Converts BillingOperation into a real discriminated union (Pending/Succeeded/ Failed/TimedOut), and consolidates the three handlers into one transitionToTerminal function that owns the whole pending -> terminal transition, with per-outcome telemetry/toast/side-effect pieces factored out but no longer duplicating the state-update/cleanup/resolve spine. Fixes #14420 --- .../workspace/stores/billingOperationStore.ts | 336 +++++++++++------- 1 file changed, 198 insertions(+), 138 deletions(-) diff --git a/src/platform/workspace/stores/billingOperationStore.ts b/src/platform/workspace/stores/billingOperationStore.ts index 53070ce48de..53581c8be74 100644 --- a/src/platform/workspace/stores/billingOperationStore.ts +++ b/src/platform/workspace/stores/billingOperationStore.ts @@ -27,7 +27,6 @@ const SUBSCRIPTION_ACTION_DISCOVERY_TIMEOUT_MS = 5 * 60_000 const SUBSCRIPTION_AUTHENTICATION_TIMEOUT_MS = 23 * 60 * 60_000 type OperationType = 'subscription' | 'topup' | 'cancel' -type OperationStatus = 'pending' | 'succeeded' | 'failed' | 'timeout' export interface StartOperationMetadata { tier?: SubscriptionCheckoutTier @@ -41,11 +40,9 @@ export interface StartOperationMetadata { } } -interface BillingOperation { +interface BillingOperationBase { opId: string type: OperationType - status: OperationStatus - errorMessage: string | null startedAt: number actionUrl: string | null authenticationRequiredSeen: boolean @@ -57,7 +54,46 @@ interface BillingOperation { downgradeToPersonal?: StartOperationMetadata['downgradeToPersonal'] } -type TerminalResolver = (operation: BillingOperation) => void +interface PendingOperation extends BillingOperationBase { + status: 'pending' + errorMessage: null +} + +interface SucceededOperation extends BillingOperationBase { + status: 'succeeded' + errorMessage: null + actionUrl: null +} + +interface FailedOperation extends BillingOperationBase { + status: 'failed' + errorMessage: string + actionUrl: null +} + +interface TimedOutOperation extends BillingOperationBase { + status: 'timeout' + errorMessage: string + actionUrl: null +} + +type BillingOperation = + | PendingOperation + | SucceededOperation + | FailedOperation + | TimedOutOperation + +type TerminalOperation = + | SucceededOperation + | FailedOperation + | TimedOutOperation + +type TransitionOutcome = + | { status: 'succeeded' } + | { status: 'failed'; summary: string; detail: string | undefined } + | { status: 'timeout'; summary: string } + +type TerminalResolver = (operation: TerminalOperation) => void export const useBillingOperationStore = defineStore('billingOperation', () => { const workspaceStore = useTeamWorkspaceStore() @@ -66,7 +102,7 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { const intervals = new Map() const receivedToasts = new Map() const terminalResolvers = new Map() - const terminalPromises = new Map>() + const terminalPromises = new Map>() const hasPendingOperations = computed(() => [...operations.value.values()].some((op) => op.status === 'pending') @@ -114,7 +150,7 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { if (existing) clearOperation(opId) const actionUrl = validateActionUrl(initialActionUrl) - const operation: BillingOperation = { + const operation: PendingOperation = { opId, type, status: 'pending', @@ -148,7 +184,7 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { useToastStore().add(toastMessage) } - const terminal = new Promise((resolve) => { + const terminal = new Promise((resolve) => { terminalResolvers.set(opId, resolve) }) terminalPromises.set(opId, terminal) @@ -180,12 +216,15 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { } if (response.status === 'succeeded') { - await handleSuccess(opId) + await transitionToTerminal(opId, { status: 'succeeded' }) return } if (response.status === 'failed') { - handleFailure(opId, response.error_message ?? null) + await transitionToTerminal( + opId, + failureOutcome(operation.type, response.error_message ?? null) + ) return } @@ -236,7 +275,10 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { function stopIfTimedOut(opId: string, operation: BillingOperation): boolean { if (!hasTimedOut(operation)) return false - handleTimeout(opId) + void transitionToTerminal(opId, { + status: 'timeout', + summary: timeoutMessage(operation.type) + }) return true } @@ -251,54 +293,37 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { }) } - async function handleSuccess(opId: string) { - const operation = operations.value.get(opId) - if (!operation) return + /** + * Owns the entire pending -> terminal transition: status update, cleanup, + * telemetry, refresh/side effects, toast, and terminal-promise resolution. + * The three outcomes (succeeded/failed/timeout) share this one path and + * differ only in the pieces below that actually differ. + */ + async function transitionToTerminal( + opId: string, + outcome: TransitionOutcome + ): Promise { + if (outcome.status === 'succeeded') { + const operation = updateOperationStatus(opId, outcome) + if (!operation) return + cleanup(opId) + trackSuccessTelemetry(operation) + await applySuccessSideEffects(operation) + resolveTerminal(opId, operation) + return + } - updateOperationStatus(opId, 'succeeded', null) + const operation = updateOperationStatus(opId, outcome) + if (!operation) return cleanup(opId) + trackFailureTelemetry(operation, outcome) + applyFailureToast(operation, outcome) + resolveTerminal(opId, operation) + } - const telemetry = useTelemetry() - if (operation.type === 'subscription') { - 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 - }) - 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 - }) - } - } else if (operation.type === 'topup') { - telemetry?.trackBillingEvent({ - operation: 'topup', - stage: 'succeeded', - outcome: 'success', - billing_op_id: opId - }) - } else { - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'succeeded', - outcome: 'success', - billing_op_id: opId, - operation_type: 'cancel' - }) - } - + async function applySuccessSideEffects( + operation: SucceededOperation + ): Promise { const billingContext = useBillingContext() if (operation.type === 'subscription') { await Promise.allSettled([billingContext.reconcileSubscriptionSuccess()]) @@ -311,7 +336,6 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { if (operation.type === 'cancel') { useTeamWorkspaceStore().updateActiveWorkspace({ isSubscribed: false }) - resolveTerminal(opId) return } @@ -322,93 +346,111 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { useSettingsDialog().show('workspace') } - const toastStore = useToastStore() const messageKey = operation.type === 'subscription' ? 'billingOperation.subscriptionSuccess' : 'billingOperation.topupSuccess' - toastStore.add({ + useToastStore().add({ severity: 'success', summary: t(messageKey), life: 5000 }) - - resolveTerminal(opId) } - function handleFailure(opId: string, errorMessage: string | null) { - const operation = operations.value.get(opId) - if (!operation) return - - const defaultMessage = failureMessage(operation.type) - const detail = - operation.type === 'subscription' - ? t('billingOperation.subscriptionFailedDetail') - : errorMessage + function applyFailureToast( + operation: FailedOperation | TimedOutOperation, + outcome: Extract + ) { + if (operation.type === 'cancel') return - updateOperationStatus(opId, 'failed', detail ?? defaultMessage) - cleanup(opId) + useToastStore().add({ + severity: 'error', + summary: outcome.summary, + detail: outcome.status === 'failed' ? outcome.detail : undefined + }) + } + function trackSuccessTelemetry(operation: SucceededOperation) { const telemetry = useTelemetry() - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'failed', - outcome: 'failure', - billing_op_id: opId, - operation_type: operation.type, - tier: operation.tier, - cycle: operation.cycle, - checkout_type: operation.checkoutType, - payment_intent_source: operation.paymentIntentSource, - failure_category: 'unknown' - }) + + if (operation.type === 'subscription') { + 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: operation.opId + }) + } else if (operation.type === 'topup') { + telemetry?.trackBillingEvent({ + operation: 'topup', + stage: 'succeeded', + outcome: 'success', + billing_op_id: operation.opId + }) + } else { + telemetry?.trackBillingEvent({ + operation: 'operation', + stage: 'succeeded', + outcome: 'success', + billing_op_id: operation.opId, + operation_type: 'cancel' + }) + } + if (operation.downgradeToPersonal) { telemetry?.trackBillingEvent({ operation: 'downgrade_to_personal', - stage: 'failed', - outcome: 'failure', + stage: 'succeeded', + outcome: 'success', member_removal_count: operation.downgradeToPersonal.memberRemovalCount, member_removal_failures: operation.downgradeToPersonal.memberRemovalFailures, - target_tier: operation.downgradeToPersonal.targetTier, - failure_category: 'unknown' + target_tier: operation.downgradeToPersonal.targetTier }) } - - if (operation.type !== 'cancel') { - useToastStore().add({ - severity: 'error', - summary: defaultMessage, - detail: detail ?? undefined - }) - } - - resolveTerminal(opId) } - function handleTimeout(opId: string) { - const operation = operations.value.get(opId) - if (!operation) return - - const message = timeoutMessage(operation.type) + function trackFailureTelemetry( + operation: FailedOperation | TimedOutOperation, + outcome: Extract + ) { + const telemetry = useTelemetry() + const failureCategory = + outcome.status === 'timeout' ? 'poll_timeout' : 'unknown' - updateOperationStatus(opId, 'timeout', message) - cleanup(opId) + if (outcome.status === 'timeout') { + telemetry?.trackBillingEvent({ + operation: 'operation', + stage: 'timeout', + outcome: 'failure', + billing_op_id: operation.opId, + operation_type: operation.type, + tier: operation.tier, + cycle: operation.cycle, + checkout_type: operation.checkoutType, + payment_intent_source: operation.paymentIntentSource, + failure_category: 'poll_timeout' + }) + } else { + telemetry?.trackBillingEvent({ + operation: 'operation', + stage: 'failed', + outcome: 'failure', + billing_op_id: operation.opId, + operation_type: operation.type, + tier: operation.tier, + cycle: operation.cycle, + checkout_type: operation.checkoutType, + payment_intent_source: operation.paymentIntentSource, + failure_category: 'unknown' + }) + } - const telemetry = useTelemetry() - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'timeout', - outcome: 'failure', - billing_op_id: opId, - operation_type: operation.type, - tier: operation.tier, - cycle: operation.cycle, - checkout_type: operation.checkoutType, - payment_intent_source: operation.paymentIntentSource, - failure_category: 'poll_timeout' - }) if (operation.downgradeToPersonal) { telemetry?.trackBillingEvent({ operation: 'downgrade_to_personal', @@ -418,18 +460,20 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { member_removal_failures: operation.downgradeToPersonal.memberRemovalFailures, target_tier: operation.downgradeToPersonal.targetTier, - failure_category: 'poll_timeout' - }) - } - - if (operation.type !== 'cancel') { - useToastStore().add({ - severity: 'error', - summary: message + failure_category: failureCategory }) } + } - resolveTerminal(opId) + function failureOutcome( + type: OperationType, + backendMessage: string | null + ): Extract { + const detail = + type === 'subscription' + ? t('billingOperation.subscriptionFailedDetail') + : (backendMessage ?? undefined) + return { status: 'failed', summary: failureMessage(type), detail } } function failureMessage(type: OperationType) { @@ -445,26 +489,42 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { return t('billingOperation.cancelTimeout') } - function resolveTerminal(opId: string) { - const resolve = terminalResolvers.get(opId) - const operation = operations.value.get(opId) - if (resolve && operation) { - resolve(operation) - } + function resolveTerminal(opId: string, operation: TerminalOperation) { + terminalResolvers.get(opId)?.(operation) terminalResolvers.delete(opId) terminalPromises.delete(opId) } + /** Applies a transition outcome to the pending operation, returning the new terminal state. */ function updateOperationStatus( opId: string, - status: OperationStatus, - errorMessage: string | null - ) { + outcome: Extract + ): SucceededOperation | undefined + function updateOperationStatus( + opId: string, + outcome: Extract + ): FailedOperation | TimedOutOperation | undefined + function updateOperationStatus( + opId: string, + outcome: TransitionOutcome + ): TerminalOperation | undefined { const operation = operations.value.get(opId) - if (!operation) return + if (!operation) return undefined + + const base = { ...operation, actionUrl: null } as const + const updated: TerminalOperation = + outcome.status === 'succeeded' + ? { ...base, status: 'succeeded', errorMessage: null } + : outcome.status === 'failed' + ? { + ...base, + status: 'failed', + errorMessage: outcome.detail ?? outcome.summary + } + : { ...base, status: 'timeout', errorMessage: outcome.summary } - const updated = { ...operation, status, errorMessage, actionUrl: null } operations.value = new Map(operations.value).set(opId, updated) + return updated } function cleanup(opId: string) { From 428c6141552c641e3637f027722e75c2b3479c53 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 30 Jul 2026 16:25:01 -0700 Subject: [PATCH 2/2] fix: resolve terminal promise even if success side effects throw resolveTerminal only ran after applySuccessSideEffects completed without throwing, so a thrown error there (e.g. from a toast/dialog call) leaked the terminal resolver/promise map entries and left any caller awaiting startOperation() hanging forever. poll()'s catch-all silently swallowed the exception, masking the hang. Found by CodeRabbit on #14421. --- .../stores/billingOperationStore.test.ts | 19 +++++++++++++++++++ .../workspace/stores/billingOperationStore.ts | 7 +++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/platform/workspace/stores/billingOperationStore.test.ts b/src/platform/workspace/stores/billingOperationStore.test.ts index cac9790bad1..28b4800ecac 100644 --- a/src/platform/workspace/stores/billingOperationStore.test.ts +++ b/src/platform/workspace/stores/billingOperationStore.test.ts @@ -396,6 +396,25 @@ describe('billingOperationStore', () => { expect(mockToastRemove).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() + }) + mockToastAdd.mockImplementationOnce(() => {}) + mockToastAdd.mockImplementationOnce(() => { + throw new Error('toast rendering failed') + }) + + const store = useBillingOperationStore() + const terminal = store.startOperation('op-1', 'topup') + + await vi.advanceTimersByTimeAsync(0) + + await expect(terminal).resolves.toMatchObject({ status: 'succeeded' }) + }) }) describe('polling failure', () => { diff --git a/src/platform/workspace/stores/billingOperationStore.ts b/src/platform/workspace/stores/billingOperationStore.ts index 53581c8be74..3fd99805745 100644 --- a/src/platform/workspace/stores/billingOperationStore.ts +++ b/src/platform/workspace/stores/billingOperationStore.ts @@ -308,8 +308,11 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { if (!operation) return cleanup(opId) trackSuccessTelemetry(operation) - await applySuccessSideEffects(operation) - resolveTerminal(opId, operation) + try { + await applySuccessSideEffects(operation) + } finally { + resolveTerminal(opId, operation) + } return }