diff --git a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts index accd895a849..d485362d0d1 100644 --- a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts +++ b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts @@ -7,9 +7,9 @@ import CloudRunButtonWrapper from './CloudRunButtonWrapper.vue' const mockCanRunWorkflows = ref(true) const mockBillingStatus = ref('paid') +const mockV1PaymentRecovery = ref(true) +const mockCanManageSubscription = ref(true) const state = vi.hoisted(() => ({ - v1PaymentRecovery: true, - canManageSubscription: true, manageSubscription: vi.fn(), fetchStatus: vi.fn(), fetchBalance: vi.fn(), @@ -33,7 +33,7 @@ vi.mock('@/composables/useFeatureFlags', () => ({ useFeatureFlags: () => ({ flags: { get v1PaymentRecovery() { - return state.v1PaymentRecovery + return mockV1PaymentRecovery.value } } }) @@ -48,7 +48,7 @@ vi.mock('@/platform/workspace/composables/useWorkspaceUI', async () => { return { useWorkspaceUI: () => ({ permissions: computed(() => ({ - canManageSubscription: state.canManageSubscription + canManageSubscription: mockCanManageSubscription.value })) }) } @@ -90,8 +90,8 @@ describe('CloudRunButtonWrapper', () => { beforeEach(() => { mockCanRunWorkflows.value = true mockBillingStatus.value = 'paid' - state.v1PaymentRecovery = true - state.canManageSubscription = true + mockV1PaymentRecovery.value = true + mockCanManageSubscription.value = true vi.clearAllMocks() }) @@ -196,6 +196,49 @@ describe('CloudRunButtonWrapper', () => { expect(state.fetchBalance).toHaveBeenCalledOnce() }) + it('finishes the balance refresh after status unlocks recovery', async () => { + let resolveStatus!: () => void + let resolveBalance!: () => void + let balanceCommitted = false + state.fetchStatus.mockImplementationOnce( + (signal?: AbortSignal) => + new Promise((resolve) => { + resolveStatus = () => { + if (!signal?.aborted) { + mockBillingStatus.value = 'paid' + mockCanRunWorkflows.value = true + } + resolve() + } + }) + ) + state.fetchBalance.mockImplementationOnce( + (signal?: AbortSignal) => + new Promise((resolve) => { + resolveBalance = () => { + if (!signal?.aborted) balanceCommitted = true + resolve() + } + }) + ) + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + await userEvent.click( + screen.getByRole('button', { name: 'Update payment to run' }) + ) + const dialog = state.showLayoutDialog.mock.calls[0][0] + await dialog.props.onUpdatePayment() + window.dispatchEvent(new Event('focus')) + + resolveStatus() + await nextTick() + resolveBalance() + + await waitFor(() => expect(balanceCommitted).toBe(true)) + }) + it('reuses a pending portal request across rapid clicks and reopen', async () => { let resolvePortal!: () => void state.manageSubscription.mockImplementationOnce( @@ -251,11 +294,13 @@ describe('CloudRunButtonWrapper', () => { ) const dialog = state.showLayoutDialog.mock.calls[0][0] const portalRequest = dialog.props.onUpdatePayment() + const signal = state.manageSubscription.mock.calls[0][0] unmount() + expect(signal.aborted).toBe(true) resolvePortal() await portalRequest - expect(state.closeDialog).not.toHaveBeenCalled() + expect(state.closeDialog).toHaveBeenCalledOnce() expect(state.updateDialog).toHaveBeenCalledTimes(1) expect(state.updateDialog).toHaveBeenCalledWith({ key: 'subscription-paused', @@ -263,10 +308,23 @@ describe('CloudRunButtonWrapper', () => { }) }) + it('blocks a captured payment action after unmount', async () => { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + const { unmount } = renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const dialog = state.showLayoutDialog.mock.calls[0][0] + unmount() + await dialog.props.onUpdatePayment() + + expect(state.manageSubscription).not.toHaveBeenCalled() + }) + it('opens member-safe recovery copy without a payment action', async () => { mockCanRunWorkflows.value = false mockBillingStatus.value = 'paused' - state.canManageSubscription = false + mockCanManageSubscription.value = false renderWrapper() expect(screen.getByTestId('queue-button')).toHaveTextContent('Run') @@ -284,13 +342,200 @@ describe('CloudRunButtonWrapper', () => { it('keeps generic inactive behavior when payment recovery is disabled', () => { mockCanRunWorkflows.value = false mockBillingStatus.value = 'paused' - state.v1PaymentRecovery = false + mockV1PaymentRecovery.value = false renderWrapper() expect(screen.getByTestId('subscribe-to-run-button')).toBeInTheDocument() expect(screen.queryByTestId('queue-group')).not.toBeInTheDocument() }) + it('closes recovery and blocks a captured payment action after rollback', async () => { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const dialogOptions = state.showLayoutDialog.mock.calls[0][0] + + mockV1PaymentRecovery.value = false + await nextTick() + + expect(state.closeDialog).toHaveBeenCalledWith({ + key: 'subscription-paused' + }) + await dialogOptions.props.onUpdatePayment() + expect(state.manageSubscription).not.toHaveBeenCalled() + }) + + it('does not resume recovery UI after rollback during a portal request', async () => { + let resolvePortal!: () => void + state.manageSubscription.mockImplementationOnce( + () => + new Promise((resolve) => { + resolvePortal = resolve + }) + ) + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const dialogOptions = state.showLayoutDialog.mock.calls[0][0] + const portalRequest = dialogOptions.props.onUpdatePayment() + const signal = state.manageSubscription.mock.calls[0][0] + + mockV1PaymentRecovery.value = false + await nextTick() + expect(signal.aborted).toBe(true) + resolvePortal() + await portalRequest + window.dispatchEvent(new Event('focus')) + + expect(state.closeDialog).toHaveBeenCalledOnce() + expect(state.updateDialog).toHaveBeenCalledOnce() + expect(state.updateDialog).toHaveBeenCalledWith({ + key: 'subscription-paused', + contentProps: { isUpdatingPayment: true } + }) + expect(state.fetchStatus).not.toHaveBeenCalled() + expect(state.fetchBalance).not.toHaveBeenCalled() + }) + + it('aborts portal-return refreshes on rollback', async () => { + state.fetchStatus.mockReturnValueOnce(new Promise(() => {})) + state.fetchBalance.mockReturnValueOnce(new Promise(() => {})) + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const dialog = state.showLayoutDialog.mock.calls[0][0] + await dialog.props.onUpdatePayment() + window.dispatchEvent(new Event('focus')) + const statusSignal = state.fetchStatus.mock.calls[0][0] + const balanceSignal = state.fetchBalance.mock.calls[0][0] + + mockV1PaymentRecovery.value = false + await nextTick() + + expect(statusSignal.aborted).toBe(true) + expect(balanceSignal.aborted).toBe(true) + }) + + it('aborts portal-return refreshes on unmount', async () => { + state.fetchStatus.mockReturnValueOnce(new Promise(() => {})) + state.fetchBalance.mockReturnValueOnce(new Promise(() => {})) + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + const { unmount } = renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const dialog = state.showLayoutDialog.mock.calls[0][0] + await dialog.props.onUpdatePayment() + window.dispatchEvent(new Event('focus')) + const statusSignal = state.fetchStatus.mock.calls[0][0] + const balanceSignal = state.fetchBalance.mock.calls[0][0] + + unmount() + + expect(statusSignal.aborted).toBe(true) + expect(balanceSignal.aborted).toBe(true) + }) + + it.for([ + [ + 'owner loses permission', + () => { + mockCanManageSubscription.value = false + } + ], + [ + 'billing recovers', + () => { + mockBillingStatus.value = 'paid' + } + ] + ] as const)( + 'invalidates payment recovery when %s', + async ([, invalidateRecovery]) => { + state.manageSubscription.mockReturnValueOnce(new Promise(() => {})) + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const dialog = state.showLayoutDialog.mock.calls[0][0] + void dialog.props.onUpdatePayment() + const signal = state.manageSubscription.mock.calls[0][0] + + invalidateRecovery() + await nextTick() + + expect(signal.aborted).toBe(true) + expect(state.closeDialog).toHaveBeenCalledWith({ + key: 'subscription-paused' + }) + } + ) + + it('isolates a re-enabled recovery dialog from an older portal request', async () => { + let resolveOldPortal!: () => void + state.manageSubscription.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveOldPortal = resolve + }) + ) + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const oldDialog = state.showLayoutDialog.mock.calls[0][0] + const oldRequest = oldDialog.props.onUpdatePayment() + + mockV1PaymentRecovery.value = false + await nextTick() + mockV1PaymentRecovery.value = true + await nextTick() + + await userEvent.click(screen.getByTestId('queue-button')) + const newDialog = state.showLayoutDialog.mock.calls.at(-1)?.[0] + const newRequest = newDialog.props.onUpdatePayment() + + expect(newRequest).not.toBe(oldRequest) + expect(state.manageSubscription).toHaveBeenCalledTimes(2) + await newRequest + const closeCount = state.closeDialog.mock.calls.length + const updateCount = state.updateDialog.mock.calls.length + + resolveOldPortal() + await oldRequest + + expect(state.closeDialog).toHaveBeenCalledTimes(closeCount) + expect(state.updateDialog).toHaveBeenCalledTimes(updateCount) + }) + + it('ignores a close callback captured by an older recovery dialog', async () => { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + await userEvent.click(screen.getByTestId('queue-button')) + const oldDialog = state.showLayoutDialog.mock.calls[0][0] + + mockV1PaymentRecovery.value = false + await nextTick() + mockV1PaymentRecovery.value = true + await nextTick() + await userEvent.click(screen.getByTestId('queue-button')) + const closeCount = state.closeDialog.mock.calls.length + + oldDialog.props.onClose() + + expect(state.closeDialog).toHaveBeenCalledTimes(closeCount) + }) + it('keeps generic inactive behavior for non-paused statuses', () => { mockCanRunWorkflows.value = false mockBillingStatus.value = 'inactive' diff --git a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue index e0fba1aa9d0..01552990052 100644 --- a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue +++ b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue @@ -8,7 +8,7 @@ diff --git a/src/platform/workspace/composables/deriveBillingBanner.test.ts b/src/platform/workspace/composables/deriveBillingBanner.test.ts index 732c40daa89..ef0b2a09422 100644 --- a/src/platform/workspace/composables/deriveBillingBanner.test.ts +++ b/src/platform/workspace/composables/deriveBillingBanner.test.ts @@ -54,9 +54,45 @@ describe('deriveBillingBanner', () => { ) }) - it('hides payment recovery states when their flag is off', () => { - expect(derive({ ...paymentFailed, v1PaymentRecovery: false })).toBeNull() - expect(derive({ ...paused, v1PaymentRecovery: false })).toBeNull() + it('preserves legacy recovery banners when the new flag is off', () => { + expect(derive({ ...paymentFailed, v1PaymentRecovery: false })).toBe( + 'paymentFailed' + ) + expect(derive({ ...paused, v1PaymentRecovery: false })).toBe('paused') + }) + + it('shows recovery banners when only the recovery flag is on', () => { + expect( + derive({ + ...paymentFailed, + billingControlEnabled: false, + v1PaymentRecovery: true + }) + ).toBe('paymentFailed') + expect( + derive({ + ...paused, + billingControlEnabled: false, + v1PaymentRecovery: true + }) + ).toBe('paused') + }) + + it('hides recovery banners when both billing flags are off', () => { + expect( + derive({ + ...paymentFailed, + billingControlEnabled: false, + v1PaymentRecovery: false + }) + ).toBeNull() + expect( + derive({ + ...paused, + billingControlEnabled: false, + v1PaymentRecovery: false + }) + ).toBeNull() }) it('does not move existing notices onto the payment recovery flag', () => { diff --git a/src/platform/workspace/composables/useBillingBanner.test.ts b/src/platform/workspace/composables/useBillingBanner.test.ts index 39765e94107..f5694434582 100644 --- a/src/platform/workspace/composables/useBillingBanner.test.ts +++ b/src/platform/workspace/composables/useBillingBanner.test.ts @@ -1,5 +1,5 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { nextTick } from 'vue' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { effectScope, nextTick } from 'vue' const mocks = vi.hoisted(() => ({ billing: null as { @@ -65,6 +65,15 @@ vi.mock('@/platform/workspace/composables/useWorkspaceUI', async () => { import { useBillingBanner } from './useBillingBanner' +let scope: ReturnType | undefined + +function setupBanner() { + scope = effectScope() + const banner = scope.run(() => useBillingBanner()) + if (!banner) throw new Error('Failed to create billing banner composable') + return banner +} + describe('useBillingBanner', () => { beforeEach(() => { const b = mocks.billing! @@ -78,9 +87,14 @@ describe('useBillingBanner', () => { b.fetchBalance.mockClear() }) + afterEach(() => { + scope?.stop() + scope = undefined + }) + it('suppresses the banner entirely when billing control is rolled back', async () => { const b = mocks.billing! - const { kind } = useBillingBanner() + const { kind } = setupBanner() b.subscription.value = { hasFunds: false } await nextTick() @@ -93,7 +107,7 @@ describe('useBillingBanner', () => { it('re-shows the out-of-credits banner after a top-up and a later exhaustion', async () => { const b = mocks.billing! - const { kind, dismiss } = useBillingBanner() + const { kind, dismiss } = setupBanner() b.subscription.value = { hasFunds: false } await nextTick() @@ -112,7 +126,7 @@ describe('useBillingBanner', () => { it('refreshes status and balance on focus while payment recovery is visible', async () => { const b = mocks.billing! - useBillingBanner() + setupBanner() b.billingStatus.value = 'payment_failed' window.dispatchEvent(new Event('focus')) @@ -124,7 +138,7 @@ describe('useBillingBanner', () => { it('does not refresh payment recovery on focus when the flag is off', async () => { const b = mocks.billing! - useBillingBanner() + setupBanner() b.billingStatus.value = 'payment_failed' mocks.v1PaymentRecovery!.value = false @@ -134,4 +148,41 @@ describe('useBillingBanner', () => { expect(b.fetchStatus).not.toHaveBeenCalled() expect(b.fetchBalance).not.toHaveBeenCalled() }) + + it('cancels an in-flight payment refresh when the flag is rolled back', async () => { + const b = mocks.billing! + b.fetchStatus.mockReturnValueOnce(new Promise(() => {})) + b.fetchBalance.mockReturnValueOnce(new Promise(() => {})) + setupBanner() + b.billingStatus.value = 'payment_failed' + + window.dispatchEvent(new Event('focus')) + const statusSignal = b.fetchStatus.mock.calls[0][0] + const balanceSignal = b.fetchBalance.mock.calls[0][0] + expect(statusSignal).toBeInstanceOf(AbortSignal) + expect(balanceSignal).toBeInstanceOf(AbortSignal) + + mocks.v1PaymentRecovery!.value = false + await nextTick() + + expect(statusSignal.aborted).toBe(true) + expect(balanceSignal.aborted).toBe(true) + }) + + it('cancels an in-flight payment refresh when its scope is disposed', () => { + const b = mocks.billing! + b.fetchStatus.mockReturnValueOnce(new Promise(() => {})) + b.fetchBalance.mockReturnValueOnce(new Promise(() => {})) + setupBanner() + b.billingStatus.value = 'payment_failed' + + window.dispatchEvent(new Event('focus')) + const statusSignal = b.fetchStatus.mock.calls[0][0] + const balanceSignal = b.fetchBalance.mock.calls[0][0] + + scope?.stop() + + expect(statusSignal.aborted).toBe(true) + expect(balanceSignal.aborted).toBe(true) + }) }) diff --git a/src/platform/workspace/composables/useBillingBanner.ts b/src/platform/workspace/composables/useBillingBanner.ts index 6203bb1a88d..685ff3eefc4 100644 --- a/src/platform/workspace/composables/useBillingBanner.ts +++ b/src/platform/workspace/composables/useBillingBanner.ts @@ -1,5 +1,5 @@ import { createSharedComposable, useEventListener } from '@vueuse/core' -import { computed, ref, watch } from 'vue' +import { computed, onScopeDispose, ref, watch } from 'vue' import { useBillingContext } from '@/composables/billing/useBillingContext' import { useFeatureFlags } from '@/composables/useFeatureFlags' @@ -37,7 +37,7 @@ export function deriveBillingBanner( return null } - if (inputs.v1PaymentRecovery) { + if (inputs.billingControlEnabled || inputs.v1PaymentRecovery) { if (inputs.billingStatus === 'paused') return 'paused' if (inputs.billingStatus === 'payment_failed' && inputs.canManage) { return 'paymentFailed' @@ -70,6 +70,7 @@ function useBillingBannerInternal() { const { flags } = useFeatureFlags() const dismissed = ref(false) + let paymentRefreshController: AbortController | null = null const kind = computed(() => { if (!isCloud) return null @@ -99,9 +100,34 @@ function useBillingBannerInternal() { if (!exhausted) dismissed.value = false }) + watch( + () => flags.v1PaymentRecovery, + (enabled) => { + if (enabled) return + paymentRefreshController?.abort() + paymentRefreshController = null + } + ) + + onScopeDispose(() => { + paymentRefreshController?.abort() + paymentRefreshController = null + }) + useEventListener(window, 'focus', () => { - if (kind.value !== 'paymentFailed') return - void Promise.allSettled([fetchStatus(), fetchBalance()]) + if (!flags.v1PaymentRecovery || kind.value !== 'paymentFailed') return + + paymentRefreshController?.abort() + const controller = new AbortController() + paymentRefreshController = controller + void Promise.allSettled([ + fetchStatus(controller.signal), + fetchBalance(controller.signal) + ]).finally(() => { + if (paymentRefreshController === controller) { + paymentRefreshController = null + } + }) }) function dismiss() { diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 65a52991181..78d8425c398 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -3,6 +3,7 @@ import { effectScope } from 'vue' import type { BillingStatusResponse, + CreateTopupResponse, SubscribeResponse } from '@/platform/workspace/api/workspaceApi' import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' @@ -393,12 +394,15 @@ describe('useWorkspaceBilling', () => { ) }) - it('does not recover an operation from a stale workspace response', async () => { + it('does not publish billing data from a stale workspace response', async () => { const status = createDeferred() + const balance = createDeferred() mockWorkspaceApi.getBillingStatus.mockReturnValue(status.promise) + mockWorkspaceApi.getBillingBalance.mockReturnValue(balance.promise) const billing = setupBilling() - const fetch = billing.fetchStatus() + const statusRequest = billing.fetchStatus() + const balanceRequest = billing.fetchBalance() mockActiveWorkspaceId.value = 'workspace-2' status.resolve({ ...activeStatus, @@ -406,10 +410,30 @@ describe('useWorkspaceBilling', () => { pending_billing_op_id: 'op-workspace-1', action_url: 'https://invoice.stripe.com/sensitive-token' }) - await fetch + balance.resolve(positiveBalance) + await Promise.all([statusRequest, balanceRequest]) expect(mockStartOperation).not.toHaveBeenCalled() expect(billing.subscription.value).toBeNull() + expect(billing.balance.value).toBeNull() + expect(billing.error.value).toBeNull() + }) + + it('does not publish billing errors from stale workspace requests', async () => { + const status = createDeferred() + const balance = createDeferred() + mockWorkspaceApi.getBillingStatus.mockReturnValue(status.promise) + mockWorkspaceApi.getBillingBalance.mockReturnValue(balance.promise) + const billing = setupBilling() + + const statusRequest = billing.fetchStatus() + const balanceRequest = billing.fetchBalance() + mockActiveWorkspaceId.value = 'workspace-2' + status.reject(new Error('old workspace status failed')) + balance.reject(new Error('old workspace balance failed')) + await Promise.allSettled([statusRequest, balanceRequest]) + + expect(billing.error.value).toBeNull() }) it("keeps a 'scheduled' subscription on the active treatment", async () => { @@ -513,6 +537,50 @@ describe('useWorkspaceBilling', () => { expect(billing.subscription.value?.planSlug).toBe('pro-monthly') }) + it('does not commit status after its caller aborts the read', async () => { + const status = createDeferred() + mockWorkspaceApi.getBillingStatus.mockReturnValue(status.promise) + const controller = new AbortController() + const billing = setupBilling() + + const request = billing.fetchStatus(controller.signal) + controller.abort() + expect(billing.isLoading.value).toBe(false) + status.resolve(activeStatus) + await request + + expect(billing.subscription.value).toBeNull() + expect(billing.error.value).toBeNull() + }) + + it('keeps loading while another billing operation remains pending', async () => { + const status = createDeferred() + const topup = createDeferred() + mockWorkspaceApi.getBillingStatus.mockReturnValue(status.promise) + mockWorkspaceApi.createTopup.mockReturnValue(topup.promise) + const controller = new AbortController() + const billing = setupBilling() + + const topupRequest = billing.topup(500) + const statusRequest = billing.fetchStatus(controller.signal) + controller.abort() + + expect(billing.isLoading.value).toBe(true) + + status.resolve(activeStatus) + await statusRequest + expect(billing.isLoading.value).toBe(true) + + topup.resolve({ + billing_op_id: 'op-topup', + topup_id: 'topup-1', + status: 'pending', + amount_cents: 500 + }) + await topupRequest + expect(billing.isLoading.value).toBe(false) + }) + it('surfaces a team credit stop from the status response', async () => { const teamStop = { id: 'team_2500', @@ -581,6 +649,22 @@ describe('useWorkspaceBilling', () => { expect(billing.balance.value?.amountMicros).toBe(5_000_000) }) + + it('does not commit balance after its caller aborts the read', async () => { + const balance = createDeferred() + mockWorkspaceApi.getBillingBalance.mockReturnValue(balance.promise) + const controller = new AbortController() + const billing = setupBilling() + + const request = billing.fetchBalance(controller.signal) + controller.abort() + expect(billing.isLoading.value).toBe(false) + balance.resolve(positiveBalance) + await request + + expect(billing.balance.value).toBeNull() + expect(billing.error.value).toBeNull() + }) }) describe('subscribe', () => { @@ -822,7 +906,8 @@ describe('useWorkspaceBilling', () => { await billing.manageSubscription() expect(mockWorkspaceApi.getPaymentPortalUrl).toHaveBeenCalledWith( - 'https://app.example/settings' + 'https://app.example/settings', + undefined ) expect(openSpy).toHaveBeenCalledWith( 'https://billing.example/portal', @@ -857,6 +942,93 @@ describe('useWorkspaceBilling', () => { await expect(billing.manageSubscription()).rejects.toThrow('portal down') expect(billing.error.value).toBe('portal down') }) + + it('does not open a portal from a request aborted during rollback', async () => { + const portal = createDeferred<{ url: string }>() + const openSpy = vi.fn() + vi.stubGlobal('open', openSpy) + mockWorkspaceApi.getPaymentPortalUrl.mockReturnValue(portal.promise) + const controller = new AbortController() + const billing = setupBilling() + + const request = billing.manageSubscription(controller.signal) + expect(mockWorkspaceApi.getPaymentPortalUrl).toHaveBeenCalledWith( + 'https://app.example/settings', + controller.signal + ) + controller.abort() + portal.resolve({ url: 'https://billing.example/old-portal' }) + await request + + expect(openSpy).not.toHaveBeenCalled() + expect(billing.error.value).toBeNull() + }) + + it('keeps an older portal response out of a newer recovery session', async () => { + const oldPortal = createDeferred<{ url: string }>() + const openSpy = vi.fn() + vi.stubGlobal('open', openSpy) + mockWorkspaceApi.getPaymentPortalUrl + .mockReturnValueOnce(oldPortal.promise) + .mockResolvedValueOnce({ url: 'https://billing.example/new-portal' }) + const oldController = new AbortController() + const billing = setupBilling() + + const oldRequest = billing.manageSubscription(oldController.signal) + oldController.abort() + await billing.manageSubscription(new AbortController().signal) + oldPortal.resolve({ url: 'https://billing.example/old-portal' }) + await oldRequest + + expect(openSpy).toHaveBeenCalledOnce() + expect(openSpy).toHaveBeenCalledWith( + 'https://billing.example/new-portal', + '_blank' + ) + expect(billing.isLoading.value).toBe(false) + }) + + it('preserves concurrent legacy portal requests without a signal', async () => { + const firstPortal = createDeferred<{ url: string }>() + const openSpy = vi.fn() + vi.stubGlobal('open', openSpy) + mockWorkspaceApi.getPaymentPortalUrl + .mockReturnValueOnce(firstPortal.promise) + .mockResolvedValueOnce({ url: 'https://billing.example/second-portal' }) + const billing = setupBilling() + + const firstRequest = billing.manageSubscription() + await billing.manageSubscription() + firstPortal.resolve({ url: 'https://billing.example/first-portal' }) + await firstRequest + + expect(openSpy).toHaveBeenCalledTimes(2) + expect(openSpy).toHaveBeenNthCalledWith( + 1, + 'https://billing.example/second-portal', + '_blank' + ) + expect(openSpy).toHaveBeenNthCalledWith( + 2, + 'https://billing.example/first-portal', + '_blank' + ) + }) + + it('does not open a recovery portal after the workspace changes', async () => { + const portal = createDeferred<{ url: string }>() + const openSpy = vi.fn() + vi.stubGlobal('open', openSpy) + mockWorkspaceApi.getPaymentPortalUrl.mockReturnValue(portal.promise) + const billing = setupBilling() + + const request = billing.manageSubscription(new AbortController().signal) + mockActiveWorkspaceId.value = 'workspace-2' + portal.resolve({ url: 'https://billing.example/workspace-1-portal' }) + await request + + expect(openSpy).not.toHaveBeenCalled() + }) }) describe('cancelSubscription', () => { diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index ba174e290d3..0b1c0ec61ce 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -120,6 +120,26 @@ export function useWorkspaceBilling(): BillingState & BillingActions { const balanceData = shallowRef(null) // Prevent older status and balance responses from overwriting newer state. const latestBillingReadIds = { status: 0, balance: 0 } + let latestPortalRequestId = 0 + let activeLoadingOperations = 0 + + function beginLoading(signal?: AbortSignal): () => void { + activeLoadingOperations++ + isLoading.value = true + let released = false + + const release = () => { + if (released) return + released = true + signal?.removeEventListener('abort', release) + activeLoadingOperations-- + isLoading.value = activeLoadingOperations > 0 + } + + signal?.addEventListener('abort', release, { once: true }) + if (signal?.aborted) release() + return release + } const canAccessSubscriptionFeatures = computed( () => statusData.value?.is_active ?? false @@ -190,7 +210,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { async function initialize(): Promise { if (isInitialized.value) return - isLoading.value = true + const releaseLoading = beginLoading() error.value = null try { await Promise.all([fetchStatus(), fetchBalance(), fetchPlans()]) @@ -204,18 +224,20 @@ export function useWorkspaceBilling(): BillingState & BillingActions { err instanceof Error ? err.message : 'Failed to initialize billing' throw err } finally { - isLoading.value = false + releaseLoading() } } - async function fetchStatus(): Promise { + async function fetchStatus(signal?: AbortSignal): Promise { + if (signal?.aborted) return const requestId = ++latestBillingReadIds.status const workspaceId = workspaceStore.activeWorkspace?.id - isLoading.value = true + const releaseLoading = beginLoading(signal) error.value = null try { - const status = await workspaceApi.getBillingStatus() + const status = await workspaceApi.getBillingStatus(signal) if ( + signal?.aborted || requestId !== latestBillingReadIds.status || workspaceId !== workspaceStore.activeWorkspace?.id ) { @@ -254,33 +276,47 @@ export function useWorkspaceBilling(): BillingState & BillingActions { ) } } catch (err) { - if (requestId === latestBillingReadIds.status) { + if (signal?.aborted) return + if ( + requestId === latestBillingReadIds.status && + workspaceId === workspaceStore.activeWorkspace?.id + ) { error.value = err instanceof Error ? err.message : 'Failed to fetch billing status' } throw err } finally { - if (requestId === latestBillingReadIds.status) isLoading.value = false + releaseLoading() } } - async function fetchBalance(): Promise { + async function fetchBalance(signal?: AbortSignal): Promise { + if (signal?.aborted) return const requestId = ++latestBillingReadIds.balance - isLoading.value = true + const workspaceId = workspaceStore.activeWorkspace?.id + const releaseLoading = beginLoading(signal) error.value = null try { - const balance = await workspaceApi.getBillingBalance() - if (requestId === latestBillingReadIds.balance) { + const balance = await workspaceApi.getBillingBalance(signal) + if ( + !signal?.aborted && + requestId === latestBillingReadIds.balance && + workspaceId === workspaceStore.activeWorkspace?.id + ) { balanceData.value = balance } } catch (err) { - if (requestId === latestBillingReadIds.balance) { + if (signal?.aborted) return + if ( + requestId === latestBillingReadIds.balance && + workspaceId === workspaceStore.activeWorkspace?.id + ) { error.value = err instanceof Error ? err.message : 'Failed to fetch balance' } throw err } finally { - if (requestId === latestBillingReadIds.balance) isLoading.value = false + releaseLoading() } } @@ -333,17 +369,17 @@ export function useWorkspaceBilling(): BillingState & BillingActions { planSlug: string, options?: SubscribeOptions ): Promise { - isLoading.value = true + const releaseLoading = beginLoading() error.value = null try { const response = await workspaceApi.subscribe(planSlug, options) - isLoading.value = false void reconcileBillingStateAfterSubscribe() return response } catch (err) { error.value = err instanceof Error ? err.message : 'Failed to subscribe' - isLoading.value = false throw err + } finally { + releaseLoading() } } @@ -351,7 +387,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { planSlug: string, options?: PreviewSubscribeOptions ): Promise { - isLoading.value = true + const releaseLoading = beginLoading() error.value = null try { return await workspaceApi.previewSubscribe(planSlug, options) @@ -360,30 +396,44 @@ export function useWorkspaceBilling(): BillingState & BillingActions { err instanceof Error ? err.message : 'Failed to preview subscription' throw err } finally { - isLoading.value = false + releaseLoading() } } - async function manageSubscription(): Promise { - isLoading.value = true + async function manageSubscription(signal?: AbortSignal): Promise { + if (signal?.aborted) return + const requestId = signal ? ++latestPortalRequestId : null + const workspaceId = signal ? workspaceStore.activeWorkspace?.id : null + const isCurrentRequest = () => + requestId === null || requestId === latestPortalRequestId + const isCurrentWorkspace = () => + workspaceId === null || workspaceId === workspaceStore.activeWorkspace?.id + const releaseLoading = beginLoading(signal) error.value = null try { const returnUrl = window.location.href - const response = await workspaceApi.getPaymentPortalUrl(returnUrl) - if (response.url) { + const response = await workspaceApi.getPaymentPortalUrl(returnUrl, signal) + if ( + !signal?.aborted && + isCurrentRequest() && + isCurrentWorkspace() && + response.url + ) { window.open(response.url, '_blank') } } catch (err) { + if (signal?.aborted || !isCurrentRequest() || !isCurrentWorkspace()) + return error.value = err instanceof Error ? err.message : 'Failed to open billing portal' throw err } finally { - isLoading.value = false + releaseLoading() } } async function cancelSubscription(): Promise { - isLoading.value = true + const releaseLoading = beginLoading() error.value = null try { const response = await workspaceApi.cancelSubscription() @@ -409,12 +459,12 @@ export function useWorkspaceBilling(): BillingState & BillingActions { err instanceof Error ? err.message : 'Failed to cancel subscription' throw err } finally { - isLoading.value = false + releaseLoading() } } async function resubscribe(): Promise { - isLoading.value = true + const releaseLoading = beginLoading() error.value = null try { const response = await workspaceApi.resubscribe() @@ -449,12 +499,12 @@ export function useWorkspaceBilling(): BillingState & BillingActions { error.value = err instanceof Error ? err.message : 'Failed to resubscribe' throw err } finally { - isLoading.value = false + releaseLoading() } } async function topup(amountCents: number): Promise { - isLoading.value = true + const releaseLoading = beginLoading() error.value = null try { return await workspaceApi.createTopup(amountCents) @@ -463,12 +513,12 @@ export function useWorkspaceBilling(): BillingState & BillingActions { err instanceof Error ? err.message : 'Failed to top up credits' throw err } finally { - isLoading.value = false + releaseLoading() } } async function fetchPlans(): Promise { - isLoading.value = true + const releaseLoading = beginLoading() error.value = null try { await billingPlans.fetchPlans() @@ -476,7 +526,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { error.value = billingPlans.error.value } } finally { - isLoading.value = false + releaseLoading() } }