From 4c0a3ca0939cfdef58e37bd5fec37e9d0f22ebd6 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 16:29:19 -0400 Subject: [PATCH 1/8] feat(billing): mint hosted billing entries from the shared contract (FE-2218) Layer C of the rollout needs one place that turns the server's hosted_billing_destination into a URL shape: the contract's /v1/ entry when the flag says billing_web, and the provider URL the backend already handed back when it says stripe. Everything unresolved fails closed to the provider - no configured origin, a backend family whose return target has no destination, an entry the contract refuses to build. --- package.json | 1 + pnpm-lock.yaml | 3 + .../billing/hostedBillingRoutes.test.ts | 112 ++++++++++++++++++ .../workspace/billing/hostedBillingRoutes.ts | 95 +++++++++++++++ 4 files changed, 211 insertions(+) create mode 100644 src/platform/workspace/billing/hostedBillingRoutes.test.ts create mode 100644 src/platform/workspace/billing/hostedBillingRoutes.ts diff --git a/package.json b/package.json index 569e7160625..ecd359742ac 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "@alloc/quick-lru": "catalog:", "@atlaskit/pragmatic-drag-and-drop": "^1.3.1", "@comfyorg/account-core": "workspace:*", + "@comfyorg/billing-contract": "workspace:*", "@comfyorg/comfy-multi-player": "0.2.1", "@comfyorg/comfyui-desktop-bridge-types": "catalog:", "@comfyorg/comfyui-electron-types": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3e49a50ef99..47ea1f85af3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -500,6 +500,9 @@ importers: '@comfyorg/account-core': specifier: workspace:* version: link:packages/account-core + '@comfyorg/billing-contract': + specifier: workspace:* + version: link:packages/billing-contract '@comfyorg/comfy-multi-player': specifier: 0.2.1 version: 0.2.1 diff --git a/src/platform/workspace/billing/hostedBillingRoutes.test.ts b/src/platform/workspace/billing/hostedBillingRoutes.test.ts new file mode 100644 index 00000000000..d41bb95dcbe --- /dev/null +++ b/src/platform/workspace/billing/hostedBillingRoutes.test.ts @@ -0,0 +1,112 @@ +import type { + BillingEnvironment, + BillingIntent +} from '@comfyorg/billing-contract' + +import { hostedBillingRoute } from './hostedBillingRoutes' + +const cloudBaseUrl = vi.hoisted(() => ({ + value: 'https://testcloud.comfy.org' +})) + +vi.mock(import('@/config/comfyApi'), () => ({ + getComfyCloudBaseUrl: () => cloudBaseUrl.value +})) + +const BILLING_WEB = new URL('https://billing.comfy.org') + +function entryUrl( + intent: BillingIntent, + environment: BillingEnvironment = 'production', + base: URL = BILLING_WEB +): string | undefined { + const route = hostedBillingRoute('billing_web', intent, base, environment) + return route.kind === 'billing_web' ? route.url.href : undefined +} + +describe('hostedBillingRoute', () => { + beforeEach(() => { + cloudBaseUrl.value = 'https://testcloud.comfy.org' + }) + + it.for([ + ['pricing', 'https://billing.comfy.org/v1/pricing'], + ['subscription', 'https://billing.comfy.org/v1/subscription'], + ['payment-methods', 'https://billing.comfy.org/v1/payment-methods'], + ['checkout', 'https://billing.comfy.org/v1/checkout'] + ] as const)('mints %s at its contract route', ([intent, path]) => { + expect(entryUrl(intent)).toBe( + `${path}?product=comfyui&return_to=comfyui_workspace` + ) + }) + + it.for(['production', 'staging', 'test'] as const)( + 'mints the same workspace return in %s', + (environment) => { + expect(entryUrl('payment-methods', environment)).toContain( + 'return_to=comfyui_workspace' + ) + } + ) + + it.for([ + ['https://billing.comfy.org/billing/', '/billing/v1/pricing'], + ['https://billing.comfy.org/app', '/app/v1/pricing'], + ['https://billing.comfy.org/', '/v1/pricing'] + ] as const)('serves %s beneath its own path prefix', ([base, path]) => { + expect(entryUrl('pricing', 'production', new URL(base))).toBe( + `https://billing.comfy.org${path}?product=comfyui&return_to=comfyui_workspace` + ) + }) + + it.for(['pricing', 'subscription', 'payment-methods'] as const)( + 'leaves %s on the provider while the server says stripe', + (intent) => { + expect( + hostedBillingRoute('stripe', intent, BILLING_WEB, 'production') + ).toEqual({ kind: 'provider' }) + } + ) + + it('stays on the provider when no billing-web origin is configured', () => { + expect( + hostedBillingRoute('billing_web', 'pricing', null, 'production') + ).toEqual({ kind: 'provider' }) + }) + + it('stays on the provider when the contract refuses the origin', () => { + expect( + hostedBillingRoute( + 'billing_web', + 'pricing', + new URL('http://billing.example.com'), + 'production' + ) + ).toEqual({ kind: 'provider' }) + }) + + it.for([ + ['https://cloud.comfy.org', 'production'], + ['https://stagingcloud.comfy.org', 'staging'], + ['https://testcloud.comfy.org', 'test'] + ] as const)('derives %s as its billing family', ([baseUrl]) => { + cloudBaseUrl.value = baseUrl + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + + expect(hostedBillingRoute('billing_web', 'pricing')).toEqual({ + kind: 'billing_web', + url: new URL( + 'https://billing.comfy.org/v1/pricing?product=comfyui&return_to=comfyui_workspace' + ) + }) + }) + + it('stays on the provider for a backend outside the known families', () => { + cloudBaseUrl.value = 'https://cloud.example.com' + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + + expect(hostedBillingRoute('billing_web', 'pricing')).toEqual({ + kind: 'provider' + }) + }) +}) diff --git a/src/platform/workspace/billing/hostedBillingRoutes.ts b/src/platform/workspace/billing/hostedBillingRoutes.ts new file mode 100644 index 00000000000..625dfc30783 --- /dev/null +++ b/src/platform/workspace/billing/hostedBillingRoutes.ts @@ -0,0 +1,95 @@ +/** + * Layer C of the billing rollout: which origin a hosted billing action opens. + * + * The server decides, through `hosted_billing_destination`. `stripe` means the + * URL the backend already handed back — `action_url`, `payment_method_url`, a + * portal link — is opened unchanged, so the host never composes a provider + * URL of its own. `billing_web` means the host mints a `/v1/` entry + * from `@comfyorg/billing-contract`, the one definition of that route surface. + * + * Every hosted surface reads the same flag, so they flip together and stay + * independent of Layer A: whether an action reached here over the SDK rail or + * the legacy client says nothing about where it should land. + * + * Anything unresolved fails closed to the provider — no configured billing-web + * origin, an environment whose return target has no destination, an entry the + * contract refuses to build. A customer on the provider page is served; one on + * an origin nobody hosts, or with no way back, is stranded. + */ +import type { + BillingEnvironment, + BillingIntent +} from '@comfyorg/billing-contract' +import { + buildBillingEntryUrl, + resolveReturnTarget +} from '@comfyorg/billing-contract' + +import type { HostedBillingDestination } from '@/config/billingWeb' +import { getBillingWebUrl } from '@/config/billingWeb' +import { getComfyCloudBaseUrl } from '@/config/comfyApi' +import { resolveDeployEnv } from '@/platform/telemetry/initDatadogRum' + +export type HostedBillingRoute = + | { readonly kind: 'billing_web'; readonly url: URL } + | { readonly kind: 'provider' } + +const PROVIDER: HostedBillingRoute = { kind: 'provider' } + +const PRODUCT = 'comfyui' +const RETURN_TO = 'comfyui_workspace' + +const BILLING_ENVIRONMENT_BY_DEPLOY_ENV: Readonly< + Record +> = { + 'prod-v2': 'production', + 'stg-v2': 'staging', + 'test-v2': 'test' +} + +/** + * The family the session was minted against, not the label on this build: a + * developer running the frontend locally still talks to a deployed backend, + * so the cloud base URL classifies the trip and `window.location` cannot. + */ +function hostBillingEnvironment( + cloudBaseUrl = getComfyCloudBaseUrl() +): BillingEnvironment | undefined { + const deployEnv = resolveDeployEnv(new URL(cloudBaseUrl).hostname) + return deployEnv === undefined + ? undefined + : BILLING_ENVIRONMENT_BY_DEPLOY_ENV[deployEnv] +} + +/** + * Re-bases a contract route under the configured billing-web path, which the + * builder drops because an entry URL is only ever routing input. A prefixed + * deployment (`https://host/billing/`) serves `/v1/` beneath its own + * prefix, so the origin alone would point at nothing. + */ +function underBase(base: URL, entry: URL): URL { + const prefix = base.pathname.replace(/\/$/, '') + return new URL(`${prefix}${entry.pathname}${entry.search}`, base.origin) +} + +export function hostedBillingRoute( + destination: HostedBillingDestination, + intent: BillingIntent, + billingWebBase: URL | null = getBillingWebUrl(), + environment: BillingEnvironment | undefined = hostBillingEnvironment() +): HostedBillingRoute { + if (destination !== 'billing_web' || !billingWebBase) return PROVIDER + if (!environment || !resolveReturnTarget(RETURN_TO, environment)) { + return PROVIDER + } + + const entry = buildBillingEntryUrl({ + billingOrigin: billingWebBase, + intent, + product: PRODUCT, + returnTo: RETURN_TO + }) + return entry.status === 'ok' + ? { kind: 'billing_web', url: underBase(billingWebBase, entry.url) } + : PROVIDER +} From 031acea3dc9ba30b4949a4e4347f4c011bd230d0 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 16:29:47 -0400 Subject: [PATCH 2/8] feat(billing): route hosted billing actions to the server's destination (FE-2218) Plans & pricing opened the billing-web root with no intent and no way back; it now opens the contract's pricing entry with return_to. Manage subscription reads the destination before it picks a rail, so on billing_web neither the SDK nor the legacy client is asked for a portal URL the customer will never open, and the portal-return refresh still re-reads status on the way back. --- .../CurrentUserPopoverWorkspace.test.ts | 18 +++--- .../CurrentUserPopoverWorkspace.vue | 8 +-- .../composables/useWorkspaceBilling.test.ts | 62 +++++++++++++++++++ .../composables/useWorkspaceBilling.ts | 13 ++++ 4 files changed, 88 insertions(+), 13 deletions(-) diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 325b51d6157..564dd335a36 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -35,7 +35,7 @@ const state = vi.hoisted(() => { canReactivatePlan: false, canOpenPricingSurface: false, shouldUseWorkspaceBilling: true, - hostedBillingWebEnabled: false, + hostedBillingDestination: 'stripe', billingWebUrl: initialBillingWebUrl(), showCreateWorkspaceDialog: vi.fn(), showTopUpCreditsDialog: vi.fn(), @@ -139,8 +139,8 @@ vi.mock(import('@/composables/useExternalLink'), () => ({ vi.mock(import('@/composables/useFeatureFlags'), () => ({ useFeatureFlags: () => ({ flags: { - get hostedBillingWebEnabled() { - return state.hostedBillingWebEnabled + get hostedBillingDestination() { + return state.hostedBillingDestination } } }) @@ -217,7 +217,7 @@ describe('CurrentUserPopoverWorkspace', () => { state.canOpenPricingSurface = false state.canReactivate = false state.shouldUseWorkspaceBilling = true - state.hostedBillingWebEnabled = false + state.hostedBillingDestination = 'stripe' state.billingWebUrl = new URL('http://localhost:5174') }) @@ -341,13 +341,13 @@ describe('CurrentUserPopoverWorkspace', () => { const user = userEvent.setup() const open = vi.spyOn(window, 'open').mockReturnValue(window) state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' renderComponent('team') await user.click(screen.getByTestId('plans-pricing-menu-item')) expect(open).toHaveBeenCalledWith( - 'http://localhost:5174/', + 'http://localhost:5174/v1/pricing?product=comfyui&return_to=comfyui_workspace', '_blank', 'noopener,noreferrer' ) @@ -358,7 +358,7 @@ describe('CurrentUserPopoverWorkspace', () => { const user = userEvent.setup() const open = vi.spyOn(window, 'open').mockReturnValue(null) state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' renderComponent('team') await user.click(screen.getByTestId('plans-pricing-menu-item')) @@ -373,7 +373,7 @@ describe('CurrentUserPopoverWorkspace', () => { const user = userEvent.setup() const open = vi.spyOn(window, 'open').mockImplementation(() => null) state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' state.billingWebUrl = null renderComponent('team') @@ -630,7 +630,7 @@ describe('CurrentUserPopoverWorkspace', () => { state.canManageSubscriptionLifecycle = true state.canReactivatePlan = true state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' renderComponent('team') expect(screen.getByTestId('add-credits-button')).toBeInTheDocument() diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index fc243434fc9..7656f95257a 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -267,11 +267,11 @@ import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useExternalLink } from '@/composables/useExternalLink' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useBillingContext } from '@/composables/billing/useBillingContext' -import { getBillingWebUrl } from '@/config/billingWeb' import SubscribeButton from '@/platform/cloud/subscription/components/SubscribeButton.vue' import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' +import { hostedBillingRoute } from '@/platform/workspace/billing/hostedBillingRoutes' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -393,10 +393,10 @@ const handleOpenWorkspaceSettings = () => { } const handleOpenPlansAndPricing = () => { - const billingWebUrl = getBillingWebUrl() + const route = hostedBillingRoute(flags.hostedBillingDestination, 'pricing') const hostedTab = - flags.hostedBillingWebEnabled && billingWebUrl - ? window.open(billingWebUrl.href, '_blank', 'noopener,noreferrer') + route.kind === 'billing_web' + ? window.open(route.url.href, '_blank', 'noopener,noreferrer') : null if (!hostedTab) { subscriptionDialog.showPricingTable({ reason: 'avatar_menu_plans' }) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 64abb06bb4e..036037350cd 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -85,6 +85,18 @@ vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError: mockReportError })) +const mockRail = vi.hoisted(() => ({ + enabled: false, + openPaymentPortal: vi.fn() +})) + +vi.mock( + import('@/platform/workspace/composables/useSubscriptionRail'), + () => ({ + useSubscriptionRail: () => (mockRail.enabled ? mockRail : null) + }) +) + vi.mock(import('@/platform/telemetry')) let scope: ReturnType | undefined @@ -843,6 +855,8 @@ describe('useWorkspaceBilling', () => { }) afterEach(() => { + mockRail.enabled = false + localStorage.clear() Object.defineProperty(window, 'location', { configurable: true, writable: true, @@ -887,6 +901,54 @@ describe('useWorkspaceBilling', () => { expect(openSpy).not.toHaveBeenCalled() }) + // Layer C is independent of Layer A: the destination decides the URL, so + // neither rail is asked for a portal link the customer will not open. + it.for([ + ['the legacy client', false], + ['the SDK rail', true] + ] as const)( + 'opens the hosted payment-methods route on %s', + async ([, railEnabled]) => { + const openSpy = vi.fn(() => window) + vi.stubGlobal('open', openSpy) + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + localStorage.setItem('ff:hosted_billing_destination', '"billing_web"') + mockRail.enabled = railEnabled + + const billing = setupBilling() + await billing.manageSubscription() + + expect(openSpy).toHaveBeenCalledWith( + 'https://billing.comfy.org/v1/payment-methods?product=comfyui&return_to=comfyui_workspace', + '_blank' + ) + expect(mockWorkspaceApi.getPaymentPortalUrl).not.toHaveBeenCalled() + expect(mockRail.openPaymentPortal).not.toHaveBeenCalled() + } + ) + + it('opens the portal URL the SDK rail returns while the server says stripe', async () => { + const openSpy = vi.fn(() => window) + vi.stubGlobal('open', openSpy) + mockRail.enabled = true + mockRail.openPaymentPortal.mockResolvedValue({ + status: 'ok', + value: 'https://billing.example/sdk-portal' + }) + + const billing = setupBilling() + await billing.manageSubscription() + + expect(mockRail.openPaymentPortal).toHaveBeenCalledWith( + 'https://app.example/settings' + ) + expect(openSpy).toHaveBeenCalledWith( + 'https://billing.example/sdk-portal', + '_blank' + ) + expect(mockWorkspaceApi.getPaymentPortalUrl).not.toHaveBeenCalled() + }) + it('records error when API call fails', async () => { mockWorkspaceApi.getPaymentPortalUrl.mockRejectedValue( new Error('portal down') diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 461b29ea0a9..82f7d6dd203 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -32,6 +32,7 @@ import { WorkspaceApiError, workspaceApi } from '@/platform/workspace/api/workspaceApi' +import { hostedBillingRoute } from '@/platform/workspace/billing/hostedBillingRoutes' import { useBillingSdkStore } from '@/platform/workspace/billing/sdk/billingSdkStore' import type { SubscriptionRailOutcome } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' @@ -537,7 +538,19 @@ export function useWorkspaceBilling(): BillingState & BillingActions { if (portalWindow) refreshOnPortalReturn() } + // Layer C before Layer A: where the customer lands is the server's call, so + // the rail the host would otherwise take never gets asked for a portal URL + // it would not open. async function manageSubscription(): Promise { + const hosted = hostedBillingRoute( + flags.hostedBillingDestination, + 'payment-methods' + ) + if (hosted.kind === 'billing_web') { + openPortalWindow(hosted.url.href) + return + } + const rail = useSubscriptionRail() if (rail) { const url = await onSubscriptionRail(() => From a243c3557c7a95db9dc2a33643bc543225fd8c72 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 16:30:17 -0400 Subject: [PATCH 3/8] test(billing): cover the hosted billing destination end to end on cloud (FE-2218) Billing & invoices is the surface both destinations share, so the spec drives it twice: stripe opens the portal URL the mocked backend returns, billing_web opens the minted payment-methods entry and never asks for a portal URL at all. The hosted origin is a build-time value, so the cloud e2e artifact now carries a reserved one. It is reachable only when the server flag says billing_web, which no deployment default does. --- .../actions/build-cloud-frontend/action.yaml | 5 + .../dialogs/hostedBillingDestination.spec.ts | 192 ++++++++++++++++++ 2 files changed, 197 insertions(+) create mode 100644 browser_tests/tests/dialogs/hostedBillingDestination.spec.ts diff --git a/.github/actions/build-cloud-frontend/action.yaml b/.github/actions/build-cloud-frontend/action.yaml index a13eeb36de6..77b8c2c24bc 100644 --- a/.github/actions/build-cloud-frontend/action.yaml +++ b/.github/actions/build-cloud-frontend/action.yaml @@ -18,6 +18,11 @@ runs: run: pnpm build:cloud env: VITE_USE_LEGACY_DEFAULT_GRAPH: 'true' + # A reserved origin the e2e suite stubs, so the hosted billing + # destination has somewhere to mint to. Reachable only when the server + # flag says billing_web, which no deployment default does. + # browser_tests/tests/dialogs/hostedBillingDestination.spec.ts pins it. + VITE_BILLING_WEB_URL: 'https://billing-web.example' - name: Verify cloud frontend shell: bash diff --git a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts new file mode 100644 index 00000000000..a904c577e00 --- /dev/null +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -0,0 +1,192 @@ +import { expect } from '@playwright/test' +import type { Page, Request } from '@playwright/test' + +import type { RemoteConfig } from '@/platform/remoteConfig/types' +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' + +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { createWorkspaceBillingCapabilities } from '@e2e/fixtures/data/billingCapabilities' +import { mockSystemStats } from '@e2e/fixtures/data/systemStats' +import { CloudAuthHelper } from '@e2e/fixtures/helpers/CloudAuthHelper' +import { FeatureFlagHelper } from '@e2e/fixtures/helpers/FeatureFlagHelper' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { + mockWorkspaceTokenMint, + workspace +} from '@e2e/fixtures/utils/workspaceMocks' + +/** + * Hosted billing destination — FE-2218, Layer C of the billing rollout. + * + * `hosted_billing_destination` decides where Billing & invoices lands, and + * nothing else does: on `stripe` the app opens the URL `/billing/payment-portal` + * handed back, on `billing_web` it mints the contract's `/v1/payment-methods` + * entry and never asks the server for a portal link. + * + * Drives a raw `page` so the cloud app boots against fully mocked endpoints, + * the same pattern as creditsTile.spec.ts. + * + * The hosted origin is baked in at build time. `.github/actions/build-cloud-frontend` + * supplies the value below; a locally served build needs the same + * `VITE_BILLING_WEB_URL`, or the hosted case falls back to the provider page. + */ +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' + +const BILLING_WEB_ORIGIN = 'https://billing-web.example' +const PROVIDER_PORTAL_URL = 'https://billing.example/portal' + +const ACTIVE_BILLING_STATUS: BillingStatusResponse = { + is_active: true, + max_seats: 1, + occupied_seats: 1, + team_credit_stop: null, + scheduled_change: null, + subscription_tier: 'PRO', + subscription_duration: 'MONTHLY', + plan_slug: 'pro-monthly', + billing_status: 'paid', + renewal_date: '2099-02-20T12:00:00Z', + has_funds: true +} + +/** Every request the app made for a provider portal URL, in order. */ +async function mockCloudBoot(page: Page): Promise { + const portalRequests: Request[] = [] + + await page.route('**/api/features', (r) => + r.fulfill( + jsonRoute({ billing_control_enabled: true } satisfies RemoteConfig) + ) + ) + await page.route('**/api/system_stats', (r) => + r.fulfill(jsonRoute(mockSystemStats)) + ) + await page.route('**/api/users', (r) => + r.fulfill( + jsonRoute({ + storage: 'server', + migrated: true, + users: { 'test-user-e2e': 'E2E Test User' } + }) + ) + ) + // TutorialCompleted suppresses the new-user template browser, whose modal + // overlay would otherwise intercept the Settings click. + await page.route('**/api/settings', (r) => + r.fulfill(jsonRoute({ 'Comfy.TutorialCompleted': true })) + ) + await page.route('**/api/userdata**', (r) => r.fulfill(jsonRoute([]))) + await page.route('**/api/extensions', (r) => r.fulfill(jsonRoute([]))) + await page.route('**/api/object_info', (r) => r.fulfill(jsonRoute({}))) + await page.route('**/api/global_subgraphs', (r) => r.fulfill(jsonRoute({}))) + await page.route('**/api/i18n', (r) => r.fulfill(jsonRoute({}))) + await page.route('**/api/auth/session', (r) => + r.fulfill(jsonRoute({ token: 'mock-workspace-token' })) + ) + await page.route('**/releases**', (r) => r.fulfill(jsonRoute([]))) + await mockWorkspaceTokenMint(page, workspace('personal', 'owner')) + await page.route('**/api/workspaces', (r) => + r.fulfill(jsonRoute({ workspaces: [workspace('personal', 'owner')] })) + ) + + await page.route('**/api/billing/status', (r) => + r.fulfill(jsonRoute(ACTIVE_BILLING_STATUS)) + ) + await page.route('**/api/billing/balance', (r) => + r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) + ) + await page.route('**/customers/balance', (r) => + r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) + ) + await page.route('**/api/billing/plans', (r) => + r.fulfill(jsonRoute({ plans: [] })) + ) + await page.route('**/api/billing/capabilities', (r) => { + if (r.request().method() !== 'GET') return r.fallback() + return r.fulfill( + jsonRoute( + createWorkspaceBillingCapabilities(workspace('personal', 'owner')) + ) + ) + }) + await page.route('**/api/billing/payment-portal', (r) => { + portalRequests.push(r.request()) + return r.fulfill(jsonRoute({ url: PROVIDER_PORTAL_URL })) + }) + + return portalRequests +} + +async function bootApp(page: Page) { + await new CloudAuthHelper(page).mockAuth() + await page.addInitScript(() => { + localStorage.setItem('Comfy.userId', 'test-user-e2e') + // Records the destination instead of opening a tab the test would have to + // dismiss; returning a window keeps the app's portal-return refresh armed. + window.open = (url) => { + document.documentElement.dataset.openedUrl = String(url) + return window + } + }) + await page.goto(APP_URL) + await page.waitForFunction(() => !!window.app?.extensionManager, null, { + timeout: 45_000 + }) +} + +/** Settings ▸ Workspace ▸ Plan & Credits, where Billing & invoices lives. */ +async function openPlanAndCredits(page: Page) { + await page + .getByRole('button', { name: /^Settings/ }) + .first() + .click() + const dialog = page.getByTestId('settings-dialog') + await expect(dialog).toBeVisible() + await dialog + .locator('nav') + .getByRole('button', { name: 'Plan & Credits' }) + .click() + + return dialog.getByRole('main') +} + +function openedUrl(page: Page) { + return page.locator('html').getAttribute('data-opened-url') +} + +test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { + test('opens the provider portal while the destination is stripe', async ({ + page + }) => { + test.setTimeout(60_000) + const portalRequests = await mockCloudBoot(page) + await bootApp(page) + + const content = await openPlanAndCredits(page) + await content.getByRole('button', { name: 'Billing & invoices' }).click() + + await expect.poll(() => openedUrl(page)).toBe(PROVIDER_PORTAL_URL) + expect(portalRequests).toHaveLength(1) + }) + + test('mints the billing-web payment-methods entry while the destination is billing_web', async ({ + page + }) => { + test.setTimeout(60_000) + const portalRequests = await mockCloudBoot(page) + await bootApp(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + hosted_billing_destination: 'billing_web' + }) + + const content = await openPlanAndCredits(page) + await content.getByRole('button', { name: 'Billing & invoices' }).click() + + await expect + .poll(() => openedUrl(page)) + .toBe( + `${BILLING_WEB_ORIGIN}/v1/payment-methods?product=comfyui&return_to=comfyui_workspace` + ) + expect(portalRequests).toHaveLength(0) + }) +}) From a2c38c93d5614e5be67c6b82299d446aa9335c62 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 17:19:46 -0400 Subject: [PATCH 4/8] fix(billing): open the hosted pricing entry without a phantom popup fallback (FE-2218) `window.open` with `noopener` always returns null per the HTML spec, so treating a falsy handle as a blocked popup fired the in-app fallback on every click: the customer got the billing-web tab and the "Choose a Plan" dialog stacked on top of it. Open the tab and stop. A genuinely blocked popup is the browser's own affordance, and `noopener,noreferrer` stays because billing-web is a separate origin that must not receive `window.opener`. --- .../CurrentUserPopoverWorkspace.test.ts | 22 +++++-------------- .../CurrentUserPopoverWorkspace.vue | 8 +++---- 2 files changed, 8 insertions(+), 22 deletions(-) diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 564dd335a36..c1f8e601b7d 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -327,6 +327,7 @@ describe('CurrentUserPopoverWorkspace', () => { it('keeps Plans & pricing in-app when hosted billing is disabled', async () => { const user = userEvent.setup() + const open = vi.spyOn(window, 'open').mockReturnValue(null) state.canOpenPricingSurface = true renderComponent('team') @@ -335,17 +336,19 @@ describe('CurrentUserPopoverWorkspace', () => { expect(state.showPricingTable).toHaveBeenCalledWith({ reason: 'avatar_menu_plans' }) + expect(open).not.toHaveBeenCalled() }) - it('opens hosted billing when its feature flag is enabled', async () => { + it('opens hosted billing alone when its feature flag is enabled', async () => { const user = userEvent.setup() - const open = vi.spyOn(window, 'open').mockReturnValue(window) + const open = vi.spyOn(window, 'open').mockReturnValue(null) state.canOpenPricingSurface = true state.hostedBillingDestination = 'billing_web' renderComponent('team') await user.click(screen.getByTestId('plans-pricing-menu-item')) + expect(open).toHaveBeenCalledOnce() expect(open).toHaveBeenCalledWith( 'http://localhost:5174/v1/pricing?product=comfyui&return_to=comfyui_workspace', '_blank', @@ -354,21 +357,6 @@ describe('CurrentUserPopoverWorkspace', () => { expect(state.showPricingTable).not.toHaveBeenCalled() }) - it('keeps Plans & pricing in-app when the hosted tab is blocked', async () => { - const user = userEvent.setup() - const open = vi.spyOn(window, 'open').mockReturnValue(null) - state.canOpenPricingSurface = true - state.hostedBillingDestination = 'billing_web' - renderComponent('team') - - await user.click(screen.getByTestId('plans-pricing-menu-item')) - - expect(open).toHaveBeenCalledOnce() - expect(state.showPricingTable).toHaveBeenCalledWith({ - reason: 'avatar_menu_plans' - }) - }) - it('keeps Plans & pricing in-app when the hosted URL is unavailable', async () => { const user = userEvent.setup() const open = vi.spyOn(window, 'open').mockImplementation(() => null) diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index 7656f95257a..859d23b3bc5 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -394,11 +394,9 @@ const handleOpenWorkspaceSettings = () => { const handleOpenPlansAndPricing = () => { const route = hostedBillingRoute(flags.hostedBillingDestination, 'pricing') - const hostedTab = - route.kind === 'billing_web' - ? window.open(route.url.href, '_blank', 'noopener,noreferrer') - : null - if (!hostedTab) { + if (route.kind === 'billing_web') { + window.open(route.url.href, '_blank', 'noopener,noreferrer') + } else { subscriptionDialog.showPricingTable({ reason: 'avatar_menu_plans' }) } emit('close') From 923819d5a57cc4ac6c1aace1fae41ec0606fd8e5 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 17:20:23 -0400 Subject: [PATCH 5/8] test(billing): cover Plans and pricing on both hosted destinations (FE-2218) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The spec's `window.open` stub returned a window for every call, so a `noopener` open looked successful to the app and the double-open went unseen. The stub now answers as a browser does — null for `noopener`, a window otherwise — and two cases assert the avatar menu's Plans and pricing entry lands on exactly one surface per destination. The dialog's frame is pushed synchronously by the click handler while its contents are lazily imported, so asserting on the frame settles the negative case instead of racing the import. --- .../dialogs/hostedBillingDestination.spec.ts | 68 +++++++++++++++++-- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts index a904c577e00..1afb0303a6a 100644 --- a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -18,10 +18,11 @@ import { /** * Hosted billing destination — FE-2218, Layer C of the billing rollout. * - * `hosted_billing_destination` decides where Billing & invoices lands, and - * nothing else does: on `stripe` the app opens the URL `/billing/payment-portal` - * handed back, on `billing_web` it mints the contract's `/v1/payment-methods` - * entry and never asks the server for a portal link. + * `hosted_billing_destination` decides where Billing & invoices and Plans and + * pricing land, and nothing else does: on `stripe` the app opens the URL + * `/billing/payment-portal` handed back and shows the in-app pricing table, on + * `billing_web` it mints the contract's `/v1/payment-methods` and `/v1/pricing` + * entries and never asks the server for a portal link. * * Drives a raw `page` so the cloud app boots against fully mocked endpoints, * the same pattern as creditsTile.spec.ts. @@ -122,10 +123,12 @@ async function bootApp(page: Page) { await page.addInitScript(() => { localStorage.setItem('Comfy.userId', 'test-user-e2e') // Records the destination instead of opening a tab the test would have to - // dismiss; returning a window keeps the app's portal-return refresh armed. - window.open = (url) => { + // dismiss. The handle follows the spec: a `noopener` open always yields + // null, while a plain one returns a window and keeps the app's + // portal-return refresh armed. + window.open = (url, _target, features) => { document.documentElement.dataset.openedUrl = String(url) - return window + return (features ?? '').includes('noopener') ? null : window } }) await page.goto(APP_URL) @@ -154,6 +157,23 @@ function openedUrl(page: Page) { return page.locator('html').getAttribute('data-opened-url') } +/** The avatar menu's Plans and pricing entry. */ +async function clickPlansAndPricing(page: Page) { + await page.getByRole('button', { name: 'Current user' }).click() + await page.getByTestId('plans-pricing-menu-item').click() +} + +const pricingHeading = (page: Page) => + page.getByRole('heading', { name: 'Choose a Plan' }) + +/** + * The in-app pricing dialog's frame. Pushed synchronously by the click + * handler, unlike its lazily imported contents, so its absence right after + * the handler ran is a settled answer rather than a race. + */ +const pricingDialog = (page: Page) => + page.locator('[data-dialog-key="subscription-required"]') + test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { test('opens the provider portal while the destination is stripe', async ({ page @@ -189,4 +209,38 @@ test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { ) expect(portalRequests).toHaveLength(0) }) + + test('opens the in-app pricing table from the avatar menu while the destination is stripe', async ({ + page + }) => { + test.setTimeout(60_000) + await mockCloudBoot(page) + await bootApp(page) + + await clickPlansAndPricing(page) + + await expect(pricingHeading(page)).toBeVisible() + expect(await openedUrl(page)).toBeNull() + }) + + test('opens the billing-web pricing entry alone from the avatar menu while the destination is billing_web', async ({ + page + }) => { + test.setTimeout(60_000) + await mockCloudBoot(page) + await bootApp(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + hosted_billing_destination: 'billing_web' + }) + + await clickPlansAndPricing(page) + + await expect + .poll(() => openedUrl(page)) + .toBe( + `${BILLING_WEB_ORIGIN}/v1/pricing?product=comfyui&return_to=comfyui_workspace` + ) + await expect(pricingDialog(page)).toHaveCount(0) + await expect(pricingHeading(page)).toBeHidden() + }) }) From fc1f36a0b1425b824ece3f6157111355dc596bc3 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 00:41:05 -0400 Subject: [PATCH 6/8] FE-2218 fix(billing): clear the stale error when the hosted destination opens The billing_web branch of manageSubscription returned without clearing error, so a failure from a previous attempt survived a successful hosted open on the composable's public error, unlike the SDK-rail and legacy branches that clear it first. Type RETURN_TO as the contract's ReturnTarget and key the deploy-env map with a DeployEnv union exported from initDatadogRum, so a typo in either fails typecheck instead of silently degrading every customer to the provider page. --- src/platform/telemetry/initDatadogRum.ts | 6 ++++-- src/platform/workspace/billing/hostedBillingRoutes.ts | 8 +++++--- src/platform/workspace/composables/useWorkspaceBilling.ts | 3 +++ 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/platform/telemetry/initDatadogRum.ts b/src/platform/telemetry/initDatadogRum.ts index 48f077aa1f7..19b2fabec1e 100644 --- a/src/platform/telemetry/initDatadogRum.ts +++ b/src/platform/telemetry/initDatadogRum.ts @@ -4,7 +4,9 @@ import { datadogRum } from '@datadog/browser-rum' import { rumBeforeSend } from './datadogRumBeforeSend' import { trackUserManualRefresh } from './manualRefreshTracker' -const DATADOG_ENV_BY_HOSTNAME = new Map([ +export type DeployEnv = 'prod-v2' | 'stg-v2' | 'test-v2' + +const DATADOG_ENV_BY_HOSTNAME = new Map([ ['cloud.comfy.org', 'prod-v2'], ['stagingcloud.comfy.org', 'stg-v2'], ['testcloud.comfy.org', 'test-v2'] @@ -63,7 +65,7 @@ async function initializeDatadogRum(env: string): Promise { */ export function resolveDeployEnv( hostname = window.location.hostname -): string | undefined { +): DeployEnv | undefined { return ( DATADOG_ENV_BY_HOSTNAME.get(hostname) ?? (hostname.endsWith('.testenvs.comfy.org') ? 'test-v2' : undefined) diff --git a/src/platform/workspace/billing/hostedBillingRoutes.ts b/src/platform/workspace/billing/hostedBillingRoutes.ts index 625dfc30783..55f83bb0314 100644 --- a/src/platform/workspace/billing/hostedBillingRoutes.ts +++ b/src/platform/workspace/billing/hostedBillingRoutes.ts @@ -18,7 +18,8 @@ */ import type { BillingEnvironment, - BillingIntent + BillingIntent, + ReturnTarget } from '@comfyorg/billing-contract' import { buildBillingEntryUrl, @@ -28,6 +29,7 @@ import { import type { HostedBillingDestination } from '@/config/billingWeb' import { getBillingWebUrl } from '@/config/billingWeb' import { getComfyCloudBaseUrl } from '@/config/comfyApi' +import type { DeployEnv } from '@/platform/telemetry/initDatadogRum' import { resolveDeployEnv } from '@/platform/telemetry/initDatadogRum' export type HostedBillingRoute = @@ -37,10 +39,10 @@ export type HostedBillingRoute = const PROVIDER: HostedBillingRoute = { kind: 'provider' } const PRODUCT = 'comfyui' -const RETURN_TO = 'comfyui_workspace' +const RETURN_TO: ReturnTarget = 'comfyui_workspace' const BILLING_ENVIRONMENT_BY_DEPLOY_ENV: Readonly< - Record + Record > = { 'prod-v2': 'production', 'stg-v2': 'staging', diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 82f7d6dd203..e870df5af1a 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -534,6 +534,8 @@ export function useWorkspaceBilling(): BillingState & BillingActions { } function openPortalWindow(url: string): void { + // The handle arms the return refresh, so adding `noopener` here (which + // nulls it) silently stops billing state from re-reading on return. const portalWindow = window.open(url, '_blank') if (portalWindow) refreshOnPortalReturn() } @@ -547,6 +549,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { 'payment-methods' ) if (hosted.kind === 'billing_web') { + error.value = null openPortalWindow(hosted.url.href) return } From edbbb616eb9f066639019f52e49fcfac263ee312 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 00:41:10 -0400 Subject: [PATCH 7/8] FE-2218 test(billing): pin the hosted return refresh and the deploy-env mapping The hosted rows asserted the minted URL and the skipped rails but never the return refresh, so replacing openPortalWindow with a bare window.open dropped the re-read and stayed green. Dispatch visibilitychange after the open and assert the status re-read. Cover the stale error the hosted branch now clears, and mock getComfyCloudBaseUrl in both suites so the environment leg no longer depends on the checkout's build-time staging base URL. --- .../CurrentUserPopoverWorkspace.test.ts | 5 ++++ .../composables/useWorkspaceBilling.test.ts | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index c1f8e601b7d..c97d580c6d5 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -150,6 +150,11 @@ vi.mock(import('@/config/billingWeb'), () => ({ getBillingWebUrl: () => state.billingWebUrl })) +// Pins the billing family the hosted route derives; an unmapped one fails closed to the provider. +vi.mock(import('@/config/comfyApi'), () => ({ + getComfyCloudBaseUrl: () => 'https://testcloud.comfy.org' +})) + const WorkspaceSwitcherPopoverStub = defineComponent({ emits: ['select', 'create'], template: ` diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 036037350cd..2e207772b81 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -99,6 +99,11 @@ vi.mock( vi.mock(import('@/platform/telemetry')) +// Pins the billing family the hosted route derives; an unmapped one fails closed to the provider. +vi.mock(import('@/config/comfyApi'), () => ({ + getComfyCloudBaseUrl: () => 'https://testcloud.comfy.org' +})) + let scope: ReturnType | undefined function setupBilling() { @@ -924,9 +929,33 @@ describe('useWorkspaceBilling', () => { ) expect(mockWorkspaceApi.getPaymentPortalUrl).not.toHaveBeenCalled() expect(mockRail.openPaymentPortal).not.toHaveBeenCalled() + + mockWorkspaceApi.getBillingStatus.mockClear() + document.dispatchEvent(new Event('visibilitychange')) + expect(mockWorkspaceApi.getBillingStatus).toHaveBeenCalledTimes(1) } ) + it('clears a failure from the previous attempt when the hosted route opens', async () => { + vi.stubGlobal( + 'open', + vi.fn(() => window) + ) + localStorage.setItem('ff:hosted_billing_destination', '"billing_web"') + mockWorkspaceApi.getPaymentPortalUrl.mockRejectedValue( + new Error('portal down') + ) + + const billing = setupBilling() + await expect(billing.manageSubscription()).rejects.toThrow('portal down') + expect(billing.error.value).toBe('portal down') + + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + await billing.manageSubscription() + + expect(billing.error.value).toBeNull() + }) + it('opens the portal URL the SDK rail returns while the server says stripe', async () => { const openSpy = vi.fn(() => window) vi.stubGlobal('open', openSpy) From d89db10da6f67d59829609dd834856874675fd94 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 00:42:14 -0400 Subject: [PATCH 8/8] FE-2218 test(billing): name the backend-family rows after what they assert The table carried an expected-family column the callback never read and asserted one URL on all three rows, under a title claiming it derives the family. What the rows prove is that each known backend mints an entry rather than falling back to the provider, so they now say that. --- .../workspace/billing/hostedBillingRoutes.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/platform/workspace/billing/hostedBillingRoutes.test.ts b/src/platform/workspace/billing/hostedBillingRoutes.test.ts index d41bb95dcbe..301405cf600 100644 --- a/src/platform/workspace/billing/hostedBillingRoutes.test.ts +++ b/src/platform/workspace/billing/hostedBillingRoutes.test.ts @@ -86,10 +86,10 @@ describe('hostedBillingRoute', () => { }) it.for([ - ['https://cloud.comfy.org', 'production'], - ['https://stagingcloud.comfy.org', 'staging'], - ['https://testcloud.comfy.org', 'test'] - ] as const)('derives %s as its billing family', ([baseUrl]) => { + 'https://cloud.comfy.org', + 'https://stagingcloud.comfy.org', + 'https://testcloud.comfy.org' + ] as const)('mints an entry for the %s backend', (baseUrl) => { cloudBaseUrl.value = baseUrl vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org')