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..1afb0303a6a --- /dev/null +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -0,0 +1,246 @@ +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 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. + * + * 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. 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 (features ?? '').includes('noopener') ? null : 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') +} + +/** 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 + }) => { + 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) + }) + + 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() + }) +}) 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/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.test.ts b/src/platform/workspace/billing/hostedBillingRoutes.test.ts new file mode 100644 index 00000000000..301405cf600 --- /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', + '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') + + 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..55f83bb0314 --- /dev/null +++ b/src/platform/workspace/billing/hostedBillingRoutes.ts @@ -0,0 +1,97 @@ +/** + * 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, + ReturnTarget +} 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 type { DeployEnv } from '@/platform/telemetry/initDatadogRum' +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: ReturnTarget = '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 +} diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 325b51d6157..c97d580c6d5 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 } } }) @@ -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: ` @@ -217,7 +222,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') }) @@ -327,6 +332,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,45 +341,32 @@ 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.hostedBillingWebEnabled = 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/', + 'http://localhost:5174/v1/pricing?product=comfyui&return_to=comfyui_workspace', '_blank', 'noopener,noreferrer' ) 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.hostedBillingWebEnabled = true - 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) state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' state.billingWebUrl = null renderComponent('team') @@ -630,7 +623,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..859d23b3bc5 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,12 +393,10 @@ const handleOpenWorkspaceSettings = () => { } const handleOpenPlansAndPricing = () => { - const billingWebUrl = getBillingWebUrl() - const hostedTab = - flags.hostedBillingWebEnabled && billingWebUrl - ? window.open(billingWebUrl.href, '_blank', 'noopener,noreferrer') - : null - if (!hostedTab) { + const route = hostedBillingRoute(flags.hostedBillingDestination, 'pricing') + if (route.kind === 'billing_web') { + window.open(route.url.href, '_blank', 'noopener,noreferrer') + } else { subscriptionDialog.showPricingTable({ reason: 'avatar_menu_plans' }) } emit('close') diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 64abb06bb4e..2e207772b81 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -85,8 +85,25 @@ 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')) +// 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() { @@ -843,6 +860,8 @@ describe('useWorkspaceBilling', () => { }) afterEach(() => { + mockRail.enabled = false + localStorage.clear() Object.defineProperty(window, 'location', { configurable: true, writable: true, @@ -887,6 +906,78 @@ 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() + + 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) + 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..e870df5af1a 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' @@ -533,11 +534,26 @@ 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() } + // 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') { + error.value = null + openPortalWindow(hosted.url.href) + return + } + const rail = useSubscriptionRail() if (rail) { const url = await onSubscriptionRail(() =>