From f0924a6a2e79dd249eaee2f5605b9e09b86ea2c2 Mon Sep 17 00:00:00 2001 From: Dante Date: Mon, 19 Oct 2026 21:24:18 +0000 Subject: [PATCH] FE-3434 fix(billing): lock Run for payment recovery on payment_recovery_available (#21362) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why The server now emits `payment_recovery_available` on the billing capabilities response (BE-20313, cloud#13802, synced in PR 20840). The Cloud run button should render it instead of deciding recovery itself. Follow-up to FE-3434 ("Wire `payment_recovery_available`"). ## Root cause `CloudRunButtonWrapper` decided the payment recovery lock on the client: `billing_status` of `payment_failed` (or `paused` behind `v1_payment_recovery`) combined with `canManageSubscription`. That is a frontend copy of backend policy (ADR-API-SERVER-FACTS-0042), and it can disagree with the provider state the server checks. ## How - `useBillingCapabilities` exposes `paymentRecoveryAvailable` as a `ServerFact`, as received. Absent (unknown, older server, billing disabled) reads as `false`. - `useBillingCapabilities` exposes `runDeniedPaymentPastDue`: `denied_reasons.can_run_workflows === 'payment_past_due'` as received, wrapped in `pendingServerFact('BE-21535', …)` until the ingest types list that reason. - `usePaymentRecoveryDialog` exposes `paymentRecoveryLock` (`'owner'` when `payment_recovery_available` is true, else `'member'` when Run is denied `payment_past_due`, otherwise `null`) and `refreshCapabilities`, so the run button reaches capabilities through it and not across the cloud/presentation to billing/application boundary. - `CloudRunButtonWrapper` locks Run with "Update payment to run" only from that lock. It no longer reads `billingStatus`, `permissions.canManageSubscription` or `v1PaymentRecovery`. - The wrapper opens the shared recovery dialog instead of its own copy of the dialog and portal logic. `showPaymentRecoveryDialog(onPortalOpened)` tells the opener when the portal opened, so the wrapper still refreshes once on return. That refresh now includes capabilities, so the lock clears when the fact flips. **Visible changes** - Members of a past-due workspace get the member lock ("Run" + "Ask your workspace owner to restore this subscription") from `denied_reasons.can_run_workflows: payment_past_due` (BE-21535, [cloud PR 14324](https://github.com/Comfy-Org/cloud/pull/14324)), bridged with `pendingServerFact` until it deploys and the ingest types sync. Clicking it opens the recovery dialog without the portal, as before. Until the backend deploys, members see the generic inactive Run prompt ("Contact your workspace owner to resubscribe"). - Owners who were `paused` now see the payment-failed copy in the recovery dialog ("Your payment didn't go through"), the copy the shared dialog already uses for Add credits (FE-3434). **Not in this PR.** - `CurrentUserPopoverWorkspace` still reads `billingStatus` in `hasDelinquentSubscription`. That value feeds two compound gates (`showManagePlan`, `showSubscribeAction`). Replacing it means editing those gates, which the server-fact gate rejects, and the right fix is a fact per menu action, not a swap. Left for a follow-up. ## Backend dependency Members get the member lock from `denied_reasons.can_run_workflows: payment_past_due` on `GET /billing/capabilities`, added by BE-21535 ([cloud PR 14324](https://github.com/Comfy-Org/cloud/pull/14324), not deployed). It does not grant payment management. The read is bridged with `pendingServerFact('BE-21535', …)` until the backend deploys and the ingest types sync; until then members see the generic inactive prompt. ## Verification - `vitest`: `CloudRunButtonWrapper`, `ComfyQueueButton`, `usePaymentRecoveryDialog`, `useBillingCapabilities`, `useBillingDialogs.topUpCredits`, `BillingStatusBanner`, `CurrentUserPopoverWorkspace` (678 tests). - Two tables in `CloudRunButtonWrapper.test.ts` run `billing_status` against the recovery lock (locked rows, unlocked rows). On the old wrapper they fail for `paid` + fact true (no lock) and `payment_failed` + fact false (member lock). - `fallow audit` on the changed files: no issues. - `oxlint --type-aware`, `oxfmt`, `eslint` on the touched files. `lint:server-facts` and `typecheck:app` passed in pre-commit. ## Feature flag - No client flag gates the run-button lock. It follows `payment_recovery_available` from `GET /billing/capabilities` for every Cloud workspace. - `v1_payment_recovery` is no longer read on the client (it was only read here, and is at 100% per FE-3135). Its getter in `useFeatureFlags.ts` stays for BE-17905. - `billing_control_enabled` is unchanged; it still gates the settings banners, not the run button. ## AS IS / TO BE The run button's visible UI changes only for past-due workspaces (see Visible changes). Not captured: no testcloud workspace on the test account is past due. ## Plan position | Item | Ticket | PR | Status | | --- | --- | --- | --- | | Past-due top-up opens payment recovery | FE-3434 | [PR 21265](https://github.com/Comfy-Org/ComfyUI_frontend/pull/21265) | Merged | | Sync ingest types (`payment_recovery_available`) | BE-20313 | [PR 20840](https://github.com/Comfy-Org/ComfyUI_frontend/pull/20840) | Merged | | **Run button locks on `payment_recovery_available`** | **FE-3434 follow-up** | **this PR** | **Draft** | | Avatar menu stops reading `billingStatus` | none yet | — | Needs a fact per action | | Member-facing past-due fact (`denied_reasons.can_run_workflows: payment_past_due`) | BE-21535 | [cloud PR 14324](https://github.com/Comfy-Org/cloud/pull/14324) | Open; this PR renders it via `pendingServerFact` until deployed and synced | ```mermaid graph LR A["PR 21265 past-due top-up"] --> C["This PR: run button on payment_recovery_available"] B["PR 20840 ingest types sync"] --> C C --> D["Avatar menu gates"] E["BE-21535 member past-due fact"] --> C style C fill:#f9d71c,stroke:#333,stroke-width:2px ``` --- .../CloudRunButtonWrapper.test.ts | 379 +++++------------- .../ComfyRunButton/CloudRunButtonWrapper.vue | 107 +---- .../useBillingDialogs.topUpCredits.test.ts | 4 +- .../__mocks__/useBillingCapabilities.ts | 28 +- .../useBillingCapabilities.test.ts | 40 ++ .../composables/useBillingCapabilities.ts | 16 + .../usePaymentRecoveryDialog.test.ts | 87 +++- .../composables/usePaymentRecoveryDialog.ts | 32 +- 8 files changed, 307 insertions(+), 386 deletions(-) diff --git a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts index 2b7250b3aed..45159373cd5 100644 --- a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts +++ b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts @@ -6,26 +6,20 @@ import { computed, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' import TopbarSubscribeButton from '@/components/topbar/TopbarSubscribeButton.vue' -import type { - BillingPortalOutcome, - SubscriptionInfo -} from '@/composables/billing/types' import { useBillingContext } from '@/composables/billing/useBillingContext' -import { useErrorHandling } from '@/composables/useErrorHandling' import enMessages from '@/locales/en/main.json' with { type: 'json' } -import { useFeatureFlags } from '@/composables/useFeatureFlags' -import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import type { BillingStatus } from '@/platform/workspace/api/workspaceApi' -import { useDialogService } from '@/services/dialogService' -import { useDialogStore } from '@/stores/dialogStore' +import { usePaymentRecoveryDialog } from '@/platform/workspace/composables/usePaymentRecoveryDialog' import CloudRunButtonWrapper from './CloudRunButtonWrapper.vue' const mockCanRunWorkflows = ref(true) const mockIsFreeTier = ref(true) const mockIsInitialized = ref(true) -const mockBillingStatus = ref('paid') const mockSubscriptionTier = ref(null) +const mockPaymentRecoveryLock = ref<'owner' | 'member' | null>(null) +const showPaymentRecoveryDialog = vi.fn() +const refreshCapabilities = vi.fn(async () => undefined) vi.mock(import('@/composables/billing/useBillingContext')) @@ -37,12 +31,7 @@ vi.mock( import('@/platform/cloud/subscription/composables/useSubscriptionDialog') ) -vi.mock(import('@/composables/useFeatureFlags')) -vi.mock(import('@/composables/useErrorHandling')) - -vi.mock(import('@/platform/workspace/composables/useWorkspaceUI')) - -vi.mock(import('@/services/dialogService')) +vi.mock(import('@/platform/workspace/composables/usePaymentRecoveryDialog')) vi.mock( import('@/components/actionbar/ComfyRunButton/ComfyQueueButton.vue'), @@ -52,7 +41,7 @@ vi.mock( props: ['paymentRecoveryLock'], emits: ['paymentRecoveryClick'], template: - '
' + '
' } }) ) @@ -76,13 +65,9 @@ function renderWrapper() { return render(CloudRunButtonWrapper) } -function setCanManageSubscription(value: boolean) { - const permissions = useWorkspaceUI().permissions.value - vi.mocked(useWorkspaceUI()).permissions = computed(() => ({ - ...permissions, - canManageSubscription: value - })) -} +type SubscriptionInfo = NonNullable< + ReturnType['subscription']['value'] +> function subscription(tier: string | null): SubscriptionInfo | null { if (!tier) return null @@ -102,25 +87,19 @@ function subscription(tier: string | null): SubscriptionInfo | null { return result } -function getPaymentRecoveryDialog(index = 0) { - const call = vi - .mocked(useDialogService().showLayoutDialog) - .mock.calls.at(index) - assert(call) - const { props } = call[0] - assert('canManage' in props) - assert('status' in props) - assert('isUpdatingPayment' in props) - assert('onClose' in props) - assert('onUpdatePayment' in props) - const { canManage, status, isUpdatingPayment, onClose, onUpdatePayment } = - props - assert(typeof canManage === 'boolean') - assert(typeof status === 'string') - assert(typeof isUpdatingPayment === 'boolean') - assert(typeof onClose === 'function') - assert(typeof onUpdatePayment === 'function') - return { canManage, status, isUpdatingPayment, onClose, onUpdatePayment } +function portalOpenedCallback() { + const [onPortalOpened] = showPaymentRecoveryDialog.mock.lastCall ?? [] + assert(typeof onPortalOpened === 'function') + return onPortalOpened +} + +function restoreRunOnRefresh() { + vi.mocked(useBillingContext().fetchStatus).mockImplementationOnce( + async () => { + mockPaymentRecoveryLock.value = null + mockCanRunWorkflows.value = true + } + ) } describe('CloudRunButtonWrapper', () => { @@ -130,19 +109,23 @@ describe('CloudRunButtonWrapper', () => { billing.showsSubscribeToRunPrompt = computed( () => mockIsInitialized.value && !mockCanRunWorkflows.value ) - billing.billingStatus = computed(() => mockBillingStatus.value) billing.isFreeTier = computed(() => mockIsFreeTier.value) billing.subscription = computed(() => subscription(mockSubscriptionTier.value) ) vi.mocked(useBillingContext).mockReturnValue(billing) - setCanManageSubscription(true) mockCanRunWorkflows.value = true mockIsInitialized.value = true - mockBillingStatus.value = 'paid' mockSubscriptionTier.value = null - vi.mocked(useFeatureFlags().flags).v1PaymentRecovery = true mockIsFreeTier.value = true + mockPaymentRecoveryLock.value = null + vi.mocked(usePaymentRecoveryDialog).mockReturnValue({ + showPaymentRecoveryDialog, + updatePayment: vi.fn(), + isUpdatingPayment: computed(() => false), + paymentRecoveryLock: computed(() => mockPaymentRecoveryLock.value), + refreshCapabilities + }) }) describe('one subscribe CTA at a time', () => { @@ -174,7 +157,7 @@ describe('CloudRunButtonWrapper', () => { it('keeps the topbar CTA under payment recovery, where the prompt never mounts', () => { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' + mockPaymentRecoveryLock.value = 'owner' renderCtaSurface() @@ -248,15 +231,57 @@ describe('CloudRunButtonWrapper', () => { ).not.toBeInTheDocument() }) - it('refreshes stale billing state on focus and restores Run', async () => { + it.for(['paid', 'inactive'])( + 'locks Run for payment recovery when payment_recovery_available is true, though billing_status is %s', + (billingStatus) => { + useBillingContext().billingStatus = computed(() => billingStatus) + mockCanRunWorkflows.value = false + mockPaymentRecoveryLock.value = 'owner' + renderWrapper() + + expect(screen.getByTestId('queue-button')).toHaveTextContent( + 'Update payment to run' + ) + expect( + screen.queryByTestId('subscribe-to-run-button') + ).not.toBeInTheDocument() + } + ) + + it.for(['paused', 'payment_failed', 'inactive'])( + 'shows the subscribe prompt when payment_recovery_available is false, though billing_status is %s', + (billingStatus) => { + useBillingContext().billingStatus = computed(() => billingStatus) + mockCanRunWorkflows.value = false + renderWrapper() + + expect(screen.getByTestId('subscribe-to-run-button')).toBeInTheDocument() + expect(screen.queryByTestId('queue-group')).not.toBeInTheDocument() + } + ) + + it('locks Run for a member of a past-due workspace and opens the recovery dialog, not the portal', async () => { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'inactive' - vi.mocked(useBillingContext().fetchStatus).mockImplementationOnce( - async () => { - mockBillingStatus.value = 'paid' - mockCanRunWorkflows.value = true - } + mockPaymentRecoveryLock.value = 'member' + renderWrapper() + + const run = screen.getByRole('button', { name: 'Run' }) + expect(run).toHaveAccessibleDescription( + 'Ask your workspace owner to restore this subscription' ) + expect( + screen.queryByTestId('subscribe-to-run-button') + ).not.toBeInTheDocument() + + await userEvent.click(run) + + expect(showPaymentRecoveryDialog).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).not.toHaveBeenCalled() + }) + + it('refreshes stale billing state on focus and restores Run', async () => { + mockCanRunWorkflows.value = false + restoreRunOnRefresh() renderWrapper() window.dispatchEvent(new Event('focus')) @@ -264,6 +289,7 @@ describe('CloudRunButtonWrapper', () => { await waitFor(() => { expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() + expect(refreshCapabilities).toHaveBeenCalledOnce() expect(screen.getByRole('button', { name: 'Run' })).toBeInTheDocument() }) }) @@ -274,13 +300,7 @@ describe('CloudRunButtonWrapper', () => { .mockReturnValue('visible') try { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'inactive' - vi.mocked(useBillingContext().fetchStatus).mockImplementationOnce( - async () => { - mockBillingStatus.value = 'paid' - mockCanRunWorkflows.value = true - } - ) + restoreRunOnRefresh() renderWrapper() document.dispatchEvent(new Event('visibilitychange')) @@ -305,7 +325,6 @@ describe('CloudRunButtonWrapper', () => { .mockReturnValue('visible') try { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'inactive' vi.mocked(useBillingContext().fetchStatus).mockReturnValueOnce(refresh) vi.mocked(useBillingContext().fetchBalance).mockReturnValueOnce(refresh) renderWrapper() @@ -338,7 +357,6 @@ describe('CloudRunButtonWrapper', () => { .mockReturnValue('hidden') try { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'inactive' renderWrapper() document.dispatchEvent(new Event('visibilitychange')) @@ -352,7 +370,6 @@ describe('CloudRunButtonWrapper', () => { it('retries a failed stale billing refresh on the next focus', async () => { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'inactive' vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( new Error('Status unavailable') ) @@ -390,100 +407,52 @@ describe('CloudRunButtonWrapper', () => { ).not.toBeInTheDocument() }) - it('preserves queue controls and opens the owner recovery flow when paused', async () => { + it('preserves queue controls and opens the recovery dialog when payment recovery is available', async () => { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' + mockPaymentRecoveryLock.value = 'owner' renderWrapper() expect(screen.getByTestId('batch-count')).toBeInTheDocument() expect(screen.getByTestId('queue-dropdown')).toBeInTheDocument() - expect(screen.getByTestId('queue-button')).toHaveTextContent( - 'Update payment to run' - ) - expect( - screen.queryByTestId('subscribe-to-run-button') - ).not.toBeInTheDocument() await userEvent.click( screen.getByRole('button', { name: 'Update payment to run' }) ) - const dialogProps = getPaymentRecoveryDialog() - expect(dialogProps.canManage).toBe(true) - expect(dialogProps.status).toBe('paused') - await dialogProps.onUpdatePayment() - expect(useDialogStore().closeDialog).toHaveBeenCalledWith({ - key: 'subscription-paused' - }) - expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() + expect(showPaymentRecoveryDialog).toHaveBeenCalledOnce() }) - it('does not refresh paused billing before the recovery portal is opened', () => { + it('does not refresh billing before the recovery portal is opened', async () => { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' + mockPaymentRecoveryLock.value = 'owner' renderWrapper() + await userEvent.click( + screen.getByRole('button', { name: 'Update payment to run' }) + ) window.dispatchEvent(new Event('focus')) expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(refreshCapabilities).not.toHaveBeenCalled() }) - it('keeps recovery open and surfaces portal failures', async () => { - const error = new Error('Portal unavailable') - vi.mocked(useBillingContext().manageSubscription).mockRejectedValueOnce( - error - ) - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' - renderWrapper() - - await userEvent.click(screen.getByTestId('queue-button')) - const dialogProps = getPaymentRecoveryDialog() - await dialogProps.onUpdatePayment() - - expect(useErrorHandling().toastErrorHandler).toHaveBeenCalledWith(error) - expect(useDialogStore().closeDialog).not.toHaveBeenCalled() - }) - - it('keeps recovery open when the billing context reports the portal did not open', async () => { - vi.mocked(useBillingContext().manageSubscription).mockResolvedValueOnce({ - ok: false, - reason: 'blocked' - }) + it('refreshes billing and capabilities once on focus after returning from the portal', async () => { mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' - renderWrapper() - - await userEvent.click(screen.getByTestId('queue-button')) - await getPaymentRecoveryDialog().onUpdatePayment() - - expect(useDialogStore().closeDialog).not.toHaveBeenCalled() - window.dispatchEvent(new Event('focus')) - expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() - }) - - it('refreshes billing once on focus after returning from the portal', async () => { - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' - vi.mocked(useBillingContext().fetchStatus).mockImplementationOnce( - async () => { - mockBillingStatus.value = 'paid' - mockCanRunWorkflows.value = true - } - ) + mockPaymentRecoveryLock.value = 'owner' + restoreRunOnRefresh() renderWrapper() await userEvent.click( screen.getByRole('button', { name: 'Update payment to run' }) ) - const dialogProps = getPaymentRecoveryDialog() - await dialogProps.onUpdatePayment() + portalOpenedCallback()() window.dispatchEvent(new Event('focus')) await waitFor(() => { expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() + expect(refreshCapabilities).toHaveBeenCalledOnce() expect(screen.getByRole('button', { name: 'Run' })).toBeInTheDocument() }) @@ -491,160 +460,4 @@ describe('CloudRunButtonWrapper', () => { expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() }) - - it('reuses a pending portal request across rapid clicks and reopen', async () => { - let resolvePortal!: (outcome: BillingPortalOutcome) => void - vi.mocked(useBillingContext().manageSubscription).mockImplementationOnce( - () => - new Promise((resolve) => { - resolvePortal = resolve - }) - ) - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' - renderWrapper() - - await userEvent.click( - screen.getByRole('button', { name: 'Update payment to run' }) - ) - const firstDialogProps = getPaymentRecoveryDialog() - const firstRequest = firstDialogProps.onUpdatePayment() - const repeatedRequest = firstDialogProps.onUpdatePayment() - expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() - - firstDialogProps.onClose() - await userEvent.click( - screen.getByRole('button', { name: 'Update payment to run' }) - ) - const reopenedDialogProps = getPaymentRecoveryDialog(-1) - expect(reopenedDialogProps.isUpdatingPayment).toBe(true) - expect(reopenedDialogProps.onUpdatePayment()).toBe(firstRequest) - expect(repeatedRequest).toBe(firstRequest) - expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() - - resolvePortal({ ok: true }) - await firstRequest - expect(useDialogStore().updateDialog).toHaveBeenLastCalledWith({ - key: 'subscription-paused', - contentProps: { isUpdatingPayment: false } - }) - }) - - it('does not update a replacement dialog after unmount', async () => { - let resolvePortal!: (outcome: BillingPortalOutcome) => void - vi.mocked(useBillingContext().manageSubscription).mockImplementationOnce( - () => - new Promise((resolve) => { - resolvePortal = resolve - }) - ) - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' - const { unmount } = renderWrapper() - - await userEvent.click( - screen.getByRole('button', { name: 'Update payment to run' }) - ) - const dialogProps = getPaymentRecoveryDialog() - const portalRequest = dialogProps.onUpdatePayment() - unmount() - - resolvePortal({ ok: true }) - await portalRequest - expect(useDialogStore().closeDialog).not.toHaveBeenCalled() - expect(useDialogStore().updateDialog).toHaveBeenCalledTimes(1) - expect(useDialogStore().updateDialog).toHaveBeenCalledWith({ - key: 'subscription-paused', - contentProps: { isUpdatingPayment: true } - }) - }) - - it('opens member-safe recovery copy without a payment action', async () => { - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' - setCanManageSubscription(false) - renderWrapper() - - expect(screen.getByTestId('queue-button')).toHaveTextContent('Run') - await userEvent.click(screen.getByTestId('queue-button')) - - const dialogProps = getPaymentRecoveryDialog() - expect(dialogProps.canManage).toBe(false) - expect(dialogProps.status).toBe('paused') - dialogProps.onClose() - expect(useDialogStore().closeDialog).toHaveBeenCalledWith({ - key: 'subscription-paused' - }) - expect(useBillingContext().manageSubscription).not.toHaveBeenCalled() - }) - - it('opens payment recovery for a payment-failed owner', async () => { - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'payment_failed' - renderWrapper() - - expect(screen.getByTestId('queue-button')).toHaveTextContent( - 'Update payment to run' - ) - expect( - screen.queryByTestId('subscribe-to-run-button') - ).not.toBeInTheDocument() - - await userEvent.click(screen.getByTestId('queue-button')) - - const dialogProps = getPaymentRecoveryDialog() - expect(dialogProps.canManage).toBe(true) - expect(dialogProps.status).toBe('payment_failed') - }) - - it('keeps Run locked with owner guidance for a payment-failed member', async () => { - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'payment_failed' - setCanManageSubscription(false) - renderWrapper() - - expect(screen.getByTestId('queue-button')).toHaveTextContent('Run') - expect( - screen.queryByTestId('subscribe-to-run-button') - ).not.toBeInTheDocument() - - await userEvent.click(screen.getByTestId('queue-button')) - - const dialogProps = getPaymentRecoveryDialog() - expect(dialogProps.canManage).toBe(false) - expect(dialogProps.status).toBe('payment_failed') - }) - - it('does not fall back to Subscribe to Run for payment failure when recovery flag is disabled', () => { - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'payment_failed' - vi.mocked(useFeatureFlags().flags).v1PaymentRecovery = false - renderWrapper() - - expect(screen.getByTestId('queue-button')).toHaveTextContent( - 'Update payment to run' - ) - expect( - screen.queryByTestId('subscribe-to-run-button') - ).not.toBeInTheDocument() - }) - - it('keeps generic inactive behavior when payment recovery is disabled', () => { - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'paused' - vi.mocked(useFeatureFlags().flags).v1PaymentRecovery = false - renderWrapper() - - expect(screen.getByTestId('subscribe-to-run-button')).toBeInTheDocument() - expect(screen.queryByTestId('queue-group')).not.toBeInTheDocument() - }) - - it('keeps generic inactive behavior for non-paused statuses', () => { - mockCanRunWorkflows.value = false - mockBillingStatus.value = 'inactive' - renderWrapper() - - expect(screen.getByTestId('subscribe-to-run-button')).toBeInTheDocument() - expect(screen.queryByTestId('queue-group')).not.toBeInTheDocument() - }) }) diff --git a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue index d180d401ac2..e175eb78843 100644 --- a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue +++ b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue @@ -4,67 +4,36 @@ !showsSubscribeToRunPrompt || paymentRecoveryLock || isSalesManagedPlan " :payment-recovery-lock="paymentRecoveryLock" - @payment-recovery-click="showPaymentRecoveryDialog" + @payment-recovery-click="showPaymentRecoveryDialog(refreshOnReturn)" /> diff --git a/src/composables/billing/useBillingDialogs.topUpCredits.test.ts b/src/composables/billing/useBillingDialogs.topUpCredits.test.ts index 881a6ecbf78..5025d6f906b 100644 --- a/src/composables/billing/useBillingDialogs.topUpCredits.test.ts +++ b/src/composables/billing/useBillingDialogs.topUpCredits.test.ts @@ -57,7 +57,9 @@ describe('showTopUpCreditsDialog', () => { vi.mocked(usePaymentRecoveryDialog).mockReturnValue({ showPaymentRecoveryDialog: mockShowPaymentRecoveryDialog, updatePayment: vi.fn(), - isUpdatingPayment: computed(() => false) + isUpdatingPayment: computed(() => false), + paymentRecoveryLock: computed(() => null), + refreshCapabilities: vi.fn(async () => undefined) }) mockIsCloud.value = true diff --git a/src/platform/workspace/composables/__mocks__/useBillingCapabilities.ts b/src/platform/workspace/composables/__mocks__/useBillingCapabilities.ts index dc36997bb3e..0001d1fb23f 100644 --- a/src/platform/workspace/composables/__mocks__/useBillingCapabilities.ts +++ b/src/platform/workspace/composables/__mocks__/useBillingCapabilities.ts @@ -1,5 +1,6 @@ import { onTestFinished, vi } from 'vitest' -import { computed } from 'vue' +import { computed, toValue } from 'vue' +import type { MaybeRefOrGetter } from 'vue' import { receiveServerFact } from '@/platform/serverFacts/serverFact' import type { useBillingCapabilities as realUseBillingCapabilities } from '../useBillingCapabilities' @@ -42,6 +43,12 @@ const defaults: ReturnType = { receiveServerFact('can_manage_auto_top_up', false) ), autoTopUpSetup: computed(() => null), + paymentRecoveryAvailable: computed(() => + receiveServerFact('payment_recovery_available', false) + ), + runDeniedPaymentPastDue: computed(() => + receiveServerFact('denied_reasons.can_run_workflows', false) + ), isReady: computed(() => true), hasResolvedCapabilities: computed(() => true), snapshotAuthoritative: computed(() => true), @@ -55,6 +62,25 @@ export function canManageBillingFact(granted: boolean) { return computed(() => receiveServerFact('can_manage_billing', granted)) } +export function paymentRecoveryAvailableFact( + available: MaybeRefOrGetter +) { + return computed(() => + receiveServerFact('payment_recovery_available', toValue(available)) + ) +} + +export function runDeniedPaymentPastDueFact( + deniedPastDue: MaybeRefOrGetter +) { + return computed(() => + receiveServerFact( + 'denied_reasons.can_run_workflows', + toValue(deniedPastDue) + ) + ) +} + export const useBillingCapabilities = vi.fn(() => { onTestFinished(() => { Object.assign(capabilities, defaults) diff --git a/src/platform/workspace/composables/useBillingCapabilities.test.ts b/src/platform/workspace/composables/useBillingCapabilities.test.ts index 883d1bf3fa9..c132c53f73d 100644 --- a/src/platform/workspace/composables/useBillingCapabilities.test.ts +++ b/src/platform/workspace/composables/useBillingCapabilities.test.ts @@ -394,6 +394,25 @@ describe('useBillingCapabilities', () => { expect(billingCapabilities.canManageBilling.value).toBe(true) }) + it.for([ + { served: true, expected: true }, + { served: false, expected: false }, + { served: undefined, expected: false } + ])( + 'renders payment_recovery_available $served as $expected', + async ({ served, expected }) => { + const response = capabilitiesResponse(true, 'workspace-1', true) + response.payment_recovery_available = served + vi.mocked(workspaceApi.getBillingCapabilities).mockResolvedValueOnce( + response + ) + + await billingCapabilities.initialize() + + expect(billingCapabilities.paymentRecoveryAvailable.value).toBe(expected) + } + ) + it('offers workspace editing only when the server does', async () => { vi.mocked(workspaceApi.getBillingCapabilities).mockResolvedValueOnce( capabilitiesResponse( @@ -1493,6 +1512,27 @@ describe('useBillingCapabilities on the SDK rail', () => { expect(readCapabilities).toHaveBeenCalledTimes(2) expect(billingCapabilities.snapshotAuthoritative.value).toBe(true) }) + + it.for([ + { denial: 'payment_past_due', expected: true }, + { denial: 'no_funds', expected: false }, + { denial: undefined, expected: false } + ])( + 'reads a can_run_workflows denial of $denial as payment past due: $expected', + async ({ denial, expected }) => { + readCapabilities.mockResolvedValueOnce({ + status: 'ok', + value: { + ...capabilitiesResponse(true), + denied_reasons: { can_run_workflows: denial } + } + }) + + await billingCapabilities.initialize() + + expect(billingCapabilities.runDeniedPaymentPastDue.value).toBe(expected) + } + ) }) describe('useBillingCapabilities capability gates', () => { diff --git a/src/platform/workspace/composables/useBillingCapabilities.ts b/src/platform/workspace/composables/useBillingCapabilities.ts index 7787efb825d..5757db4fc64 100644 --- a/src/platform/workspace/composables/useBillingCapabilities.ts +++ b/src/platform/workspace/composables/useBillingCapabilities.ts @@ -5,6 +5,7 @@ import { } from '@vueuse/core' import { computed, onScopeDispose, shallowRef, watch } from 'vue' +import { pendingServerFact } from '@/platform/serverFacts/pendingServerFact' import { receiveServerFact } from '@/platform/serverFacts/serverFact' import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' @@ -196,6 +197,19 @@ function useBillingCapabilitiesInternal() { const autoTopUpSetup = computed( () => resolvedResponse.value?.auto_top_up_setup ?? null ) + const paymentRecoveryAvailable = computed(() => + receiveServerFact( + 'payment_recovery_available', + resolvedResponse.value?.payment_recovery_available ?? false + ) + ) + const runDeniedPaymentPastDue = computed(() => + pendingServerFact<'denied_reasons.can_run_workflows', boolean>( + 'BE-21535', + resolvedResponse.value?.denied_reasons?.can_run_workflows === + 'payment_past_due' + ) + ) const isReady = computed(() => { const state = readState.value if (state.status === 'idle' || state.status === 'pending') return false @@ -539,6 +553,8 @@ function useBillingCapabilitiesInternal() { canDowngradeToPersonal, canManageAutoTopUp, autoTopUpSetup, + paymentRecoveryAvailable, + runDeniedPaymentPastDue, isReady, hasResolvedCapabilities, snapshotAuthoritative, diff --git a/src/platform/workspace/composables/usePaymentRecoveryDialog.test.ts b/src/platform/workspace/composables/usePaymentRecoveryDialog.test.ts index e045674858c..27504b3a7e5 100644 --- a/src/platform/workspace/composables/usePaymentRecoveryDialog.test.ts +++ b/src/platform/workspace/composables/usePaymentRecoveryDialog.test.ts @@ -1,10 +1,15 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' +import { ref } from 'vue' import type { BillingPortalOutcome } from '@/composables/billing/types' import { useBillingContext } from '@/composables/billing/useBillingContext' import { useErrorHandling } from '@/composables/useErrorHandling' import { reportError } from '@/platform/telemetry/reportError' -import { canManageBillingFact } from '@/platform/workspace/composables/__mocks__/useBillingCapabilities' +import { + canManageBillingFact, + paymentRecoveryAvailableFact, + runDeniedPaymentPastDueFact +} from '@/platform/workspace/composables/__mocks__/useBillingCapabilities' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { usePaymentRecoveryDialog } from '@/platform/workspace/composables/usePaymentRecoveryDialog' import { useDialogService } from '@/services/dialogService' @@ -42,6 +47,62 @@ describe('usePaymentRecoveryDialog', () => { } ) + it.for<{ outcome: BillingPortalOutcome; calls: number }>([ + { outcome: { ok: true }, calls: 1 }, + { outcome: { ok: false, reason: 'blocked' }, calls: 0 } + ])( + 'notifies the opener only when the portal opens from the dialog ($outcome.ok)', + async ({ outcome, calls }) => { + vi.mocked(useBillingContext().manageSubscription).mockResolvedValueOnce( + outcome + ) + const onPortalOpened = vi.fn() + + usePaymentRecoveryDialog().showPaymentRecoveryDialog(onPortalOpened) + const [args] = vi.mocked(useDialogService().showLayoutDialog).mock + .calls[0] + assert('onUpdatePayment' in args.props) + assert(typeof args.props.onUpdatePayment === 'function') + await args.props.onUpdatePayment() + + expect(onPortalOpened).toHaveBeenCalledTimes(calls) + } + ) + + it.for([ + { available: true, runDeniedPastDue: false, lock: 'owner' }, + { available: true, runDeniedPastDue: true, lock: 'owner' }, + { available: false, runDeniedPastDue: true, lock: 'member' }, + { available: false, runDeniedPastDue: false, lock: null } + ])( + 'locks for recovery as $lock when payment_recovery_available is $available and Run is denied past due: $runDeniedPastDue', + ({ available, runDeniedPastDue, lock }) => { + const capabilities = useBillingCapabilities() + capabilities.paymentRecoveryAvailable = + paymentRecoveryAvailableFact(available) + capabilities.runDeniedPaymentPastDue = + runDeniedPaymentPastDueFact(runDeniedPastDue) + + expect(usePaymentRecoveryDialog().paymentRecoveryLock.value).toBe(lock) + } + ) + + it('clears the recovery lock once refreshed capabilities drop the fact', async () => { + const capabilities = useBillingCapabilities() + const available = ref(true) + capabilities.paymentRecoveryAvailable = + paymentRecoveryAvailableFact(available) + vi.mocked(capabilities.refresh).mockImplementationOnce(async () => { + available.value = false + }) + const recovery = usePaymentRecoveryDialog() + expect(recovery.paymentRecoveryLock.value).toBe('owner') + + await recovery.refreshCapabilities() + + expect(recovery.paymentRecoveryLock.value).toBeNull() + }) + it('closes the recovery dialog once the billing portal opens', async () => { await expect(usePaymentRecoveryDialog().updatePayment()).resolves.toEqual({ ok: true @@ -97,6 +158,28 @@ describe('usePaymentRecoveryDialog', () => { expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(2) }) + it('reopens the dialog showing the portal request still in flight', async () => { + let resolvePortal: (outcome: BillingPortalOutcome) => void = () => {} + vi.mocked(useBillingContext().manageSubscription).mockReturnValueOnce( + new Promise((resolve) => { + resolvePortal = resolve + }) + ) + const recovery = usePaymentRecoveryDialog() + const request = recovery.updatePayment() + + recovery.showPaymentRecoveryDialog() + + const [args] = vi.mocked(useDialogService().showLayoutDialog).mock.calls[0] + expect(args.props).toMatchObject({ isUpdatingPayment: true }) + resolvePortal({ ok: true }) + await request + expect(useDialogStore().updateDialog).toHaveBeenLastCalledWith({ + key: 'subscription-paused', + contentProps: { isUpdatingPayment: false } + }) + }) + it('shares one in-flight portal request across callers', async () => { let resolvePortal: (outcome: BillingPortalOutcome) => void = () => {} const billing = useBillingContext() diff --git a/src/platform/workspace/composables/usePaymentRecoveryDialog.ts b/src/platform/workspace/composables/usePaymentRecoveryDialog.ts index 0c7c7a3f0a3..18ec32a7e60 100644 --- a/src/platform/workspace/composables/usePaymentRecoveryDialog.ts +++ b/src/platform/workspace/composables/usePaymentRecoveryDialog.ts @@ -23,12 +23,24 @@ export function isTopUpDeniedPastDue(denial: string | undefined): boolean { /** Opens the Update payment dialog, offering the portal only with `can_manage_billing`. */ export function usePaymentRecoveryDialog() { const { manageSubscription } = useBillingContext() - const { canManageBilling } = useBillingCapabilities() + const { + canManageBilling, + paymentRecoveryAvailable, + runDeniedPaymentPastDue, + refresh: refreshCapabilities + } = useBillingCapabilities() const dialogService = useDialogService() const dialogStore = useDialogStore() const { toastErrorHandler } = useErrorHandling() const isUpdatingPayment = computed(() => paymentPortalRequest.value !== null) + const paymentRecoveryLock = computed<'owner' | 'member' | null>(() => + paymentRecoveryAvailable.value + ? 'owner' + : runDeniedPaymentPastDue.value + ? 'member' + : null + ) function closePaymentRecoveryDialog() { dialogStore.closeDialog({ key: DIALOG_KEY }) @@ -70,7 +82,13 @@ export function usePaymentRecoveryDialog() { return paymentPortalRequest.value } - function showPaymentRecoveryDialog() { + async function updatePaymentFromDialog(onPortalOpened?: () => void) { + const outcome = await updatePayment() + if (outcome.ok) onPortalOpened?.() + } + + /** `onPortalOpened` runs each time the billing portal opens from this dialog. */ + function showPaymentRecoveryDialog(onPortalOpened?: () => void) { return dialogService.showLayoutDialog({ key: DIALOG_KEY, component: SubscriptionPausedDialog, @@ -79,7 +97,7 @@ export function usePaymentRecoveryDialog() { status: 'payment_failed', isUpdatingPayment: isUpdatingPayment.value, onClose: closePaymentRecoveryDialog, - onUpdatePayment: updatePayment + onUpdatePayment: () => updatePaymentFromDialog(onPortalOpened) }, dialogComponentProps: { headless: true @@ -87,5 +105,11 @@ export function usePaymentRecoveryDialog() { }) } - return { showPaymentRecoveryDialog, updatePayment, isUpdatingPayment } + return { + showPaymentRecoveryDialog, + updatePayment, + isUpdatingPayment, + paymentRecoveryLock, + refreshCapabilities + } }