From ea43f5c824fdc67a1a057eaee922317b04d42910 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 16 Oct 2026 23:42:28 -0400 Subject: [PATCH 1/2] FE-1908 / DES-1033 fix(billing): offer hosted checkout when top-up has no default payment method (#21180) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Consolidated-rail top-up now recovers from `NO_PAYMENT_METHOD` by offering Stripe-hosted Checkout for the same amount instead of ending on an error toast. Supersedes the copy change in https://github.com/Comfy-Org/ComfyUI_frontend/pull/21171. **Why.** Off-session top-up (`POST /api/billing/topup`) is the only purchase path once a workspace leaves `legacy_stripe`. A workspace without a Stripe invoice default gets a dead-end toast and cannot buy credits at all. **Root cause (backend, confirmed on BE-5732).** `CreateTopup` charges only the customer's live Stripe `invoice_settings.default_payment_method`. A card saved only on the subscription, or merely attached, does not count, and the resolver deliberately does not promote one. `can_top_up` does not cover payment-method readiness: capabilities are UI guidance, so a `can_top_up: true` workspace can still be refused. **How.** - On a definitive `NO_PAYMENT_METHOD` refusal, the confirm step shows an inline hint and swaps **Pay** for **Continue to checkout**. Every other refusal keeps its existing toast. The refusal happens before any billing operation is reserved, so this cannot start a second payment for an in-flight purchase. - **Continue to checkout** calls the existing hosted endpoint `POST /api/billing/topup/checkout` with the selected amount and a `return_url` chosen by `topupCheckoutReturnUrl`: cloud web returns to `location.href`; Desktop, Desktop 2 and local web return to billing-web's neutral `/return/topup` page (https://github.com/Comfy-Org/ComfyUI_frontend/pull/21199, renamed in https://github.com/Comfy-Org/ComfyUI_frontend/pull/21205), because their own origin is not an allowed return host. The billing-web origin comes from `billing_web_url`, else from the connected Cloud environment (`billing.comfy.org` / `stagingbilling.comfy.org` / `testbilling.comfy.org`), since a local `/api/features` has none. If no origin resolves, checkout is not started. It goes through `sdk.topup.createHostedTopupCheckout` on the SDK rail and a new `workspaceApi.createTopupCheckout` on the legacy rail, so issue and recovery stay on one rail. It then sets the pending top-up marker so the balance refreshes on return, and opens Checkout. On Desktop the URL goes to the system browser through the host's popup handler. - Per DES review: a blocked checkout tab switches the dialog to a "Checkout didn't open" screen with an **Open checkout** retry (a fresh click) instead of navigating the app away, and a checkout that fails to open shows "The payment page couldn't open. Nothing was charged. Try again." inline instead of a Purchase Failed toast. - No new capability field: the hosted endpoint has no payment-method precondition, no rail branch and no flag gate, so a `can_top_up_hosted_checkout` would always equal `can_top_up` (agreed on FE-1908). - `noPaymentMethodError` is replaced by `noPaymentMethodCheckoutHint`: "This workspace has no card saved for one-click top-ups. Pay on a checkout page instead." It no longer points to Billing & invoices, because the generic portal does not set an invoice default. **Set a default card** (`flow_type: payment_method_update`, cloud#13970) follows once that flow is live in production. Linear: FE-1908, DES-1033 ## Verification - Comfy Desktop 1.1.7 (Desktop 2) pointed at this branch (`dev:cloud`, testcloud, SDK rail), with `NO_PAYMENT_METHOD` stubbed on `POST /api/billing/topup`: the refused screen offers Continue to checkout; `POST /api/billing/topup/checkout` is sent with `return_url=https://testbilling.comfy.org/return/topup`; `window.open(checkout.comfy.org/...)` is handed to the system browser and the dialog closes without the blocked screen; a sandbox test-card payment lands on the neutral return page; switching back to the app fires `focus`, which refetches `/api/billing/balance` and moves the balance from 90,909 to 101,459 (+10,550). - Local e2e `topUpNoPaymentMethod.spec.ts` against a local backend: passed (local build sends the billing-web return page). - `topupCheckoutReturnUrl.test.ts`: cloud web, server origin, prefixed origin, each environment fallback, unresolved. - `pnpm exec vitest run` on `TopUpCreditsDialogContentWorkspace.test.ts`, `topupOperationView.test.ts`, `useTopupOperation.test.ts`, `billingSdkStore.test.ts`: 181 passed. - New: checkout opens for the refused amount and the marker is set (legacy rail); checkout failure keeps the dialog open with an error; other refusals do not offer checkout; SDK rail routes through `createHostedTopupCheckout`; hosted-checkout failure projection. - `oxfmt`, `oxlint --type-aware`, `eslint`, server-fact gate, `typecheck:app` clean. ### AS IS / TO BE
AS ISTO BE
https://github.com/user-attachments/assets/6e32d1f8-32ae-4898-9b17-d88d4c50c98d https://github.com/user-attachments/assets/bf51da8b-508b-40ae-92a9-53c9fb1f0570
main build in Comfy Desktop 2: Pay ends on a "Purchase Failed" toast that points at a Manage billing button that does not exist. This PR in Comfy Desktop 2: refused, Continue to checkout, Stripe sandbox checkout in the system browser, test-card payment, billing-web return page, and back in the app the balance goes from 101,459 to 112,009.

The return page in this recording still shows the old title; https://github.com/Comfy-Org/ComfyUI_frontend/pull/21205 renames it to "Return to ComfyUI" at /return/topup.
### Plan position | Item | Ticket | PR | Status | | --- | --- | --- | --- | | Fix "Manage billing" copy | FE-1908 | https://github.com/Comfy-Org/ComfyUI_frontend/pull/21171 | Superseded by this PR | | **Hosted checkout recovery on `NO_PAYMENT_METHOD`** | **FE-1908 / DES-1033** | **this PR** | **In review** | | Migration gate reads the live Stripe invoice default, not the stored field | BE-20139 follow-up | – | Proposed | | Neutral billing-web return page | FE-3464 | https://github.com/Comfy-Org/ComfyUI_frontend/pull/21199 | Merged | | Generic return path and title (`/return/topup`, "Return to ComfyUI") | FE-3464 | https://github.com/Comfy-Org/ComfyUI_frontend/pull/21205 | In review | | Test/staging return hosts | – | https://github.com/Comfy-Org/cloud/pull/13964 | Merged | | Set a default card (`payment_method_update`) | BE-21143 | https://github.com/Comfy-Org/cloud/pull/13970 | Merged, not in prod | ```mermaid graph LR A["PR 21171: copy fix"] -.->|"superseded"| B["This PR: hosted checkout recovery"] C["BE: migration gate uses live invoice default"] --> D["Fewer NO_PAYMENT_METHOD refusals"] B --> D E["PR 21199: billing-web return page"] --> B style B fill:#f9d71c,stroke:#333,stroke-width:2px ``` (cherry picked from commit fe4189d31747547cce11d0b180e7543aa6d98467) (cherry picked from commit 70ec2c451bfa674a2a1121882d5b46304f19dc87) --- .../dialogs/topUpNoPaymentMethod.spec.ts | 34 +- src/composables/auth/useAuthActions.test.ts | 35 +- src/composables/auth/useAuthActions.ts | 3 +- .../billing/topupBalanceRefresh.ts | 22 +- src/locales/en/main.json | 7 +- .../composables/useSubscription.test.ts | 3 +- .../composables/useSubscription.ts | 3 +- .../utils/subscriptionCheckoutUtil.test.ts | 3 +- .../utils/subscriptionCheckoutUtil.ts | 3 +- .../workspace/api/__mocks__/workspaceApi.ts | 3 + src/platform/workspace/api/workspaceApi.ts | 28 ++ .../workspace/billing/billingTab.test.ts | 120 +++++++ src/platform/workspace/billing/billingTab.ts | 44 +++ .../workspace/billing/hostedBillingRoutes.ts | 2 +- .../workspace/billing/openHostedBillingTab.ts | 20 +- .../billing/sdk/billingSdkStore.test.ts | 5 +- .../workspace/billing/sdk/billingSdkStore.ts | 14 +- .../billing/sdk/topupOperationView.test.ts | 31 +- .../billing/sdk/topupOperationView.ts | 17 +- .../billing/topupCheckoutReturnUrl.test.ts | 69 ++++ .../billing/topupCheckoutReturnUrl.ts | 47 +++ ...TopUpCreditsDialogContentWorkspace.test.ts | 313 ++++++++++++++++-- .../TopUpCreditsDialogContentWorkspace.vue | 153 ++++++++- .../useDowngradeToPersonal.test.ts | 5 +- .../composables/useDowngradeToPersonal.ts | 4 +- .../useSubscriptionCheckout.test.ts | 5 +- .../composables/useSubscriptionCheckout.ts | 9 +- .../composables/useTopupOperation.ts | 17 + .../composables/useWorkspaceBilling.test.ts | 2 + .../composables/useWorkspaceBilling.ts | 7 +- 30 files changed, 945 insertions(+), 83 deletions(-) create mode 100644 src/platform/workspace/billing/billingTab.test.ts create mode 100644 src/platform/workspace/billing/billingTab.ts create mode 100644 src/platform/workspace/billing/topupCheckoutReturnUrl.test.ts create mode 100644 src/platform/workspace/billing/topupCheckoutReturnUrl.ts diff --git a/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts b/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts index 8961c770fb8..4fe40d1d5fd 100644 --- a/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts +++ b/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts @@ -10,6 +10,8 @@ import { TopUpCreditsDialog } from '@e2e/fixtures/components/TopUpCreditsDialog' import { TestIds } from '@e2e/fixtures/selectors' import { workspaceRailAuthFixture as test } from '@e2e/fixtures/workspaceRailAuthFixture' +const CHECKOUT_URL = 'https://checkout.stripe.com/c/pay/cs_test_fe1908' + /** * Regression coverage for the 1.51 QA finding: with no payment method saved, * the confirm step claimed "Your saved payment method is charged immediately" @@ -32,7 +34,7 @@ test.describe('Top-up without a saved payment method', () => { return topUpDialog } - test('offers Manage billing and explains a refused purchase', async ({ + test('offers Manage billing and recovers a refused purchase through hosted checkout', async ({ comfyPage }) => { const page = comfyPage.page @@ -61,9 +63,16 @@ test.describe('Top-up without a saved payment method', () => { } }) ) + await page.route('**/api/billing/topup/checkout', (route) => + route.fulfill({ json: { checkout_url: CHECKOUT_URL } }) + ) + await page + .context() + .route(CHECKOUT_URL, (route) => + route.fulfill({ contentType: 'text/html', body: 'checkout' }) + ) const topUpDialog = await openTopUpDialog(page) - await topUpDialog.root .getByRole('button', { name: 'Add credits', exact: true }) .click() @@ -83,10 +92,25 @@ test.describe('Top-up without a saved payment method', () => { await topUpDialog.root.getByRole('button', { name: 'Pay $50.00' }).click() await expect( - page - .locator('.p-toast-message.p-toast-message-error') - .getByText(/Add one via Settings → Plan & Credits → Manage billing/) + topUpDialog.root.getByText(/no card saved for one-click top-ups/) ).toBeVisible() + await expect(comfyPage.toast.toastErrors).toHaveCount(0) + + const appUrl = page.url() + const checkoutRequest = page.waitForRequest('**/api/billing/topup/checkout') + const checkoutPage = page.context().waitForEvent('page') + await topUpDialog.root + .getByRole('button', { name: 'Continue to checkout' }) + .click() + + const checkoutBody = (await checkoutRequest).postDataJSON() + expect(checkoutBody).toMatchObject({ amount_cents: 5000 }) + expect(checkoutBody.return_url).toMatch( + /^https:\/\/(test|staging)?billing\.comfy\.org\/return\/topup$/ + ) + await expect(await checkoutPage).toHaveURL(CHECKOUT_URL) + await expect(page).toHaveURL(appUrl) + await expect(topUpDialog.root).toBeHidden() }) test('keeps the saved-card note when a payment method is on file', async ({ diff --git a/src/composables/auth/useAuthActions.test.ts b/src/composables/auth/useAuthActions.test.ts index 5bda120a28d..f2a7c2eed38 100644 --- a/src/composables/auth/useAuthActions.test.ts +++ b/src/composables/auth/useAuthActions.test.ts @@ -34,7 +34,11 @@ let mockWorkflowStore: ReturnType const mockToastErrorHandler = vi.hoisted(() => vi.fn()) const mockStartPendingTopup = vi.hoisted(() => vi.fn()) -const mockDistributionState = vi.hoisted(() => ({ isCloud: false })) +const mockClearPendingTopup = vi.hoisted(() => vi.fn()) +const mockDistributionState = vi.hoisted(() => ({ + isCloud: false, + isDesktop: false +})) const mockClearAllWorkspaceStorage = vi.hoisted(() => vi.fn()) const mockPrepareWorkflowLogoutTransition = vi.hoisted(() => vi.fn()) @@ -62,13 +66,19 @@ vi.mock(import('@/platform/auth/sso/ssoRequired')) vi.mock(import('@/platform/distribution/types'), () => ({ get isCloud() { return mockDistributionState.isCloud + }, + get isDesktop() { + return mockDistributionState.isDesktop } })) vi.mock(import('@/platform/telemetry')) vi.mock(import('@/composables/billing/usePendingTopup'), () => ({ - usePendingTopup: () => ({ startPendingTopup: mockStartPendingTopup }) + usePendingTopup: () => ({ + startPendingTopup: mockStartPendingTopup, + clearPendingTopup: mockClearPendingTopup + }) })) vi.mock(import('@/platform/workflow/persistence/base/storageIO'), () => ({ @@ -131,6 +141,7 @@ beforeEach(() => { vi.mocked(mockAuthStore.register).mockResolvedValue(credential) vi.mocked(mockAuthStore.loginWithGoogle).mockResolvedValue(credential) mockDistributionState.isCloud = false + mockDistributionState.isDesktop = false }) describe('useAuthActions.purchaseCreditsDirect', () => { @@ -174,6 +185,26 @@ describe('useAuthActions.purchaseCreditsDirect', () => { expect(mockStartPendingTopup).not.toHaveBeenCalled() expect(open).not.toHaveBeenCalled() }) + + it('reports a blocked checkout popup on the web', async () => { + vi.spyOn(window, 'open').mockImplementation(() => null) + const { purchaseCreditsDirect } = useAuthActions() + + await expect(purchaseCreditsDirect(25)).rejects.toThrow() + + expect(mockClearPendingTopup).toHaveBeenCalledOnce() + }) + + it('keeps tracking the top-up when Desktop hands checkout to the system browser', async () => { + mockDistributionState.isDesktop = true + const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const { purchaseCreditsDirect } = useAuthActions() + + await purchaseCreditsDirect(25) + + expect(open).toHaveBeenCalledWith('https://checkout.stripe.test', '_blank') + expect(mockClearPendingTopup).not.toHaveBeenCalled() + }) }) describe('useAuthActions.logout', () => { diff --git a/src/composables/auth/useAuthActions.ts b/src/composables/auth/useAuthActions.ts index f51c1f67d5d..ec5c2daf229 100644 --- a/src/composables/auth/useAuthActions.ts +++ b/src/composables/auth/useAuthActions.ts @@ -35,6 +35,7 @@ import type { SocialSignInOptions } from '@/stores/authStore' import { usdToMicros } from '@/utils/formatUtil' +import { openBillingUrl } from '@/platform/workspace/billing/billingTab' /** * The app's own auth.errors table, read through vue-i18n at resolution time. @@ -225,7 +226,7 @@ export const useAuthActions = () => { // refresh on return still fires when telemetry consent is off. const pendingTopup = usePendingTopup() pendingTopup.startPendingTopup() - if (!window.open(response.checkout_url, '_blank')) { + if (!openBillingUrl(response.checkout_url)) { pendingTopup.clearPendingTopup() throw new PaymentPopupBlockedError( t('subscription.preview.paymentPopupBlocked') diff --git a/src/composables/billing/topupBalanceRefresh.ts b/src/composables/billing/topupBalanceRefresh.ts index efcca5e0b76..57f632ea9b5 100644 --- a/src/composables/billing/topupBalanceRefresh.ts +++ b/src/composables/billing/topupBalanceRefresh.ts @@ -20,21 +20,32 @@ const MAX_SCHEDULED_RUNS = 5 let stopActiveWatch: (() => void) | null = null +interface TopupBalanceSource { + current: () => number | null + fetch: () => Promise +} + +const customerBalanceSource: TopupBalanceSource = { + current: () => useAuthStore().balance?.amount_micros ?? null, + fetch: async () => + (await useAuthStore().fetchBalance())?.amount_micros ?? null +} + /** * Watch for the user returning from a Stripe top-up and refresh the balance. * Safe to call repeatedly: a new call replaces any watch still pending. */ -export function watchForTopupBalanceUpdate(): void { +export function watchForTopupBalanceUpdate( + source: TopupBalanceSource = customerBalanceSource +): void { if (typeof window === 'undefined' || typeof document === 'undefined') return stopActiveWatch?.() - const authStore = useAuthStore() - // Null until a balance is known: treating "not loaded yet" as 0 would let the // first read of the *pre-purchase* balance count as the increase we are // waiting for, stopping the watch on the stale amount. - let baselineMicros: number | null = authStore.balance?.amount_micros ?? null + let baselineMicros: number | null = source.current() const timeouts = new Set>() let stopped = false @@ -62,8 +73,7 @@ export function watchForTopupBalanceUpdate(): void { /** Fetch the balance; true once it has risen above the arming baseline. */ const refresh = async (): Promise => { try { - const balance = await authStore.fetchBalance() - const amountMicros = balance?.amount_micros ?? 0 + const amountMicros = (await source.fetch()) ?? 0 if (baselineMicros === null) { baselineMicros = amountMicros return false diff --git a/src/locales/en/main.json b/src/locales/en/main.json index d5b3f709ed6..e8c6866291c 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2893,8 +2893,13 @@ "creditsDescription": "Credits are used to run workflows or partner nodes.", "chargedImmediatelyNote": "Your saved payment method is charged immediately.", "paymentDetailsRequiredNote": "You'll be asked to add a payment method to complete this purchase.", - "noPaymentMethodError": "No payment method is saved for this workspace. Add one via Settings → Plan & Credits → Manage billing, then retry the top-up.", "manageBillingError": "Failed to open the billing portal. Please try again.", + "noPaymentMethodCheckoutHint": "This workspace has no card saved for one-click top-ups. Pay on a checkout page instead.", + "continueToCheckout": "Continue to checkout", + "checkoutBlockedTitle": "Checkout didn't open", + "checkoutBlockedBody": "Your browser blocked the new tab. Open checkout to finish paying.", + "openCheckout": "Open checkout", + "checkoutOpenFailed": "The payment page couldn't open. Nothing was charged. Try again.", "confirmSubtitle": "Credits are added to this workspace as soon as payment completes.", "confirmTitle": "Confirm", "howManyCredits": "How many credits would you like to add?", diff --git a/src/platform/cloud/subscription/composables/useSubscription.test.ts b/src/platform/cloud/subscription/composables/useSubscription.test.ts index 0022e5512e0..45f206e29ae 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.test.ts @@ -138,7 +138,8 @@ vi.mock(import('@/composables/useErrorHandling')) vi.mock(import('@/platform/distribution/types'), () => ({ get isCloud() { return mockIsCloud.value - } + }, + isDesktop: false })) vi.mock( diff --git a/src/platform/cloud/subscription/composables/useSubscription.ts b/src/platform/cloud/subscription/composables/useSubscription.ts index fe735d9faea..25ca588086e 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.ts @@ -60,6 +60,7 @@ import { runReportedCheckoutAttempt } from '@/platform/cloud/subscription/utils/subscriptionCheckoutUtil' import { useSubscriptionCancellationWatcher } from './useSubscriptionCancellationWatcher' +import { openBillingUrl } from '@/platform/workspace/billing/billingTab' type CloudSubscriptionCheckoutResponse = NonNullable< operations['createCloudSubscriptionCheckout']['responses']['201']['content']['application/json'] @@ -554,7 +555,7 @@ function useSubscriptionInternal() { if (!response.checkout_url) throw missingCheckoutUrlError() - if (!window.open(response.checkout_url, '_blank')) { + if (!openBillingUrl(response.checkout_url)) { throw new PaymentPopupBlockedError( t('subscription.preview.paymentPopupBlocked') ) diff --git a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts index cf9b94c0632..777d8ff5f68 100644 --- a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts +++ b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts @@ -67,7 +67,8 @@ vi.mock(import('@/platform/telemetry/reportError')) vi.mock(import('@/platform/distribution/types'), () => ({ get isCloud() { return mockIsCloud.value - } + }, + isDesktop: false })) vi.mock(import('./checkoutAttributionLoader'), () => ({ diff --git a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts index 21fe159cfda..5c6887e1ebe 100644 --- a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts +++ b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts @@ -29,6 +29,7 @@ import { AuthStoreError, useAuthStore } from '@/stores/authStore' import type { BillingCycle } from './subscriptionTierRank' import { loadCheckoutAttributionModule } from './checkoutAttributionLoader' +import { openBillingUrl } from '@/platform/workspace/billing/billingTab' type CheckoutTier = TierKey | `${TierKey}-yearly` @@ -282,7 +283,7 @@ function completeSubscriptionCheckout( trackBeginCheckout(context) - if (!window.open(checkoutUrl, '_blank')) { + if (!openBillingUrl(checkoutUrl)) { throw new PaymentPopupBlockedError( t('subscription.preview.paymentPopupBlocked') ) diff --git a/src/platform/workspace/api/__mocks__/workspaceApi.ts b/src/platform/workspace/api/__mocks__/workspaceApi.ts index 010577271c5..56829a218ec 100644 --- a/src/platform/workspace/api/__mocks__/workspaceApi.ts +++ b/src/platform/workspace/api/__mocks__/workspaceApi.ts @@ -165,6 +165,9 @@ export const workspaceApi = vi.mockObject( topup_id: 'op-1', status: 'completed' }), + createTopupCheckout: async () => ({ + checkout_url: 'https://checkout.stripe.com/c/pay/cs_mock' + }), getBillingEvents: async () => ({ events: [], limit: 20, diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index 9301a0e263b..d136e7d7d61 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -10,6 +10,8 @@ import type { CancelSubscriptionRequest, CancelSubscriptionResponse, CreateInviteRequest, + CreateTopupCheckoutRequest, + CreateTopupCheckoutResponse, CreateTopupRequest, CreateTopupResponse, CreateWorkspaceRequest, @@ -897,6 +899,32 @@ export const workspaceApi = { } }, + /** + * Create a Stripe-hosted credit top-up checkout session + * POST /api/billing/topup/checkout + */ + async createTopupCheckout( + amountCents: number, + returnUrl: string + ): Promise { + const auth = await requestAuth() + try { + const response = + await workspaceApiClient.post( + workspaceApiUrl('/billing/topup/checkout'), + { + amount_cents: amountCents, + return_url: returnUrl, + idempotency_key: crypto.randomUUID() + } satisfies CreateTopupCheckoutRequest, + auth + ) + return response.data + } catch (err) { + handleAxiosError(err) + } + }, + /** * Get billing events * GET /api/billing/events diff --git a/src/platform/workspace/billing/billingTab.test.ts b/src/platform/workspace/billing/billingTab.test.ts new file mode 100644 index 00000000000..6476de2fa73 --- /dev/null +++ b/src/platform/workspace/billing/billingTab.test.ts @@ -0,0 +1,120 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { openBillingUrl, reserveBillingTab } from './billingTab' + +const distribution = vi.hoisted(() => ({ isDesktop: false })) + +vi.mock(import('@/platform/distribution/types'), () => ({ + get isDesktop() { + return distribution.isDesktop + } +})) + +const checkoutUrl = 'https://checkout.stripe.com/c/pay/cs_test' + +describe('reserveBillingTab', () => { + beforeEach(() => { + distribution.isDesktop = false + delete window.__comfyDesktop2 + }) + + afterEach(() => { + delete window.__comfyDesktop2 + }) + + describe('on the web', () => { + it('reserves a disowned blank tab and navigates it once the URL is known', () => { + const tab = { opener: window, location: { href: '' }, close: vi.fn() } + const open = vi.spyOn(window, 'open').mockReturnValue(tab as never) + + const reserved = reserveBillingTab() + expect(open).toHaveBeenCalledWith('', '_blank') + expect(tab.opener).toBeNull() + + reserved?.navigate(checkoutUrl) + expect(tab.location.href).toBe(checkoutUrl) + }) + + it('reports a blocked tab', () => { + vi.spyOn(window, 'open').mockReturnValue(null) + + expect(reserveBillingTab()).toBeNull() + }) + }) + + describe.for([ + { + host: 'local Desktop', + arrange: () => { + distribution.isDesktop = true + } + }, + { + host: 'cloud Desktop', + arrange: () => { + window.__comfyDesktop2 = {} + } + } + ])('on $host', ({ arrange }) => { + beforeEach(arrange) + + it('opens nothing until the URL is known, then hands it to the host despite a null handle', () => { + const open = vi.spyOn(window, 'open').mockReturnValue(null) + + const reserved = reserveBillingTab() + expect(reserved).not.toBeNull() + expect(open).not.toHaveBeenCalled() + + reserved?.navigate(checkoutUrl) + expect(open).toHaveBeenCalledWith(checkoutUrl, '_blank') + }) + }) +}) + +describe('openBillingUrl', () => { + beforeEach(() => { + distribution.isDesktop = false + delete window.__comfyDesktop2 + }) + + afterEach(() => { + delete window.__comfyDesktop2 + }) + + it.for([ + { + host: 'the web, opened', + arrange: () => {}, + handle: window, + opened: true + }, + { + host: 'the web, blocked', + arrange: () => {}, + handle: null, + opened: false + }, + { + host: 'local Desktop', + arrange: () => { + distribution.isDesktop = true + }, + handle: null, + opened: true + }, + { + host: 'cloud Desktop', + arrange: () => { + window.__comfyDesktop2 = {} + }, + handle: null, + opened: true + } + ])('on $host reports opened=$opened', ({ arrange, handle, opened }) => { + arrange() + const open = vi.spyOn(window, 'open').mockReturnValue(handle) + + expect(openBillingUrl(checkoutUrl)).toBe(opened) + expect(open).toHaveBeenCalledWith(checkoutUrl, '_blank') + }) +}) diff --git a/src/platform/workspace/billing/billingTab.ts b/src/platform/workspace/billing/billingTab.ts new file mode 100644 index 00000000000..85bd5049645 --- /dev/null +++ b/src/platform/workspace/billing/billingTab.ts @@ -0,0 +1,44 @@ +import { isDesktop } from '@/platform/distribution/types' + +export interface BillingTab { + navigate(url: string): void + close(): void +} + +/** + * Desktop denies every in-app popup and hands its URL to the system browser, + * so `window.open` there always returns `null` even though the page opened. + */ +function handsPopupsToSystemBrowser(): boolean { + return isDesktop || window.__comfyDesktop2 !== undefined +} + +/** Opens a billing page in a new tab; `false` only when the browser blocked it. */ +export function openBillingUrl(url: string): boolean { + const tab = window.open(url, '_blank') + return tab !== null || handsPopupsToSystemBrowser() +} + +/** + * Reserves a billing tab during the click, before its URL is known; `null` + * when the browser blocked it. On Desktop the open waits for the URL. + */ +export function reserveBillingTab(): BillingTab | null { + if (handsPopupsToSystemBrowser()) { + return { + navigate: (url) => { + window.open(url, '_blank') + }, + close: () => {} + } + } + const tab = window.open('', '_blank') + if (!tab) return null + tab.opener = null + return { + navigate: (url) => { + tab.location.href = url + }, + close: () => tab.close() + } +} diff --git a/src/platform/workspace/billing/hostedBillingRoutes.ts b/src/platform/workspace/billing/hostedBillingRoutes.ts index b80c8e071f0..56ae2ec5a59 100644 --- a/src/platform/workspace/billing/hostedBillingRoutes.ts +++ b/src/platform/workspace/billing/hostedBillingRoutes.ts @@ -71,7 +71,7 @@ function hostnameOf(url: string): string | undefined { * base URL that will not parse classifies nothing, so it fails closed like any * other unresolved environment rather than throwing through the caller. */ -function hostBillingEnvironment( +export function hostBillingEnvironment( cloudBaseUrl = getComfyCloudBaseUrl() ): BillingEnvironment | undefined { const hostname = hostnameOf(cloudBaseUrl) diff --git a/src/platform/workspace/billing/openHostedBillingTab.ts b/src/platform/workspace/billing/openHostedBillingTab.ts index 280f3fb9d7a..7130f381ab6 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.ts @@ -11,6 +11,7 @@ import { useBillingContext } from '@/composables/billing/useBillingContext' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useTelemetry } from '@/platform/telemetry' import type { PaymentIntentSource } from '@/platform/telemetry/types' +import { reserveBillingTab } from '@/platform/workspace/billing/billingTab' import { hostedBillingRoute } from '@/platform/workspace/billing/hostedBillingRoutes' import { registerRefreshOnReturn } from '@/platform/workspace/billing/refreshOnReturn' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' @@ -26,21 +27,6 @@ export interface OpenHostedBillingTabOptions { readonly journeyId?: string } -/** - * `noopener` returns a null handle even on success, so the blocked tab and the - * opened one are told apart by opening a blank tab and clearing `opener` by - * hand before it leaves `about:blank`. Only that one property survives: the - * tab stays in this page's browsing-context group and sends this origin as - * the referrer, both of which `'noopener,noreferrer'` would have prevented. - */ -function openDisownedTab(url: URL): boolean { - const tab = window.open('', '_blank') - if (!tab) return false - tab.opener = null - tab.location.href = url.href - return true -} - let stopReturnRefresh: (() => void) | null = null let stopOperationWatch: (() => void) | null = null @@ -143,7 +129,9 @@ export function openHostedBillingTabOutcome( source: options.source }) if (route.kind !== 'billing_web') return 'unavailable' - const result = openDisownedTab(route.url) ? 'opened' : 'blocked' + const tab = reserveBillingTab() + tab?.navigate(route.url.href) + const result = tab ? 'opened' : 'blocked' useTelemetry()?.trackBillingEvent({ operation: 'web_handoff', stage: 'opened', diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 92eb37fe8fe..12e3d2a9312 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -55,7 +55,10 @@ vi.mock(import('@/platform/telemetry')) vi.mock(import('@/composables/useFeatureFlags')) -vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) +vi.mock(import('@/platform/distribution/types'), () => ({ + isCloud: true, + isDesktop: false +})) vi.mock(import('firebase/auth')) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index 7ff87e2da77..8e1a81c8236 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -1,3 +1,4 @@ +import { openBillingUrl } from '@/platform/workspace/billing/billingTab' /** * The app's single billing SDK instance and the top-up effects the poller * performs today, moved onto the lifecycle's state: the progress toast, the @@ -81,6 +82,7 @@ import { } from './subscriptionOperationView' import { declineDetail, + projectHostedTopupCheckoutResult, projectTopupOperation, projectTopupResult } from './topupOperationView' @@ -374,7 +376,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { const offered = offeredActions.get(state.id) ?? new Set() if (offered.has(actionUrl)) return offeredActions.set(state.id, offered.add(actionUrl)) - if (window.open(actionUrl, '_blank')) { + if (openBillingUrl(actionUrl)) { sdk.lifecycle.reportHostedStepOpened(state.id, 'new_tab') return } @@ -459,6 +461,15 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { return projectTopupResult(result, amountCents) } + async function createHostedTopupCheckout( + amountCents: number, + returnUrl: string + ): Promise { + return projectHostedTopupCheckoutResult( + await sdk.topup.createHostedTopupCheckout({ amountCents, returnUrl }) + ) + } + // The backend gate on these routes is independent of the client flag, so a // 404 means the rail is on too early. One answer settles it for the tab: // every later action goes straight to the legacy call. @@ -677,6 +688,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { getOperation, recoverPendingOperation, createTopup, + createHostedTopupCheckout, subscribe, previewSubscribe, cancelSubscription, diff --git a/src/platform/workspace/billing/sdk/topupOperationView.test.ts b/src/platform/workspace/billing/sdk/topupOperationView.test.ts index 40bc237e5f6..5ef4c9d79a8 100644 --- a/src/platform/workspace/billing/sdk/topupOperationView.test.ts +++ b/src/platform/workspace/billing/sdk/topupOperationView.test.ts @@ -3,7 +3,11 @@ import { describe, expect, it } from 'vitest' import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { failedTopup, pendingTopup, settledTopup } from './billingSdkTestUtils' -import { projectTopupOperation, projectTopupResult } from './topupOperationView' +import { + projectHostedTopupCheckoutResult, + projectTopupOperation, + projectTopupResult +} from './topupOperationView' describe('projectTopupOperation', () => { it('hands the dialog the hosted verification link', () => { @@ -131,3 +135,28 @@ describe('projectTopupResult', () => { expect(thrown).toMatchObject({ status: 503, code: 'REQUEST_FAILED' }) }) }) + +describe('projectHostedTopupCheckoutResult', () => { + it('hands the dialog the hosted Checkout URL', () => { + expect( + projectHostedTopupCheckoutResult({ + status: 'ok', + url: 'https://checkout.stripe.com/c/pay/cs_1' + }) + ).toBe('https://checkout.stripe.com/c/pay/cs_1') + }) + + it.for([ + [{ status: 'error', code: 'INVALID_RETURN_URL' }, 'validation'], + [{ status: 'error', code: 'NOT_AVAILABLE' }, 'api_rejected'], + [{ status: 'error', code: 'REQUEST_FAILED' }, 'network'] + ] as const)('throws %o as a %s API error', ([failure, failureCategory]) => { + expect(() => projectHostedTopupCheckoutResult(failure)).toThrow( + expect.objectContaining({ + name: 'WorkspaceApiError', + code: failure.code, + failureCategory + }) + ) + }) +}) diff --git a/src/platform/workspace/billing/sdk/topupOperationView.ts b/src/platform/workspace/billing/sdk/topupOperationView.ts index 3a96a41db05..45d62603146 100644 --- a/src/platform/workspace/billing/sdk/topupOperationView.ts +++ b/src/platform/workspace/billing/sdk/topupOperationView.ts @@ -9,6 +9,8 @@ import type { BillingOperationState, BillingOperationTerminal, BillingTelemetryFailure, + HostedTopupCheckoutFailure, + HostedTopupCheckoutResult, TopupFailure, TopupResult } from '@comfyorg/account-core/billing' @@ -94,7 +96,9 @@ export class UncreditedTopupResponse implements CreateTopupResponse { * Most SDK refusals carry no HTTP status, which a status-less API error * would otherwise report as a network failure, so each names its category. */ -function topupFailureError(failure: TopupFailure): WorkspaceApiError { +function topupFailureError( + failure: TopupFailure | HostedTopupCheckoutFailure +): WorkspaceApiError { const serverCode = 'serverCode' in failure ? failure.serverCode : undefined return new WorkspaceApiError( t('credits.topUp.unknownError'), @@ -105,7 +109,7 @@ function topupFailureError(failure: TopupFailure): WorkspaceApiError { } function topupFailureCategory( - failure: TopupFailure + failure: TopupFailure | HostedTopupCheckoutFailure ): BillingTelemetryFailure['failure_category'] { switch (failure.code) { case 'REQUEST_FAILED': @@ -113,6 +117,7 @@ function topupFailureCategory( case 'SUPERSEDED': return 'stale_operation' case 'INVALID_AMOUNT': + case 'INVALID_RETURN_URL': return 'validation' default: return 'api_rejected' @@ -170,3 +175,11 @@ export function projectTopupResult( throw topupFailureError(result) } } + +/** The hosted Checkout URL, or the failure as the error the dialog handles. */ +export function projectHostedTopupCheckoutResult( + result: HostedTopupCheckoutResult +): string { + if (result.status === 'ok') return result.url + throw topupFailureError(result) +} diff --git a/src/platform/workspace/billing/topupCheckoutReturnUrl.test.ts b/src/platform/workspace/billing/topupCheckoutReturnUrl.test.ts new file mode 100644 index 00000000000..03d760eb9e2 --- /dev/null +++ b/src/platform/workspace/billing/topupCheckoutReturnUrl.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' + +import { topupCheckoutReturnUrl } from './topupCheckoutReturnUrl' + +const appUrl = 'http://127.0.0.1:8000/?settings=workspace' + +describe('topupCheckoutReturnUrl', () => { + it('returns cloud web to the page the checkout started from', () => { + expect( + topupCheckoutReturnUrl({ + servesCloudWeb: true, + currentUrl: 'https://cloud.comfy.org/?settings=workspace', + billingWebBase: new URL('https://billing.comfy.org'), + environment: 'production' + }) + ).toBe('https://cloud.comfy.org/?settings=workspace') + }) + + it.for([ + { + name: 'the server-sent billing-web origin', + billingWebBase: new URL('https://billing.comfy.org'), + environment: undefined, + expected: 'https://billing.comfy.org/return/topup' + }, + { + name: 'a prefixed billing-web deployment', + billingWebBase: new URL('https://preview.comfy.org/billing/'), + environment: undefined, + expected: 'https://preview.comfy.org/billing/return/topup' + }, + { + name: 'the production origin when the local server sends none', + billingWebBase: null, + environment: 'production', + expected: 'https://billing.comfy.org/return/topup' + }, + { + name: 'the staging origin when the local server sends none', + billingWebBase: null, + environment: 'staging', + expected: 'https://stagingbilling.comfy.org/return/topup' + }, + { + name: 'the test origin when the local server sends none', + billingWebBase: null, + environment: 'test', + expected: 'https://testbilling.comfy.org/return/topup' + }, + { + name: 'nothing when no origin resolves', + billingWebBase: null, + environment: undefined, + expected: undefined + } + ] as const)( + 'returns non-cloud-web builds to $name', + ({ billingWebBase, environment, expected }) => { + expect( + topupCheckoutReturnUrl({ + servesCloudWeb: false, + currentUrl: appUrl, + billingWebBase, + environment + }) + ).toBe(expected) + } + ) +}) diff --git a/src/platform/workspace/billing/topupCheckoutReturnUrl.ts b/src/platform/workspace/billing/topupCheckoutReturnUrl.ts new file mode 100644 index 00000000000..59008d970e0 --- /dev/null +++ b/src/platform/workspace/billing/topupCheckoutReturnUrl.ts @@ -0,0 +1,47 @@ +import type { BillingEnvironment } from '@comfyorg/billing-contract' + +import { getBillingWebUrl } from '@/config/billingWeb' +import { isCloud } from '@/platform/distribution/types' +import { hostBillingEnvironment } from '@/platform/workspace/billing/hostedBillingRoutes' + +const TOPUP_RETURN_PATH = '/return/topup' + +const BILLING_WEB_ORIGINS: Readonly> = { + production: 'https://billing.comfy.org', + staging: 'https://stagingbilling.comfy.org', + test: 'https://testbilling.comfy.org' +} + +interface TopupCheckoutReturnContext { + readonly servesCloudWeb: boolean + readonly currentUrl: string + readonly billingWebBase: URL | null + readonly environment: BillingEnvironment | undefined +} + +function currentContext(): TopupCheckoutReturnContext { + return { + servesCloudWeb: isCloud && window.__comfyDesktop2 === undefined, + currentUrl: window.location.href, + billingWebBase: getBillingWebUrl(), + environment: hostBillingEnvironment() + } +} + +/** + * Where hosted top-up checkout returns: the current page on cloud web, else + * billing-web's neutral return page; undefined when no billing-web origin resolves. + */ +export function topupCheckoutReturnUrl( + context: TopupCheckoutReturnContext = currentContext() +): string | undefined { + if (context.servesCloudWeb) return context.currentUrl + + const base = + context.billingWebBase ?? + (context.environment && new URL(BILLING_WEB_ORIGINS[context.environment])) + if (!base) return undefined + + const prefix = base.pathname.replace(/\/$/, '') + return new URL(`${prefix}${TOPUP_RETURN_PATH}`, base.origin).href +} diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index 0c94d0557e2..5e7f4b202c5 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -29,10 +29,14 @@ import { useTelemetry } from '@/platform/telemetry' import { TelemetryRegistry } from '@/platform/telemetry/TelemetryRegistry' import { DatadogRumTelemetryProvider } from '@/platform/telemetry/providers/cloud/DatadogRumTelemetryProvider' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' +import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import enMessages from '@/locales/en/main.json' with { type: 'json' } -import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' +import { + WorkspaceApiError, + workspaceApi +} from '@/platform/workspace/api/workspaceApi' import type { CreateTopupResponse } from '@/platform/workspace/api/workspaceApi' import { billingOperation } from '@/platform/workspace/composables/billingOperationTestUtils' import type { BillingOperation } from '@/platform/workspace/composables/billingOperationTestUtils' @@ -55,7 +59,10 @@ vi.mock(import('@/platform/telemetry/reportError'), () => ({ const mockToastAdd = vi.fn() -const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) +const mockDistributionTypes = vi.hoisted(() => ({ + isCloud: true, + isDesktop: false +})) vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) @@ -93,8 +100,12 @@ vi.mock(import('@/platform/workspace/billing/sdk/createBillingSdk'), () => ({ vi.mock(import('firebase/auth'), { spy: true }) const mockClearPendingTopup = vi.hoisted(() => vi.fn()) +const mockStartPendingTopup = vi.hoisted(() => vi.fn()) vi.mock(import('@/composables/billing/usePendingTopup'), () => ({ - usePendingTopup: () => ({ clearPendingTopup: mockClearPendingTopup }) + usePendingTopup: () => ({ + clearPendingTopup: mockClearPendingTopup, + startPendingTopup: mockStartPendingTopup + }) })) vi.mock( @@ -693,28 +704,259 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ) }) - it('explains how to add a payment method when the purchase is refused', async () => { - setHasSavedPaymentMethod(false) - vi.mocked(mockBillingContext().topup).mockRejectedValue( - new WorkspaceApiError( - 'No default payment method is selected.', - 400, - 'NO_PAYMENT_METHOD' + describe('without a default payment method', () => { + const checkoutUrl = 'https://checkout.stripe.com/c/pay/cs_test' + + function refuseForNoPaymentMethod() { + vi.mocked(mockBillingContext().topup).mockRejectedValue( + new WorkspaceApiError( + 'No default payment method is selected.', + 400, + 'NO_PAYMENT_METHOD' + ) ) - ) + } - renderDialog() - await clickAddCredits() - await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) + async function payAndGetRefused() { + const rendered = renderDialog() + await clickAddCredits() + await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) + const continueButton = await screen.findByRole('button', { + name: 'Continue to checkout' + }) + return { ...rendered, continueButton } + } - await waitFor(() => - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - detail: - 'No payment method is saved for this workspace. Add one via Settings → Plan & Credits → Manage billing, then retry the top-up.' + function stubCheckoutTab() { + const tab = { opener: window, location: { href: '' }, close: vi.fn() } + const open = vi.spyOn(window, 'open').mockReturnValue(tab as never) + return { tab, open } + } + + function checkoutOpensAt(url: string) { + vi.spyOn(workspaceApi, 'createTopupCheckout').mockResolvedValue({ + checkout_url: url + }) + } + + it('offers hosted checkout for the selected amount instead of a dead-end error', async () => { + refuseForNoPaymentMethod() + const createCheckout = vi + .spyOn(workspaceApi, 'createTopupCheckout') + .mockResolvedValue({ checkout_url: checkoutUrl }) + const { tab, open } = stubCheckoutTab() + const { continueButton } = await payAndGetRefused() + expect( + screen.getByText( + 'This workspace has no card saved for one-click top-ups. Pay on a checkout page instead.' + ) + ).toBeInTheDocument() + + await userEvent.click(continueButton) + + await waitFor(() => expect(tab.location.href).toBe(checkoutUrl)) + expect(open).toHaveBeenCalledExactlyOnceWith('', '_blank') + expect(createCheckout).toHaveBeenCalledWith(5000, window.location.href) + expect(mockStartPendingTopup).toHaveBeenCalledOnce() + expect(useDialogStore().closeDialog).toHaveBeenCalledWith({ + key: 'top-up-credits' + }) + expect(mockClearPendingTopup).not.toHaveBeenCalled() + expect(mockToastAdd).not.toHaveBeenCalled() + }) + + it('offers Pay again once the user goes back to change the amount', async () => { + refuseForNoPaymentMethod() + await payAndGetRefused() + + await userEvent.click(screen.getByRole('button', { name: 'Back' })) + await userEvent.click(screen.getByRole('button', { name: 'Add credits' })) + + expect( + screen.getByRole('button', { name: 'Pay $50.00' }) + ).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Continue to checkout' }) + ).not.toBeInTheDocument() + }) + + it('refreshes the workspace balance and status when the user returns from checkout', async () => { + refuseForNoPaymentMethod() + checkoutOpensAt(checkoutUrl) + const { tab } = stubCheckoutTab() + const { unmount, continueButton } = await payAndGetRefused() + await userEvent.click(continueButton) + await waitFor(() => expect(tab.location.href).toBe(checkoutUrl)) + unmount() + const billing = mockBillingContext() + vi.mocked(billing.fetchBalance).mockClear() + vi.mocked(billing.fetchStatus).mockClear() + + window.dispatchEvent(new Event('focus')) + + await waitFor(() => { + expect(billing.fetchBalance).toHaveBeenCalled() + expect(billing.fetchStatus).toHaveBeenCalled() + }) + }) + + it('keeps watching after a failed balance read instead of treating it as zero', async () => { + refuseForNoPaymentMethod() + checkoutOpensAt(checkoutUrl) + const { tab } = stubCheckoutTab() + const billing = mockBillingContext() + const balanceMicros = ref(null) + Object.assign(billing, { + balance: computed(() => + balanceMicros.value === null + ? null + : { amountMicros: balanceMicros.value, currency: 'usd' } + ) + }) + const { unmount, continueButton } = await payAndGetRefused() + await userEvent.click(continueButton) + await waitFor(() => expect(tab.location.href).toBe(checkoutUrl)) + unmount() + vi.mocked(billing.fetchBalance) + .mockReset() + .mockRejectedValueOnce(new Error('balance unavailable')) + .mockImplementation(async () => { + balanceMicros.value = 1_000_000 }) + vi.useFakeTimers() + + try { + window.dispatchEvent(new Event('focus')) + await vi.advanceTimersByTimeAsync(2_000) + expect(billing.fetchBalance).toHaveBeenCalledTimes(2) + + await vi.advanceTimersByTimeAsync(5_000) + expect(billing.fetchBalance).toHaveBeenCalledTimes(3) + } finally { + vi.useRealTimers() + } + }) + + it('hands checkout to the Desktop host and returns it to the billing-web return page', async () => { + refuseForNoPaymentMethod() + const createCheckout = vi + .spyOn(workspaceApi, 'createTopupCheckout') + .mockResolvedValue({ checkout_url: checkoutUrl }) + window.__comfyDesktop2 = {} + remoteConfig.value = { billing_web_url: 'https://testbilling.comfy.org' } + const open = vi.spyOn(window, 'open').mockReturnValue(null) + const appUrl = window.location.href + + try { + await userEvent.click((await payAndGetRefused()).continueButton) + + await waitFor(() => + expect(useDialogStore().closeDialog).toHaveBeenCalledWith({ + key: 'top-up-credits' + }) + ) + expect(createCheckout).toHaveBeenCalledWith( + 5000, + 'https://testbilling.comfy.org/return/topup' + ) + expect(open).toHaveBeenCalledWith(checkoutUrl, '_blank') + expect(window.location.href).toBe(appUrl) + } finally { + delete window.__comfyDesktop2 + remoteConfig.value = {} + } + }) + + it('keeps the app in place when the browser blocks the checkout tab and reopens it on request', async () => { + refuseForNoPaymentMethod() + checkoutOpensAt(checkoutUrl) + const tab = { opener: window, location: { href: '' }, close: vi.fn() } + const open = vi + .spyOn(window, 'open') + .mockReturnValueOnce(null) + .mockReturnValueOnce(tab as never) + const appUrl = window.location.href + + await userEvent.click((await payAndGetRefused()).continueButton) + + expect( + await screen.findByRole('heading', { name: "Checkout didn't open" }) + ).toBeInTheDocument() + expect(window.location.href).toBe(appUrl) + expect(mockStartPendingTopup).not.toHaveBeenCalled() + expect(useDialogStore().closeDialog).not.toHaveBeenCalled() + + await userEvent.click( + screen.getByRole('button', { name: 'Open checkout' }) ) - ) + + expect(open).toHaveBeenCalledTimes(2) + expect(tab.location.href).toBe(checkoutUrl) + expect(mockStartPendingTopup).toHaveBeenCalledOnce() + expect(useDialogStore().closeDialog).toHaveBeenCalledWith({ + key: 'top-up-credits' + }) + }) + + it('abandons a checkout that resolves after the dialog was dismissed', async () => { + refuseForNoPaymentMethod() + let resolveCheckout: (value: { checkout_url: string }) => void = () => {} + vi.spyOn(workspaceApi, 'createTopupCheckout').mockReturnValue( + new Promise((resolve) => { + resolveCheckout = resolve + }) + ) + const { tab } = stubCheckoutTab() + const { unmount, continueButton } = await payAndGetRefused() + await userEvent.click(continueButton) + + unmount() + resolveCheckout({ checkout_url: checkoutUrl }) + + await waitFor(() => expect(tab.close).toHaveBeenCalledOnce()) + expect(tab.location.href).toBe('') + expect(mockStartPendingTopup).not.toHaveBeenCalled() + expect(useDialogStore().closeDialog).not.toHaveBeenCalled() + }) + + it('keeps the dialog open and explains a checkout that could not start', async () => { + refuseForNoPaymentMethod() + vi.spyOn(workspaceApi, 'createTopupCheckout').mockRejectedValue( + new WorkspaceApiError('Bad return url', 400, 'INVALID_RETURN_URL') + ) + const { tab } = stubCheckoutTab() + + await userEvent.click((await payAndGetRefused()).continueButton) + + expect(await screen.findByRole('alert')).toHaveTextContent( + "The payment page couldn't open. Nothing was charged. Try again." + ) + expect(mockToastAdd).not.toHaveBeenCalled() + expect(tab.close).toHaveBeenCalledOnce() + expect(mockStartPendingTopup).not.toHaveBeenCalled() + expect( + screen.getByRole('button', { name: 'Continue to checkout' }) + ).toBeEnabled() + }) + + it('does not offer checkout for any other refusal', async () => { + vi.mocked(mockBillingContext().topup).mockRejectedValue( + new WorkspaceApiError( + 'Unpaid invoice', + 400, + 'OUTSTANDING_PAYMENT_REQUIRED' + ) + ) + + renderDialog() + await clickAddCredits() + await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) + + await waitFor(() => expect(mockToastAdd).toHaveBeenCalled()) + expect( + screen.queryByRole('button', { name: 'Continue to checkout' }) + ).not.toBeInTheDocument() + }) }) it('allows returning to amount selection before payment', async () => { @@ -1466,5 +1708,36 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ).toEqual(['sdk', 'sdk']) } ) + + it('recovers a no-payment-method refusal through the SDK hosted checkout', async () => { + const checkoutUrl = 'https://checkout.stripe.com/c/pay/cs_sdk' + const harness = fakeBillingSdk() + mockCreateBillingSdk.mockReturnValue(harness.sdk) + vi.mocked(harness.sdk.topup.createTopupCheckout).mockResolvedValue({ + status: 'error', + code: 'NO_PAYMENT_METHOD', + recoveryAction: 'replace_payment_method' + }) + vi.mocked(harness.sdk.topup.createHostedTopupCheckout).mockResolvedValue({ + status: 'ok', + url: checkoutUrl + }) + vi.mocked(useFeatureFlags().flags).billingSdkTopupRailEnabled = true + const tab = { opener: window, location: { href: '' }, close: vi.fn() } + vi.spyOn(window, 'open').mockReturnValue(tab as never) + + renderDialog() + await clickAddCredits() + await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) + await userEvent.click( + await screen.findByRole('button', { name: 'Continue to checkout' }) + ) + + await waitFor(() => expect(tab.location.href).toBe(checkoutUrl)) + expect(harness.sdk.topup.createHostedTopupCheckout).toHaveBeenCalledWith({ + amountCents: 5000, + returnUrl: window.location.href + }) + }) }) }) diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue index 762d29e5419..a529946d3ba 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue @@ -10,12 +10,12 @@ class="cursor-pointer rounded-sm border-none bg-transparent p-0 text-muted-foreground transition-colors hover:text-base-foreground disabled:pointer-events-none disabled:opacity-40" :disabled="paymentLocked" :aria-label="$t('g.back')" - @click="step = 'amount'" + @click="showAmountStep" >

{{ @@ -79,8 +79,35 @@

+

+ {{ $t('credits.topUp.noPaymentMethodCheckoutHint') }} +

+ +
+

+ {{ $t('credits.topUp.checkoutBlockedTitle') }} +

+

+ {{ $t('credits.topUp.checkoutBlockedBody') }} +

+
+