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/apps/billing-web/src/test/fakeBillingClient.ts b/apps/billing-web/src/test/fakeBillingClient.ts index 4050f5d5628..ff47464fb19 100644 --- a/apps/billing-web/src/test/fakeBillingClient.ts +++ b/apps/billing-web/src/test/fakeBillingClient.ts @@ -166,21 +166,21 @@ export function previewOf( ): SubscriptionPreview { return { allowed: true, - cost_today_cents: 2800n, - cost_next_period_cents: 2800n, - credits_today_cents: 6900n, - credits_next_period_cents: 6900n, + cost_today_cents: 2800, + cost_next_period_cents: 2800, + credits_today_cents: 6900, + credits_next_period_cents: 6900, effective_at: '2026-10-01T00:00:00.000Z', is_immediate: true, transition_type: 'upgrade', new_plan: { - credits_cents: 6900n, + credits_cents: 6900, duration: 'MONTHLY', - price_cents: 2800n, + price_cents: 2800, seat_summary: { seat_count: 1, - total_cost_cents: 2800n, - total_credits_cents: 6900n + total_cost_cents: 2800, + total_credits_cents: 6900 }, slug: 'creator_monthly', tier: 'CREATOR' diff --git a/browser_tests/fixtures/helpers/FeatureFlagHelper.ts b/browser_tests/fixtures/helpers/FeatureFlagHelper.ts index 5fca2e7a89b..f30d6edc0ca 100644 --- a/browser_tests/fixtures/helpers/FeatureFlagHelper.ts +++ b/browser_tests/fixtures/helpers/FeatureFlagHelper.ts @@ -102,6 +102,43 @@ export class FeatureFlagHelper { }, flags) } + /** + * Seed server feature flags before the app reads them, for a flag a + * boot-time action depends on — a `?pricing=` deep link opens its dialog + * from `onMounted`, so `setServerFlagsPersistent()` lands after the dialog + * has already chosen a rail. + * + * `window.app` is what gates this: it is assigned in `GraphCanvas`'s + * `onMounted` just before the URL action loaders run, so an accessor + * installed here applies the flags in that window and re-applies on every + * later `feature_flags` handshake, as `setServerFlagsPersistent()` does. + * + * Must be called before `page.goto()`; init scripts persist for the page + * lifetime and cannot be removed. + */ + async seedServerFlags(flags: Record): Promise { + await this.page.addInitScript((flagMap: Record) => { + let comfyApp: Window['app'] + Object.defineProperty(window, 'app', { + configurable: true, + get: () => comfyApp, + set: (value: Window['app']) => { + comfyApp = value + const api = value?.api + if (!api) return + const apply = () => { + api.serverFeatureFlags.value = { + ...api.serverFeatureFlags.value, + ...flagMap + } + } + apply() + api.addEventListener('feature_flags', apply) + } + }) + }, flags) + } + /** * Remove server feature flags and keep them removed across websocket * reconnects, pinning the flag-ABSENT state. The real backend may or may diff --git a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts new file mode 100644 index 00000000000..8c6878870c3 --- /dev/null +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -0,0 +1,270 @@ +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') + const recordDestination = (url: string) => { + document.documentElement.dataset.openedUrl = url + } + // A handle whose navigation is recorded rather than performed. Handing + // back the live `window` would let the disowned-tab open -- blank tab, + // null the opener, then assign `location.href` -- steer this page to the + // hosted origin instead. + const standInTab = new Proxy(window, { + get: (target, property) => + property === 'location' + ? { + get href() { + return document.documentElement.dataset.openedUrl ?? '' + }, + set href(destination: string) { + recordDestination(destination) + } + } + : Reflect.get(target, property), + // The tab is disowned before it navigates, and a stand-in that never + // navigates has nothing to disown, so the write is swallowed rather + // than reaching this page's own `window.opener`. + set: () => true + }) + // 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) => { + if (url) recordDestination(String(url)) + return (features ?? '').includes('noopener') ? null : standInTab + } + }) + 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/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts b/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts new file mode 100644 index 00000000000..427d2481c94 --- /dev/null +++ b/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts @@ -0,0 +1,318 @@ +import { expect } from '@playwright/test' +import type { Page, Request } from '@playwright/test' +import type { + BillingOpStatusResponse, + BillingPlansResponse, + BillingStatusResponse, + Plan, + PreviewSubscribeResponse, + SubscribeResponse +} from '@comfyorg/ingest-types' + +import type { RemoteConfig } from '@/platform/remoteConfig/types' + +import { + cloudAppExpect, + cloudAppFixture as test +} from '@e2e/fixtures/cloudAppFixture' +import { createWorkspaceBillingCapabilities } from '@e2e/fixtures/data/billingCapabilities' +import { FeatureFlagHelper } from '@e2e/fixtures/helpers/FeatureFlagHelper' +import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' +import { bootCloud, mockCloudBoot } from '@e2e/fixtures/utils/cloudBootMocks' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' + +/** + * Changing plan across the billing SDK rail — FE-2216. + * + * Both rails quote through `POST /billing/preview-subscribe` and commit through + * `POST /billing/subscribe`, so the recorded requests are what separate them: + * only the SDK transport sends an `Idempotency-Key`, and only on the write — + * the quote is a read the backend happens to shape as a POST, so it carries + * none on either rail. What separates the two quotes is the transport that + * issued them: the SDK runs on `fetch`, the workspace client on axios' XHR. + */ +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' + +const BOOT_FEATURES = { + billing_control_enabled: true, + unified_cloud_auth: true +} satisfies RemoteConfig + +const STANDARD_ANNUAL_PLAN = { + slug: 'standard-annual', + tier: 'STANDARD', + duration: 'ANNUAL', + price_cents: 19_200, + credits_cents: 4_200, + max_seats: 1, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: 19_200, + total_credits_cents: 4_200 + } +} satisfies Plan + +const CREATOR_ANNUAL_PLAN = { + slug: 'creator-annual', + tier: 'CREATOR', + duration: 'ANNUAL', + price_cents: 33_600, + credits_cents: 7_400, + max_seats: 5, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: 33_600, + total_credits_cents: 7_400 + } +} satisfies Plan + +const ACTIVE_STANDARD_STATUS = { + is_active: true, + subscription_status: 'active', + subscription_tier: 'STANDARD', + subscription_duration: 'ANNUAL', + plan_slug: 'standard-annual', + billing_rail: 'stripe', + billing_status: 'paid', + has_funds: true, + renewal_date: '2099-02-20T00:00:00Z', + team_credit_stop: null, + scheduled_change: null, + max_seats: 1, + occupied_seats: 1 +} satisfies BillingStatusResponse + +const PLANS = { + current_plan_slug: 'standard-annual', + plans: [STANDARD_ANNUAL_PLAN, CREATOR_ANNUAL_PLAN] +} satisfies BillingPlansResponse + +const CREATOR_UPGRADE_QUOTE = { + allowed: true, + transition_type: 'upgrade', + effective_at: '2026-09-16T00:00:00Z', + is_immediate: true, + cost_today_cents: 14_400, + cost_next_period_cents: 33_600, + credits_today_cents: 3_200, + credits_next_period_cents: 7_400, + current_plan: { + slug: STANDARD_ANNUAL_PLAN.slug, + tier: STANDARD_ANNUAL_PLAN.tier, + duration: STANDARD_ANNUAL_PLAN.duration, + price_cents: STANDARD_ANNUAL_PLAN.price_cents, + credits_cents: STANDARD_ANNUAL_PLAN.credits_cents, + seat_summary: STANDARD_ANNUAL_PLAN.seat_summary, + period_end: '2099-02-20T00:00:00Z' + }, + new_plan: { + slug: CREATOR_ANNUAL_PLAN.slug, + tier: CREATOR_ANNUAL_PLAN.tier, + duration: CREATOR_ANNUAL_PLAN.duration, + price_cents: CREATOR_ANNUAL_PLAN.price_cents, + credits_cents: CREATOR_ANNUAL_PLAN.credits_cents, + seat_summary: CREATOR_ANNUAL_PLAN.seat_summary + } +} satisfies PreviewSubscribeResponse + +const CHANGE_OPERATION_ID = 'op-plan-change' + +const SUBSCRIBED_RESPONSE = { + billing_op_id: CHANGE_OPERATION_ID, + status: 'subscribed', + effective_at: '2026-09-16T00:00:00Z' +} satisfies SubscribeResponse + +const SETTLED_OPERATION = { + id: CHANGE_OPERATION_ID, + status: 'succeeded', + started_at: '2026-09-16T00:00:00Z', + completed_at: '2026-09-16T00:00:05Z' +} satisfies BillingOpStatusResponse + +interface PlanChangeRoutes { + /** Every POST the app made to the quote route, in order. */ + readonly previewRequests: Request[] + /** Every POST the app made to the subscribe route, in order. */ + readonly subscribeRequests: Request[] + /** Answers the next subscribe with a 404, as a closed backend gate does. */ + respondNotFound: () => void +} + +// The deep-link loader runs at the tail of GraphCanvas onMounted, so the boot +// chain must not throw before it. +async function mockGraphBootExtras(page: Page) { + await page.route('**/api/settings/**', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({})) + }) + await page.route('**/api/assets**', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ assets: [], total: 0, has_more: false })) + }) + await page.route('**/api/prompt', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ exec_info: { queue_remaining: 0 } })) + }) + await page.route('**/api/queue', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ queue_running: [], queue_pending: [] })) + }) +} + +async function setupPlanChange(page: Page): Promise { + const ws = workspace('personal', 'owner') + const previewRequests: Request[] = [] + const subscribeRequests: Request[] = [] + let notFound = false + + await mockCloudBoot(page, { + features: BOOT_FEATURES, + settings: { 'Comfy.TutorialCompleted': true } + }) + await mockGraphBootExtras(page) + await mockBilling(page, { + workspaceId: ws.id, + billingStatus: ACTIVE_STANDARD_STATUS, + billingCapabilities: createWorkspaceBillingCapabilities(ws) + }) + await mockWorkspace(page, ws, []) + + await page.route('**/api/billing/plans', (route) => + route.fulfill(jsonRoute(PLANS)) + ) + await page.route('**/api/billing/preview-subscribe', (route) => { + previewRequests.push(route.request()) + return route.fulfill(jsonRoute(CREATOR_UPGRADE_QUOTE)) + }) + await page.route('**/api/billing/subscribe', async (route) => { + subscribeRequests.push(route.request()) + if (notFound) { + notFound = false + await route.fulfill({ status: 404, body: '' }) + return + } + await route.fulfill(jsonRoute(SUBSCRIBED_RESPONSE)) + }) + // Only the SDK rail polls a `subscribed` response; the legacy path reports + // success straight from the body. + await page.route(`**/api/billing/ops/${CHANGE_OPERATION_ID}`, (route) => + route.fulfill(jsonRoute(SETTLED_OPERATION)) + ) + + await bootCloud(page) + return { + previewRequests, + subscribeRequests, + respondNotFound: () => { + notFound = true + } + } +} + +/** The SDK transport sends this header; the legacy axios client never does. */ +function idempotencyKey(request: Request): string | undefined { + return request.headers()['idempotency-key'] +} + +/** + * Which transport issued a request, and so which rail served it: the SDK's + * runs on `fetch`, the legacy workspace client on axios' XHR adapter. The + * quote carries no idempotency key on either rail, so this is what tells the + * two quotes apart. + */ +function transport(request: Request): string { + return request.resourceType() +} + +/** + * The `?pricing=` deep link quotes the plan as the dialog opens, from the same + * `onMounted` that assigns `window.app`, so the rail has to be chosen before + * the page loads rather than after it. + */ +async function enableSdkRail(page: Page) { + await new FeatureFlagHelper(page).seedServerFlags({ + billing_sdk_subscription_enabled: true + }) +} + +async function openCreatorUpgrade(page: Page) { + await page.goto(`${APP_URL}/?pricing=creator&cycle=yearly`) + await cloudAppExpect( + page.getByRole('heading', { name: 'Confirm your upgrade' }) + ).toBeVisible() +} + +const confirmButton = (page: Page) => + page.getByRole('button', { name: 'Confirm upgrade' }) + +const successHeading = (page: Page) => + page.getByRole('heading', { name: "You're all set" }) + +test.describe('Plan change rail (FE-2216)', { tag: '@cloud' }, () => { + test('keeps the legacy calls while the SDK rail is off', async ({ page }) => { + test.setTimeout(60_000) + const routes = await setupPlanChange(page) + + await openCreatorUpgrade(page) + await confirmButton(page).click() + + await expect(successHeading(page)).toBeVisible() + expect(routes.subscribeRequests).toHaveLength(1) + expect(idempotencyKey(routes.subscribeRequests[0])).toBeUndefined() + expect(routes.previewRequests.length).toBeGreaterThan(0) + expect(idempotencyKey(routes.previewRequests[0])).toBeUndefined() + expect(transport(routes.previewRequests[0])).toBe('xhr') + expect(transport(routes.subscribeRequests[0])).toBe('xhr') + }) + + test('issues through the SDK transport while the rail is on', async ({ + page + }) => { + test.setTimeout(60_000) + const routes = await setupPlanChange(page) + await enableSdkRail(page) + await openCreatorUpgrade(page) + + await confirmButton(page).click() + + await expect(successHeading(page)).toBeVisible() + expect(routes.subscribeRequests).toHaveLength(1) + const [issued] = routes.subscribeRequests + expect(issued.method()).toBe('POST') + expect(idempotencyKey(issued)).toBeTruthy() + expect(issued.postDataJSON()).toMatchObject({ + plan_slug: 'creator-annual', + idempotency_key: idempotencyKey(issued) + }) + expect(transport(issued)).toBe('fetch') + // The quote is a read the SDK sends no key for, so the transport is what + // shows the rail served it. + const quote = routes.previewRequests.at(-1)! + expect(transport(quote)).toBe('fetch') + expect(idempotencyKey(quote)).toBeUndefined() + }) + + test('falls back to the legacy call when the SDK route answers 404', async ({ + page + }) => { + test.setTimeout(60_000) + const routes = await setupPlanChange(page) + await enableSdkRail(page) + await openCreatorUpgrade(page) + routes.respondNotFound() + + await confirmButton(page).click() + + await expect(successHeading(page)).toBeVisible() + await expect.poll(() => routes.subscribeRequests.length).toBe(2) + const [sdkAttempt, legacyAttempt] = routes.subscribeRequests + expect(idempotencyKey(sdkAttempt)).toBeTruthy() + expect(idempotencyKey(legacyAttempt)).toBeUndefined() + expect(transport(sdkAttempt)).toBe('fetch') + expect(transport(legacyAttempt)).toBe('xhr') + }) +}) diff --git a/package.json b/package.json index 80599969d9b..c0297b0d51f 100644 --- a/package.json +++ b/package.json @@ -96,6 +96,7 @@ "@atlaskit/pragmatic-drag-and-drop": "^1.3.1", "@comfyorg/account-core": "workspace:*", "@comfyorg/account-ui": "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/packages/account-core/docs/billing-command-eligibility.md b/packages/account-core/docs/billing-command-eligibility.md new file mode 100644 index 00000000000..a1fd688eeb1 --- /dev/null +++ b/packages/account-core/docs/billing-command-eligibility.md @@ -0,0 +1,50 @@ +# Billing command eligibility + +No subscription command reads the subscription's state to decide whether it +may run. Pricing a change, reactivating a scheduled cancel, rejecting a +duplicate and demanding a confirmation are all server decisions, and a client +that second-guesses them denies transitions the server would have allowed. + +## Routes + +| Command | Route | +| ------------- | ------------------------- | +| `subscribe` | `POST /billing/subscribe` | +| `resubscribe` | `POST .../resubscribe` | +| `cancel` | `POST .../cancel` | + +The status read decides nothing for `subscribe`: whatever state the +subscription is in, the request goes to the subscribe route carrying the +`plan_slug` that was asked for, and the server prices the change, reactivates a +scheduled cancel, or refuses. Routing a scheduled cancel to `resubscribe()` +would drop that plan and resume the old one instead; `resubscribe` stays the +explicit "resume subscription" action, which carries no plan of its own. + +## Already-held answers + +A command whose requested state already holds is a success, not a failure: the +caller's intent is satisfied and the request changed nothing. `mapServerCode` +recognises one such code per command, and only from a 4xx — a 5xx that happens +to echo the code is an upstream failure, and the requested state cannot be +assumed to hold. + +| Command | Already-held server code | +| ------------- | -------------------------------- | +| `resubscribe` | `NOT_SCHEDULED_FOR_CANCELLATION` | +| `cancel` | `ALREADY_CANCELED` | +| `subscribe` | none documented on the route | + +The subscribe route documents no already-held code, so `subscribe` never +settles without an operation. A repeat subscribe against a live subscription +surfaces whatever the server answers, exactly as the host's own +`POST /billing/subscribe` call does. + +## Codes the command maps itself + +- `REACTIVATION_CONFIRMATION_REQUIRED` — the server wants the host to + re-preview and resend with `confirm_reactivation`. It exists for exactly the + subscribe-on-a-scheduled-cancel case. +- `NO_ACTIVE_SUBSCRIPTION` — resubscribe or cancel with nothing to act on. + +Every other server code reaches the caller as the transport's coded failure, +with `serverCode` intact. diff --git a/packages/account-core/src/core/billing/subscriptionCommands.test.ts b/packages/account-core/src/core/billing/subscriptionCommands.test.ts index e6f3c4571ae..1ad72cd2fc9 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.test.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.test.ts @@ -1,4 +1,12 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + assert, + beforeEach, + describe, + expect, + expectTypeOf, + it, + vi +} from 'vitest' import type { SessionClient, SessionSnapshot } from '../session.js' import type { AccountCredential } from '../sessionContracts.js' @@ -26,6 +34,7 @@ import type { BillingStatusReader, BillingStatusSnapshot } from './status.js' +import type { SubscriptionPreview } from './subscriptionCommands.js' import { CANCEL_SUBSCRIPTION_ROUTE, PAYMENT_PORTAL_ROUTE, @@ -253,7 +262,7 @@ beforeEach(() => { }) describe('createBillingCommands', () => { - describe('eligibility from the status snapshot', () => { + describe('each command against the subscription state', () => { it('FREE: subscribe issues the checkout and settles the operation', async () => { const h = harness({ status: FREE, @@ -307,14 +316,43 @@ describe('createBillingCommands', () => { expect(h.lifecycle.getSnapshot()).toEqual([]) }) - it('PRO active: subscribe is a no-op success without a request', async () => { - const h = harness({ status: PRO_ACTIVE }) + it('PRO active: subscribe issues the plan change the server has to price', async () => { + const h = harness({ + status: PRO_ACTIVE, + script: { [POST_SUBSCRIBE]: [subscribed], [GET_OP]: settledOk } + }) + + const result = await h.commands.subscribe({ plan_slug: 'pro-yearly' }) + + expect(result).toMatchObject({ + status: 'ok', + value: { phase: 'succeeded', operation: { id: 'op-1' } } + }) + expect(h.posts()).toEqual([ + expect.objectContaining({ + route: SUBSCRIBE_ROUTE, + body: { plan_slug: 'pro-yearly', idempotency_key: 'key-1' } + }) + ]) + expect(h.invalidate).toHaveBeenCalledOnce() + }) + + it('PRO active: subscribe leaves the server to refuse a transition, code intact', async () => { + const h = harness({ + status: PRO_ACTIVE, + script: { + [POST_SUBSCRIBE]: [serverError(409, 'TRANSITION_NOT_ALLOWED')] + } + }) const result = await h.commands.subscribe(PLAN) - expect(result).toEqual({ status: 'ok', value: { phase: 'succeeded' } }) - expect(h.calls).toEqual([]) - expect(h.invalidate).not.toHaveBeenCalled() + expect(result).toMatchObject({ + status: 'error', + serverCode: 'TRANSITION_NOT_ALLOWED', + httpStatus: 409 + }) + expect(h.posts().map((call) => call.route)).toEqual([SUBSCRIBE_ROUTE]) }) it('PRO active: resubscribe already holds and re-reads status', async () => { @@ -364,24 +402,50 @@ describe('createBillingCommands', () => { expect(h.invalidate).toHaveBeenCalledOnce() }) - it('PRO canceled: subscribe routes to the resubscribe endpoint', async () => { + it('PRO canceled: subscribe carries the requested plan to the subscribe route', async () => { + const h = harness({ + status: PRO_CANCELED, + script: { [POST_SUBSCRIBE]: [subscribed], [GET_OP]: settledOk } + }) + + const result = await h.commands.subscribe({ + plan_slug: 'pro-yearly', + confirm_reactivation: true + }) + + expect(result).toMatchObject({ + status: 'ok', + value: { phase: 'succeeded', operation: { id: 'op-1' } } + }) + expect(h.posts()).toEqual([ + expect.objectContaining({ + route: SUBSCRIBE_ROUTE, + body: { + plan_slug: 'pro-yearly', + confirm_reactivation: true, + idempotency_key: 'key-1' + } + }) + ]) + }) + + it('PRO canceled: subscribe hands the server its reactivation block back', async () => { const h = harness({ status: PRO_CANCELED, script: { - [POST_RESUBSCRIBE]: [ - http(200, { billing_op_id: 'op-1', status: 'active' }) - ], - [GET_OP]: settledOk + [POST_SUBSCRIBE]: [ + serverError(409, 'REACTIVATION_CONFIRMATION_REQUIRED') + ] } }) const result = await h.commands.subscribe(PLAN) - expect(result).toMatchObject({ - status: 'ok', - value: { phase: 'succeeded', operation: { kind: 'subscription' } } + expect(result).toEqual({ + status: 'error', + code: 'REACTIVATION_CONFIRMATION_REQUIRED' }) - expect(h.posts().map((call) => call.route)).toEqual([RESUBSCRIBE_ROUTE]) + expect(h.posts().map((call) => call.route)).toEqual([SUBSCRIBE_ROUTE]) }) it('PRO canceled: resubscribe settles a pending reactivation through the lifecycle', async () => { @@ -531,8 +595,8 @@ describe('createBillingCommands', () => { status: 'ok', value: { allowed: true, - cost_today_cents: 1500n, - new_plan: { slug: 'pro-monthly', price_cents: 2000n }, + cost_today_cents: 1500, + new_plan: { slug: 'pro-monthly', price_cents: 2000 }, transition_type: 'upgrade' } }) @@ -579,7 +643,7 @@ describe('createBillingCommands', () => { value: expect.objectContaining({ discounts: [ { - amount_off_cents: 500n, + amount_off_cents: 500, code: 'LAUNCH', kind: 'promotion', name: 'Launch offer' @@ -672,6 +736,110 @@ describe('createBillingCommands', () => { }) }) + const QUOTE_CENT_FIELDS = [ + 'amount_due_cents', + 'cost_next_period_cents', + 'cost_today_cents', + 'credits_next_period_cents', + 'credits_today_cents', + 'renewal_amount_cents' + ] as const satisfies readonly (keyof SubscriptionPreview)[] + + const PLAN_CENT_FIELDS = [ + 'credits_cents', + 'price_cents' + ] as const satisfies readonly (keyof SubscriptionPreview['new_plan'])[] + + const SEAT_CENT_FIELDS = [ + 'total_cost_cents', + 'total_credits_cents' + ] as const satisfies readonly (keyof SubscriptionPreview['new_plan']['seat_summary'])[] + + // Compile-time pins: an amount a regen adds fails the package typecheck + // until it reaches a row below. + expectTypeOf<(typeof QUOTE_CENT_FIELDS)[number]>().toEqualTypeOf< + Extract + >() + expectTypeOf<(typeof PLAN_CENT_FIELDS)[number]>().toEqualTypeOf< + Extract + >() + expectTypeOf<(typeof SEAT_CENT_FIELDS)[number]>().toEqualTypeOf< + Extract< + keyof SubscriptionPreview['new_plan']['seat_summary'], + `${string}_cents` + > + >() + + const rejectsQuote = async (patch: object) => { + const h = harness({ + status: FREE, + script: { [POST_PREVIEW]: [http(200, { ...QUOTE_BODY, ...patch })] } + }) + + await expect( + h.commands.previewSubscribe({ planSlug: 'pro-monthly' }) + ).resolves.toEqual({ + status: 'error', + code: 'MALFORMED_RESPONSE', + httpStatus: 200 + }) + } + + const FRACTION_OF_A_CENT = 1500.5 + + it.for(QUOTE_CENT_FIELDS)('refuses a fraction of a cent at %s', (field) => + rejectsQuote({ [field]: FRACTION_OF_A_CENT }) + ) + + it.for(PLAN_CENT_FIELDS)( + 'refuses a fraction of a cent at new_plan.%s', + (field) => + rejectsQuote({ + new_plan: { ...PREVIEW_PLAN, [field]: FRACTION_OF_A_CENT } + }) + ) + + it.for(PLAN_CENT_FIELDS)( + 'refuses a fraction of a cent at current_plan.%s', + (field) => + rejectsQuote({ + current_plan: { ...PREVIEW_PLAN, [field]: FRACTION_OF_A_CENT } + }) + ) + + it.for(SEAT_CENT_FIELDS)( + 'refuses a fraction of a cent at new_plan.seat_summary.%s', + (field) => + rejectsQuote({ + new_plan: { + ...PREVIEW_PLAN, + seat_summary: { + ...PREVIEW_PLAN.seat_summary, + [field]: FRACTION_OF_A_CENT + } + } + }) + ) + + it('refuses a fraction of a cent off a discount', () => + rejectsQuote({ + discounts: [ + { + amount_off_cents: FRACTION_OF_A_CENT, + code: 'LAUNCH', + kind: 'promotion', + name: 'Launch offer' + } + ] + })) + + it.for([ + ['past the safe integers', Number.MAX_SAFE_INTEGER + 2], + ['with no finite value at all', Number.POSITIVE_INFINITY] + ] as const)('refuses an amount %s', ([, cents]) => + rejectsQuote({ cost_today_cents: cents }) + ) + it('forwards the caller signal and timeout, releasing an abandoned read as transient', async () => { const controller = new AbortController() const h = harness({ @@ -843,6 +1011,56 @@ describe('createBillingCommands', () => { }) }) + it.for([ + ['subscribed', subscribed], + ['pending_payment', pendingPayment], + [ + 'needs_payment_method', + http(200, { + billing_op_id: 'op-1', + status: 'needs_payment_method', + payment_method_url: 'https://checkout.example/pay' + }) + ] + ] as const)( + 'settles a %s subscribe under the status the server issued it with', + async ([issuedStatus, response]) => { + const h = harness({ + status: FREE, + script: { [POST_SUBSCRIBE]: [response], [GET_OP]: settledOk } + }) + + const result = h.commands.subscribe(PLAN) + await flush() + await vi.advanceTimersByTimeAsync(OPERATION_POLL_TIMING.parkedMs) + + await expect(result).resolves.toMatchObject({ + status: 'ok', + value: { phase: 'succeeded', issuedStatus } + }) + } + ) + + it('leaves a cancel without an issued subscribe status', async () => { + const h = harness({ + status: PRO_ACTIVE, + script: { + [POST_CANCEL]: [ + http(200, { + billing_op_id: 'op-1', + cancel_at: '2026-10-01T00:00:00.000Z' + }) + ], + [GET_OP]: settledOk + } + }) + + const result = await h.commands.cancelSubscription() + + assert(result.status === 'ok') + expect(result.value.issuedStatus).toBeUndefined() + }) + it('reports a hosted payment step without a page as MISSING_PAYMENT_METHOD_URL', async () => { const h = harness({ status: FREE, diff --git a/packages/account-core/src/core/billing/subscriptionCommands.ts b/packages/account-core/src/core/billing/subscriptionCommands.ts index 4ffafe92fe7..1192491feb9 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.ts @@ -6,21 +6,23 @@ * stay in the lifecycle. `previewSubscribe` sits beside them without a * lifecycle: it only quotes a change. * - * Eligibility is decided from the server's own status fields, never from a - * client-side notion of the plan (`docs/billing-command-eligibility.md`). - * Server codes are matched against the closed set named here; a code outside - * it reaches the caller only as the transport's coded failure. + * No command decides for the server whether a transition is allowed + * (`../../../docs/billing-command-eligibility.md`). Server codes are matched + * against the closed set named here; a code outside it reaches the caller only + * as the transport's coded failure. */ import { zCancelSubscriptionResponse2, zPaymentPortalResponse, + zPreviewPlanInfo, zPreviewSubscribeRequest, zPreviewSubscribeResponse, zResubscribeResponse, zSubscribeRequest, - zSubscribeResponse + zSubscribeResponse, + zSubscriptionDiscount } from '@comfyorg/ingest-types/zod' -import type { z } from 'zod' +import { z } from 'zod' import type { BillingFailure, BillingTransport } from './billingContracts.js' import { matchesServerCode } from './billingContracts.js' @@ -37,7 +39,7 @@ import type { } from './operationState.js' import { validateActionUrl } from './operationState.js' import { readValidatedBillingResponse } from './sharedRead.js' -import type { BillingStatusData, BillingStatusReader } from './status.js' +import type { BillingStatusReader } from './status.js' export const SUBSCRIBE_ROUTE = '/billing/subscribe' export const RESUBSCRIBE_ROUTE = '/billing/subscription/resubscribe' @@ -76,10 +78,21 @@ export type SubscriptionCommandFailure = | BillingFailure | { readonly status: 'error'; readonly code: SubscriptionCommandCode } +/** What the subscribe route answered before the lifecycle drove the operation on. */ +type SubscribeIssuedStatus = z.infer['status'] + export interface SubscriptionCommandOutcome { readonly phase: TerminalBillingOperation['phase'] /** Absent when the requested state already held and nothing was issued. */ readonly operation?: TerminalBillingOperation + /** + * The `status` the subscribe response carried, before the lifecycle settled + * the operation: `subscribed` is a plan the server activated on the spot, + * the other two are payment steps it could not complete without the + * customer. Absent for every other command, and for a subscribe that + * adopted an operation the server was already settling. + */ + readonly issuedStatus?: SubscribeIssuedStatus } export type SubscriptionCommandResult = @@ -90,6 +103,40 @@ export type PaymentPortalResult = | { readonly status: 'ok'; readonly value: { readonly url: string } } | BillingFailure +/** + * The generated schema coerces every int64 to a `bigint`, which no caller can + * add to a price or hand to a currency formatter — and the generated *type* + * for the same field is a `number`. Money on this route is bounded to cents + * well inside the JavaScript-safe range, so the cents are read as numbers, the + * way `capabilities` reads `revision` — as whole units of currency that + * survive arithmetic, since these amounts are displayed as prices and + * confirmed as charges. + */ +const cents = z.number().int().safe() + +const PlanInfoSchema = zPreviewPlanInfo.extend({ + credits_cents: cents, + price_cents: cents, + seat_summary: zPreviewPlanInfo.shape.seat_summary.extend({ + total_cost_cents: cents, + total_credits_cents: cents + }) +}) + +const PreviewSchema = zPreviewSubscribeResponse.extend({ + amount_due_cents: cents.optional(), + cost_next_period_cents: cents, + cost_today_cents: cents, + credits_next_period_cents: cents, + credits_today_cents: cents, + renewal_amount_cents: cents.optional(), + current_plan: PlanInfoSchema.optional(), + new_plan: PlanInfoSchema, + discounts: z + .array(zSubscriptionDiscount.extend({ amount_off_cents: cents.optional() })) + .optional() +}) + /** * The quote the server returns for a plan change, in the generated field names. * @@ -98,7 +145,7 @@ export type PaymentPortalResult = * `promotion` one carries back the very `promotionCode` the caller sent, so a * host renders `code` and `name` rather than matching them. */ -export type SubscriptionPreview = z.infer +export type SubscriptionPreview = z.infer export interface PreviewSubscribeInput { readonly planSlug: string @@ -146,8 +193,14 @@ export interface BillingCommands { }) => Promise } +interface IssuedOutcome { + readonly status: 'ok' + readonly value: IssuedBillingOperation + readonly issuedStatus?: SubscribeIssuedStatus +} + type IssueOutcome = - | { readonly status: 'ok'; readonly value: IssuedBillingOperation } + | IssuedOutcome /** The server refused because the requested state already holds. */ | { readonly status: 'already_held' } | SubscriptionCommandFailure @@ -161,17 +214,6 @@ function coded(code: SubscriptionCommandCode): SubscriptionCommandFailure { return { status: 'error', code } } -type Eligibility = 'free' | 'active' | 'canceled' - -function eligibilityOf(status: BillingStatusData): Eligibility { - const paid = - status.is_active && - status.subscription_tier !== undefined && - status.subscription_tier !== 'FREE' - if (!paid) return 'free' - return status.subscription_status === 'canceled' ? 'canceled' : 'active' -} - /** * A server code the caller's request already satisfies is a success, but * only from a 4xx: a 5xx echoing the code is an upstream failure that @@ -259,11 +301,17 @@ export function createBillingCommands( issue: () => Promise ): Promise { // The lifecycle carries only the shared codes; the command's own verdict - // waits here for `begin` to return. + // and what it read off the issuing response wait here for `begin` to + // return. Both stay unset when `begin` adopted an operation the server was + // already settling instead of issuing this one. const verdict: { value?: Exclude } = {} + const issued: { value?: IssuedOutcome } = {} const began = await lifecycle.begin(kind, async () => { const outcome = await issue() - if (outcome.status === 'ok') return outcome + if (outcome.status === 'ok') { + issued.value = outcome + return outcome + } verdict.value = outcome return { status: 'error', code: 'REQUEST_FAILED' } }) @@ -280,7 +328,15 @@ export function createBillingCommands( return { status: 'error', code: 'SUPERSEDED' } } if (operation.phase === 'succeeded') await refreshAfterSuccess() - return { status: 'ok', value: { phase: operation.phase, operation } } + const issuedStatus = issued.value?.issuedStatus + return { + status: 'ok', + value: { + phase: operation.phase, + operation, + ...(issuedStatus === undefined ? {} : { issuedStatus }) + } + } } async function issueSubscribe(input: SubscribeInput): Promise { @@ -301,14 +357,19 @@ export function createBillingCommands( } const { billing_op_id, status, payment_method_url } = response.value.data if (status !== 'needs_payment_method') { - return { status: 'ok', value: { operationId: billing_op_id } } + return { + status: 'ok', + value: { operationId: billing_op_id }, + issuedStatus: status + } } if (payment_method_url === undefined) { return coded('MISSING_PAYMENT_METHOD_URL') } return { status: 'ok', - value: { operationId: billing_op_id, actionUrl: payment_method_url } + value: { operationId: billing_op_id, actionUrl: payment_method_url }, + issuedStatus: status } } @@ -367,16 +428,7 @@ export function createBillingCommands( return coded('INVALID_REQUEST') } - const status = await statusReader.read() - if (status.status === 'error') return status - switch (eligibilityOf(status.value.status)) { - case 'active': - return ALREADY_HELD - case 'canceled': - return resubscribe() - case 'free': - return settle('subscription', () => issueSubscribe(request)) - } + return settle('subscription', () => issueSubscribe(request)) } async function previewSubscribe( @@ -398,7 +450,7 @@ export function createBillingCommands( ? {} : { timeoutMs: options.timeoutMs }) }, - (raw) => zPreviewSubscribeResponse.safeParse(raw) + (raw) => PreviewSchema.safeParse(raw) ) return response.status === 'error' ? response diff --git a/packages/account-ui/src/billing/usePreviewSubscribe.test.ts b/packages/account-ui/src/billing/usePreviewSubscribe.test.ts index 83a570d871f..9e28f8373cc 100644 --- a/packages/account-ui/src/billing/usePreviewSubscribe.test.ts +++ b/packages/account-ui/src/billing/usePreviewSubscribe.test.ts @@ -54,7 +54,7 @@ describe('usePreviewSubscribe', () => { await quoting expect(preview.preview.value).toMatchObject({ - cost_today_cents: 1500n, + cost_today_cents: 1500, new_plan: { slug: 'pro_monthly' } }) expect(preview.loading.value).toBe(false) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 277fc3d39af..bcd6ff897e0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -503,6 +503,9 @@ importers: '@comfyorg/account-ui': specifier: workspace:* version: link:packages/account-ui + '@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..56c6779374b --- /dev/null +++ b/src/platform/workspace/billing/hostedBillingRoutes.test.ts @@ -0,0 +1,121 @@ +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 when the cloud base URL will not parse', () => { + cloudBaseUrl.value = 'not-a-url' + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + + expect(hostedBillingRoute('billing_web', 'pricing')).toEqual({ + kind: 'provider' + }) + }) + + 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..e0d13483eea --- /dev/null +++ b/src/platform/workspace/billing/hostedBillingRoutes.ts @@ -0,0 +1,110 @@ +/** + * 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' +} + +function hostnameOf(url: string): string | undefined { + try { + return new URL(url).hostname + } catch { + return undefined + } +} + +/** + * 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. A + * 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( + cloudBaseUrl = getComfyCloudBaseUrl() +): BillingEnvironment | undefined { + const hostname = hostnameOf(cloudBaseUrl) + if (hostname === undefined) return undefined + + const deployEnv = resolveDeployEnv(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/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 6fe6143b5af..8f6ff059393 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -12,6 +12,7 @@ import { fakeBillingSdk, failedTopup, pendingTopup, + pendingSubscription, settledOperation, settledTopup } from './billingSdkTestUtils' @@ -403,6 +404,29 @@ describe('useBillingSdkStore subscription commands', () => { httpStatus: 404 } as const + const QUOTE = { + allowed: true, + cost_next_period_cents: 2000, + cost_today_cents: 1500, + credits_next_period_cents: 2000, + credits_today_cents: 1500, + effective_at: '2026-10-01T00:00:00.000Z', + is_immediate: true, + new_plan: { + credits_cents: 2000, + duration: 'MONTHLY', + price_cents: 2000, + seat_summary: { + seat_count: 1, + total_cost_cents: 2000, + total_credits_cents: 2000 + }, + slug: 'pro-monthly', + tier: 'PRO' + }, + transition_type: 'upgrade' + } as const + it('refreshes what the poller refreshed after a cancel settles', async () => { vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( SETTLED @@ -442,13 +466,127 @@ describe('useBillingSdkStore subscription commands', () => { await expect( store.openPaymentPortal('https://app.example/') ).resolves.toEqual({ status: 'unavailable' }) + await expect(store.subscribe({ plan_slug: 'pro-yearly' })).resolves.toEqual( + { status: 'unavailable' } + ) + await expect( + store.previewSubscribe({ planSlug: 'pro-yearly' }) + ).resolves.toEqual({ status: 'unavailable' }) expect(harness.sdk.commands.cancelSubscription).toHaveBeenCalledOnce() expect(harness.sdk.commands.resubscribe).not.toHaveBeenCalled() expect(harness.sdk.commands.openPaymentPortal).not.toHaveBeenCalled() + expect(harness.sdk.commands.subscribe).not.toHaveBeenCalled() + expect(harness.sdk.commands.previewSubscribe).not.toHaveBeenCalled() + expect(mockFetchStatus).not.toHaveBeenCalled() + }) + + it('reconciles the subscription after a plan change settles', async () => { + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue(SETTLED) + + await expect( + useBillingSdkStore().subscribe({ plan_slug: 'pro-yearly' }) + ).resolves.toEqual({ + status: 'ok', + value: { + billing_op_id: 'op-1', + status: 'subscribed', + requiredPayment: true + } + }) + expect(harness.sdk.commands.subscribe).toHaveBeenCalledWith({ + plan_slug: 'pro-yearly' + }) + expect(mockReconcileSubscription).toHaveBeenCalledOnce() + expect(mockCapabilitiesRefresh).toHaveBeenCalledOnce() + }) + + it('hands back the quote without refreshing anything', async () => { + vi.mocked(harness.sdk.commands.previewSubscribe).mockResolvedValue({ + status: 'ok', + value: QUOTE + }) + + await expect( + useBillingSdkStore().previewSubscribe({ planSlug: 'pro-yearly' }) + ).resolves.toEqual({ status: 'ok', value: QUOTE }) + expect(mockReconcileSubscription).not.toHaveBeenCalled() expect(mockFetchStatus).not.toHaveBeenCalled() }) + it('warns once and keeps a blocked payment page reachable however long it polls', () => { + const openPage = vi.spyOn(window, 'open').mockReturnValue(null) + const store = useBillingSdkStore() + const toasts = useToastStore() + + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/op-1' }) + ) + harness.publish( + pendingSubscription({ + actionUrl: 'https://pay.example/op-1', + customerActionSeen: true + }) + ) + harness.publish( + pendingSubscription({ + actionUrl: 'https://pay.example/op-1', + customerActionSeen: true, + authenticationState: 'requires_action' + }) + ) + + expect(openPage).toHaveBeenCalledExactlyOnceWith( + 'https://pay.example/op-1', + '_blank' + ) + expect(toasts.messagesToAdd).toEqual([ + expect.objectContaining({ severity: 'warn' }) + ]) + expect(store.subscriptionActionUrl).toBe('https://pay.example/op-1') + }) + + it('offers the next hosted page the same subscribe moves to', () => { + const openPage = vi.spyOn(window, 'open').mockReturnValue(null) + const store = useBillingSdkStore() + + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/first' }) + ) + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/second' }) + ) + + expect(openPage).toHaveBeenCalledTimes(2) + expect(store.subscriptionActionUrl).toBe('https://pay.example/second') + }) + + it('offers nothing once the subscribe has settled', () => { + vi.spyOn(window, 'open').mockReturnValue(null) + const store = useBillingSdkStore() + + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/op-1' }) + ) + harness.publish(settledOperation('succeeded', 'subscription')) + + expect(store.subscriptionActionUrl).toBeNull() + }) + + it('drives the in-page challenge a subscribe raises, as it does for a top-up', async () => { + useBillingSdkStore() + + harness.publish( + pendingSubscription({ + presentation: 'embedded', + challenge: { clientSecret: 'cs_1', status: 'required' } + }) + ) + await nextTick() + + expect(harness.sdk.driveChallenge).toHaveBeenCalledExactlyOnceWith('op-1') + }) + it('hands back the portal URL without refreshing anything', async () => { vi.mocked(harness.sdk.commands.openPaymentPortal).mockResolvedValue({ status: 'ok', diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index bea9ee91618..a6e9147832f 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -10,7 +10,8 @@ import type { BillingOperationTelemetryEvent, EmbeddedChallengePort, PendingBillingOperation, - SubscriptionCommandResult + PreviewSubscribeInput, + SubscribeInput } from '@comfyorg/account-core/billing' import { BILLING_OPERATION_TELEMETRY_EVENT } from '@comfyorg/account-core/billing' import { loadStripe } from '@stripe/stripe-js/pure' @@ -25,7 +26,11 @@ import { isCloud } from '@/platform/distribution/types' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' import { useTelemetry } from '@/platform/telemetry' import { useToastStore } from '@/platform/updates/common/toastStore' -import type { CreateTopupResponse } from '@/platform/workspace/api/workspaceApi' +import type { + CreateTopupResponse, + PreviewSubscribeResponse, + SubscribeResponse +} from '@/platform/workspace/api/workspaceApi' import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl' import { needsCustomerAttention } from '@/platform/workspace/billing/customerAttention' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' @@ -37,6 +42,8 @@ import { createBillingSdk } from './createBillingSdk' import type { SubscriptionRailOutcome } from './subscriptionOperationView' import { projectPaymentPortalResult, + projectPreviewSubscribeResult, + projectSubscribeResult, projectSubscriptionResult } from './subscriptionOperationView' import { @@ -69,6 +76,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { const dismissed = shallowRef>(new Set()) const resumedOperations = new Set() const drivenChallenges = new Set() + const offeredActions = new Map() const progressToasts = new Map< string, { kind: ProgressKind; message: ToastMessage } @@ -90,6 +98,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { sdk.lifecycle.subscribe((state) => { operations.value = sdk.lifecycle.getSnapshot() if (state.kind === 'topup') onTopupChanged(state) + else onSubscriptionChanged(state) }) const wake = () => { @@ -114,6 +123,15 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { topupViews.value.find(needsCustomerAttention) ) + const subscriptionActionUrl = computed( + () => + operations.value.flatMap((state) => + state.kind === 'subscription' && state.phase === 'pending' + ? (state.actionUrl ?? []) + : [] + )[0] ?? null + ) + // A top-up the dialog issued is reported by the dialog, exactly as before; // the lifecycle's events stand in for the poller's only on an operation // this tab reattached to. A cancel or resubscribe has no such second @@ -175,6 +193,33 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { progressToasts.delete(operationId) } + // A subscribe the SDK settles has no dialog watching it, so the two customer + // steps the checkout performs for the legacy response — driving the in-page + // challenge and opening the hosted payment page — are performed here, or the + // operation waits on a customer who was never shown anything. + function onSubscriptionChanged(state: BillingOperationState) { + if (state.phase !== 'pending') return + void driveRequiredChallenge(state) + openHostedAction(state) + } + + // One offer per hosted step, not per poll: the open runs off the lifecycle + // rather than a click, so a browser that blocked the first one blocks every + // retry and each retry would repeat the warning. A step the customer still + // owes stays on `subscriptionActionUrl` for the checkout to put behind a + // button of their own. + function openHostedAction(state: PendingBillingOperation) { + const { id, actionUrl } = state + if (actionUrl === undefined || offeredActions.get(id) === actionUrl) return + offeredActions.set(id, actionUrl) + if (window.open(actionUrl, '_blank')) return + toastStore.add({ + severity: 'warn', + summary: t('g.warning'), + detail: t('subscription.preview.paymentPopupBlocked') + }) + } + // One in-page challenge per operation, as the poller drives it: a later // challenge for the same operation waits for the customer's retry. async function driveRequiredChallenge(state: PendingBillingOperation) { @@ -224,13 +269,20 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { // every later action goes straight to the legacy call. let subscriptionRouteAvailable = true - async function runSubscriptionCommand( - command: () => Promise, - refresh: () => Promise - ): Promise { + async function onSubscriptionRoute( + run: () => Promise> + ): Promise> { if (!subscriptionRouteAvailable) return { status: 'unavailable' } - const outcome = projectSubscriptionResult(await command()) + const outcome = await run() if (outcome.status === 'unavailable') subscriptionRouteAvailable = false + return outcome + } + + async function runSubscriptionCommand( + command: () => Promise>, + refresh: () => Promise + ): Promise> { + const outcome = await onSubscriptionRoute(command) if (outcome.status === 'ok') await refresh() return outcome } @@ -246,7 +298,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { ]) } - async function refreshAfterResubscribe(): Promise { + async function refreshAfterSubscriptionChange(): Promise { const billingContext = useBillingContext() await Promise.allSettled([ billingContext.reconcileSubscriptionSuccess(), @@ -256,26 +308,46 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { function cancelSubscription(): Promise { return runSubscriptionCommand( - () => sdk.commands.cancelSubscription(), + async () => + projectSubscriptionResult(await sdk.commands.cancelSubscription()), refreshAfterCancel ) } function resubscribe(): Promise { return runSubscriptionCommand( - () => sdk.commands.resubscribe(), - refreshAfterResubscribe + async () => projectSubscriptionResult(await sdk.commands.resubscribe()), + refreshAfterSubscriptionChange + ) + } + + function subscribe( + input: SubscribeInput + ): Promise> { + return runSubscriptionCommand( + async () => projectSubscribeResult(await sdk.commands.subscribe(input)), + refreshAfterSubscriptionChange + ) + } + + // A quote changes nothing, so it refreshes nothing; it shares the route + // latch because the backend gates it with the rest of them. + async function previewSubscribe( + input: PreviewSubscribeInput + ): Promise> { + return onSubscriptionRoute(async () => + projectPreviewSubscribeResult(await sdk.commands.previewSubscribe(input)) ) } async function openPaymentPortal( returnUrl: string ): Promise> { - if (!subscriptionRouteAvailable) return { status: 'unavailable' } - const outcome = projectPaymentPortalResult( - await sdk.commands.openPaymentPortal({ returnUrl }) + const outcome = await onSubscriptionRoute(async () => + projectPaymentPortalResult( + await sdk.commands.openPaymentPortal({ returnUrl }) + ) ) - if (outcome.status === 'unavailable') subscriptionRouteAvailable = false // The portal may add or remove a card and says nothing on the way back, so // handing the URL out is the last moment this tab's list is known good. if (outcome.status === 'ok') sdk.paymentMethods.invalidate() @@ -301,7 +373,10 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { return { isAddingCredits, topupActionOperation, + subscriptionActionUrl, createTopup, + subscribe, + previewSubscribe, cancelSubscription, resubscribe, openPaymentPortal, diff --git a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts index c236ff7572e..9131d5ebdfd 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -59,6 +59,13 @@ export function pendingTopup( } } +/** A subscribe the lifecycle is still driving, for the store's own effects. */ +export function pendingSubscription( + overrides: PendingOverrides = {} +): PendingBillingOperation { + return pendingTopup({ kind: 'subscription', ...overrides }) +} + export function failedTopup( declineReason: BillingDeclineReason = 'card_declined' ): FailedBillingOperation { diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts index bc8b29c3805..1f9a416851e 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts @@ -10,6 +10,7 @@ import { } from './billingSdkTestUtils' import { projectPaymentPortalResult, + projectSubscribeResult, projectSubscriptionResult } from './subscriptionOperationView' @@ -108,6 +109,63 @@ describe('projectSubscriptionResult', () => { }) }) +describe('projectSubscribeResult', () => { + it.for([ + { issuedStatus: 'subscribed', requiredPayment: false }, + { issuedStatus: 'pending_payment', requiredPayment: true }, + { issuedStatus: 'needs_payment_method', requiredPayment: true }, + { issuedStatus: undefined, requiredPayment: true } + ] as const)( + 'reports a subscribe issued as $issuedStatus as subscribed, requiredPayment $requiredPayment', + ({ issuedStatus, requiredPayment }) => { + expect( + projectSubscribeResult({ + status: 'ok', + value: { + phase: 'succeeded', + operation: settledOperation('succeeded', 'subscription'), + ...(issuedStatus === undefined ? {} : { issuedStatus }) + } + }) + ).toEqual({ + status: 'ok', + value: { + billing_op_id: 'op-1', + status: 'subscribed', + requiredPayment + } + }) + } + ) + + it.for([ + { + phase: 'failed', + operation: failedOperation('subscription'), + detail: + 'Your bank declined this payment. Try another payment method or contact your bank.' + }, + { + phase: 'timed_out', + operation: settledOperation('timed_out', 'subscription'), + detail: "We couldn't update your subscription. Please try again." + } + ] as const)( + 'reports a $phase subscribe as a sentence for the customer', + ({ phase, operation, detail }) => { + const outcome = projectSubscribeResult({ + status: 'ok', + value: { phase, operation } + }) + + expect(outcome).toMatchObject({ status: 'error' }) + expect( + outcome.status === 'error' ? outcome.error : undefined + ).toMatchObject({ message: detail, code: phase }) + } + ) +}) + describe('projectPaymentPortalResult', () => { it('hands back the portal URL the host opens', () => { expect( diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts index 208f5586d6e..e759e4ec192 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -9,16 +9,35 @@ */ import type { PaymentPortalResult, + PreviewSubscribeInput, + PreviewSubscribeResult, + SubscribeInput, SubscriptionCommandFailure, SubscriptionCommandOutcome, SubscriptionCommandResult } from '@comfyorg/account-core/billing' import { t } from '@/i18n' +import type { + PreviewSubscribeResponse, + SubscribeResponse +} from '@/platform/workspace/api/workspaceApi' import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { declineDetail } from './topupOperationView' +/** + * A subscribe response as the checkout reads it. `requiredPayment` is set only + * by the SDK rail, where `status` is always the settled `subscribed`: it says + * whether the server had to take a payment from the customer to get there. + * The legacy path leaves it unset — there a `subscribed` response is a plan + * that was already active, and the poller it never started is what drew the + * same line. + */ +export interface SettledSubscribeResponse extends SubscribeResponse { + readonly requiredPayment?: boolean +} + export type SubscriptionRailOutcome = | { readonly status: 'ok'; readonly value: T } | { readonly status: 'error'; readonly error: Error } @@ -26,11 +45,24 @@ export type SubscriptionRailOutcome = | { readonly status: 'unavailable' } /** - * The three subscription actions the host routes through the SDK. Cancel and + * The subscription actions the host routes through the SDK. Cancel and * resubscribe report only whether they settled; the portal hands back the URL - * the host opens. + * the host opens; subscribe and its quote hand back the bodies the checkout + * already reads. */ export interface SubscriptionRail { + /** + * The hosted step a subscribe on this rail is parked on, or null. The rail + * opens it once itself, so this is what the checkout puts behind a button + * when the browser blocked that open. + */ + readonly subscriptionActionUrl: string | null + subscribe: ( + input: SubscribeInput + ) => Promise> + previewSubscribe: ( + input: PreviewSubscribeInput + ) => Promise> cancelSubscription: () => Promise resubscribe: () => Promise openPaymentPortal: ( @@ -109,6 +141,48 @@ export function projectSubscriptionResult( : projectUnsuccessfulSettle(result.value) } +/** + * A settled subscribe as the body `handleSubscribeResponse` already handles. + * The SDK waits for the operation, so by the time this projects there is + * nothing left to poll: the status is always the settled `subscribed`, never + * the response's `needs_payment_method` or `pending_payment`, both of which + * the lifecycle drove to a conclusion first. `issuedStatus` is what the + * server answered before that, so `requiredPayment` keeps the line the legacy + * poller drew: it watched — and so counted and announced — exactly the + * subscribes the server could not activate on the spot. An adopted operation + * carries no issued status and is one the server was still settling, which is + * the same side of that line. + * + * An outcome carries no operation only when the server answered that the + * requested state already held, which subscribe never reaches: the route + * documents no already-held code. + */ +export function projectSubscribeResult( + result: SubscriptionCommandResult +): SubscriptionRailOutcome { + if (result.status === 'error') return projectFailure(result) + const { phase, operation, issuedStatus } = result.value + if (phase !== 'succeeded' || operation === undefined) { + return projectUnsuccessfulSettle(result.value) + } + return { + status: 'ok', + value: { + billing_op_id: operation.id, + status: 'subscribed', + requiredPayment: issuedStatus !== 'subscribed' + } + } +} + +export function projectPreviewSubscribeResult( + result: PreviewSubscribeResult +): SubscriptionRailOutcome { + return result.status === 'error' + ? projectFailure(result) + : { status: 'ok', value: result.value } +} + export function projectPaymentPortalResult( result: PaymentPortalResult ): SubscriptionRailOutcome { diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 4376f0dc8e1..d97288fe225 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(), @@ -132,8 +132,8 @@ vi.mock(import('@/platform/telemetry')) vi.mock(import('@/composables/useFeatureFlags'), () => ({ useFeatureFlags: () => ({ flags: { - get hostedBillingWebEnabled() { - return state.hostedBillingWebEnabled + get hostedBillingDestination() { + return state.hostedBillingDestination } } }) @@ -143,6 +143,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: ` @@ -196,6 +201,20 @@ function renderComponent( }) } +/** + * A blank tab the handler can disown and navigate. happy-dom's own child + * window exposes `opener` read-only and fetches whatever `location` is set to. + */ +function stubHostedTab(): Window { + const tab: Window = Object.create(window) + Object.defineProperty(tab, 'opener', { value: window, writable: true }) + Object.defineProperty(tab, 'location', { + value: { href: 'about:blank' }, + writable: true + }) + return tab +} + describe('CurrentUserPopoverWorkspace', () => { beforeEach(() => { state.isCloud = true @@ -210,7 +229,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') }) @@ -320,6 +339,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') @@ -328,30 +348,33 @@ 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 tab = stubHostedTab() + const open = vi.spyOn(window, 'open').mockReturnValue(tab) 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/', - '_blank', - 'noopener,noreferrer' + expect(open).toHaveBeenCalledOnce() + expect(open).toHaveBeenCalledWith('', '_blank') + expect(tab.opener).toBeNull() + expect(tab.location.href).toBe( + 'http://localhost:5174/v1/pricing?product=comfyui&return_to=comfyui_workspace' ) expect(state.showPricingTable).not.toHaveBeenCalled() }) - it('keeps Plans & pricing in-app when the hosted tab is blocked', async () => { + it('falls back to the in-app pricing table 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 + state.hostedBillingDestination = 'billing_web' renderComponent('team') await user.click(screen.getByTestId('plans-pricing-menu-item')) @@ -366,7 +389,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') @@ -623,7 +646,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..6dae24bd068 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' @@ -392,13 +392,22 @@ const handleOpenWorkspaceSettings = () => { emit('close') } +/** + * `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 disowning it by hand + * before it leaves `about:blank`. + */ +const openDisownedTab = (url: URL): boolean => { + const tab = window.open('', '_blank') + if (!tab) return false + tab.opener = null + tab.location.href = url.href + return true +} + 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' || !openDisownedTab(route.url)) { subscriptionDialog.showPricingTable({ reason: 'avatar_menu_plans' }) } emit('close') diff --git a/src/platform/workspace/composables/useDowngradeToPersonal.ts b/src/platform/workspace/composables/useDowngradeToPersonal.ts index fdbd278ea77..8d17be0d706 100644 --- a/src/platform/workspace/composables/useDowngradeToPersonal.ts +++ b/src/platform/workspace/composables/useDowngradeToPersonal.ts @@ -12,10 +12,8 @@ import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { BillingFailure } from '@/platform/telemetry/types' import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' -import type { - PreviewSubscribeResponse, - SubscribeResponse -} from '@/platform/workspace/api/workspaceApi' +import type { PreviewSubscribeResponse } from '@/platform/workspace/api/workspaceApi' +import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' @@ -23,7 +21,7 @@ import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspace export interface DowngradeToPersonalResult { preview: PreviewSubscribeResponse - response: SubscribeResponse + response: SettledSubscribeResponse } export interface DowngradePreview { @@ -285,7 +283,7 @@ export function useDowngradeToPersonal() { cycle: targetCycle, checkout_type: 'change' }) - let response: SubscribeResponse | void + let response: SettledSubscribeResponse | void try { response = await subscribe(planSlug, { returnUrl: `${getComfyPlatformBaseUrl()}/payment/success`, diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index 043933fef97..c9cd8a297ab 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -205,7 +205,8 @@ const { mockCanReactivatePlan, mockCapabilities, mockSubscription, - mockBillingStatus + mockBillingStatus, + mockSubscriptionRail } = vi.hoisted(() => { return { mockSubscribe: vi.fn(), @@ -246,7 +247,10 @@ const { isCancelled: boolean } | null }, - mockBillingStatus: { value: null as BillingStatus | null } + mockBillingStatus: { value: null as BillingStatus | null }, + mockSubscriptionRail: { + value: null as { subscriptionActionUrl: string | null } | null + } } }) @@ -375,6 +379,11 @@ vi.mock(import('@/platform/workspace/api/workspaceApi'), () => ({ } })) +vi.mock( + import('@/platform/workspace/composables/useSubscriptionRail'), + () => ({ useSubscriptionRail: () => mockSubscriptionRail.value }) +) + vi.mock(import('@/config/comfyApi'), () => ({ getComfyPlatformBaseUrl: () => 'https://platform.comfy.org' })) @@ -422,6 +431,9 @@ const i18n = createI18n({ } } }, + billingOperation: { + subscriptionSuccess: 'Subscription updated' + }, toastMessages: { failedToAccessBillingPortal: 'Billing portal unavailable', invalidBillingPortalUrl: 'Invalid billing portal URL' @@ -536,6 +548,7 @@ describe('useSubscriptionCheckout', () => { } mockCanReactivatePlan.value = true mockSubscription.value = null + mockSubscriptionRail.value = null vi.mocked(useTelemetry()?.trackCheckoutJourneyEvent)?.mockClear() sessionStorage.clear() clearCheckoutJourney() @@ -3090,6 +3103,28 @@ describe('useSubscriptionCheckout', () => { }) }) + describe('hosted payment step on the SDK rail', () => { + it('re-offers the hosted page the rail opened for itself', async () => { + mockSubscriptionRail.value = { + subscriptionActionUrl: 'https://pay.example/op-3' + } + + const checkout = await setupWithApprovedPreview() + + expect(checkout.activeCheckoutActionUrl.value).toBe( + 'https://pay.example/op-3' + ) + }) + + it('offers nothing while the rail is parked on no hosted page', async () => { + mockSubscriptionRail.value = { subscriptionActionUrl: null } + + const checkout = await setupWithApprovedPreview() + + expect(checkout.activeCheckoutActionUrl.value).toBeNull() + }) + }) + describe('handleBackToPricing', () => { it('surfaces a subscription operation recovered from billing status', async () => { Object.assign(useBillingOperationStore(), { @@ -3999,6 +4034,58 @@ describe('useSubscriptionCheckout', () => { ).not.toHaveBeenCalled() }) + it('counts the conversion and announces a subscribe the server charged for', async () => { + const checkout = await setupWithApprovedPreview() + checkout.selectedTierKey.value = 'standard' + checkout.selectedBillingCycle.value = 'yearly' + mockSubscribe.mockResolvedValueOnce({ + status: 'subscribed', + billing_op_id: 'op-3', + requiredPayment: true + }) + mockFetchStatus.mockResolvedValueOnce(undefined) + mockFetchBalance.mockResolvedValueOnce(undefined) + + await checkout.handleConfirmTransition() + + expect( + useTelemetry()?.trackMonthlySubscriptionSucceeded + ).toHaveBeenCalledExactlyOnceWith({ + tier: 'standard', + cycle: 'yearly', + checkout_type: 'new', + payment_intent_source: undefined, + billing_op_id: 'op-3' + }) + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'success', + summary: 'Subscription updated' + }) + ) + }) + + it('counts neither for a subscribe the server activated without a payment', async () => { + const checkout = await setupWithApprovedPreview() + checkout.selectedTierKey.value = 'standard' + checkout.selectedBillingCycle.value = 'yearly' + mockSubscribe.mockResolvedValueOnce({ + status: 'subscribed', + billing_op_id: 'op-3', + requiredPayment: false + }) + mockFetchStatus.mockResolvedValueOnce(undefined) + mockFetchBalance.mockResolvedValueOnce(undefined) + + await checkout.handleConfirmTransition() + + expect(checkout.checkoutStep.value).toBe('success') + expect( + useTelemetry()?.trackMonthlySubscriptionSucceeded + ).not.toHaveBeenCalled() + expect(mockToastAdd).not.toHaveBeenCalled() + }) + it('shows error toast on failure', async () => { const checkout = await setupWithApprovedPreview() checkout.selectedTierKey.value = 'standard' diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.ts b/src/platform/workspace/composables/useSubscriptionCheckout.ts index 5d5bb8deb90..ad9590c3643 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.ts @@ -29,11 +29,12 @@ import type { PreviewSubscribeOptions, PreviewSubscribeResponse, SavedPaymentMethod, - SubscribeOptions, - SubscribeResponse + SubscribeOptions } from '@/platform/workspace/api/workspaceApi' import { workspaceApi } from '@/platform/workspace/api/workspaceApi' +import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { useSubscriptionRail } from '@/platform/workspace/composables/useSubscriptionRail' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -200,7 +201,10 @@ export function useSubscriptionCheckout( : undefined }) const activeCheckoutActionUrl = computed( - () => activeCheckoutOperation.value?.actionUrl ?? null + () => + activeCheckoutOperation.value?.actionUrl ?? + useSubscriptionRail()?.subscriptionActionUrl ?? + null ) // The server says whether the operation is parked; the client no longer // guesses. Only awaiting_payment_method offers this recovery — an operation @@ -1365,7 +1369,7 @@ export function useSubscriptionCheckout( } async function handleSubscribeResponse( - response: SubscribeResponse | void, + response: SettledSubscribeResponse | void, context: SubscriptionOutcomeContext, shouldTrackSubscriptionSuccess = true, // 0 when the caller holds no lock; a release from a non-holder is a no-op. @@ -1384,11 +1388,11 @@ export function useSubscriptionCheckout( const durationMs = Date.now() - context.attemptStartedAt // PostHog implements both trackBillingEvent and // trackMonthlySubscriptionSucceeded (PostHogTelemetryProvider.ts:405, - // :444), so also calling the legacy event here would double-count this - // success for it. billingOperationStore.ts's own success handler - // already restores trackMonthlySubscriptionSucceeded for the - // providers that need it (Mixpanel, GTM); this call site doesn't need - // a second one. + // :444), so calling the legacy event for a plan the server activated + // on the spot would double-count that success for it. Only a subscribe + // the server charged for reaches the legacy event below, which is the + // set billingOperationStore.ts's success handler counts for the + // providers that need it (Mixpanel, GTM) on the legacy path. telemetry?.trackBillingEvent({ operation: 'subscription_checkout', stage: 'succeeded', @@ -1412,6 +1416,24 @@ export function useSubscriptionCheckout( billing_op_id: response.billing_op_id, duration_ms: durationMs }) + if (response.requiredPayment) { + telemetry?.trackMonthlySubscriptionSucceeded({ + tier: context.tier, + cycle: context.cycle, + checkout_type: context.checkoutType, + payment_intent_source: paymentIntentSource, + billing_op_id: response.billing_op_id + }) + } + } + // The poller announced every subscription operation it settled, whatever + // the caller was tracking; on this rail there is no poller to do it. + if (response.requiredPayment) { + toast.add({ + severity: 'success', + summary: t('billingOperation.subscriptionSuccess'), + life: 5000 + }) } checkoutStep.value = 'success' return diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index de1f763a83b..e907b72bf3b 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -2,13 +2,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope } from 'vue' import type { BillingTelemetryEvent } from '@/platform/telemetry/types' -import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' +import type { + BillingStatusResponse, + PreviewSubscribeResponse +} from '@/platform/workspace/api/workspaceApi' import { WorkspaceApiError, workspaceApi } from '@/platform/workspace/api/workspaceApi' import { fakeBillingSdk, + serverCode, settledOperation } from '@/platform/workspace/billing/sdk/billingSdkTestUtils' import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingSdk' @@ -95,6 +99,37 @@ const SETTLED = { value: { phase: 'succeeded', operation: settledOperation('succeeded') } } as const +const PLAN_INFO = { + credits_cents: 2000, + duration: 'MONTHLY', + price_cents: 2000, + seat_summary: { + seat_count: 1, + total_cost_cents: 2000, + total_credits_cents: 2000 + }, + slug: 'pro-monthly', + tier: 'PRO' +} as const + +const LEGACY_QUOTE: PreviewSubscribeResponse = { + allowed: true, + cost_next_period_cents: 2000, + cost_today_cents: 1500, + credits_next_period_cents: 2000, + credits_today_cents: 1500, + effective_at: '2026-10-01T00:00:00.000Z', + is_immediate: true, + new_plan: PLAN_INFO, + transition_type: 'upgrade' +} + +const SDK_QUOTE: PreviewSubscribeResponse = { + ...LEGACY_QUOTE, + cost_today_cents: 900, + transition_type: 'downgrade' +} + let harness: ReturnType function setupBilling() { @@ -125,7 +160,13 @@ beforeEach(() => { vi.spyOn(workspaceApi, 'getPaymentPortalUrl').mockResolvedValue({ url: 'https://portal.legacy.example/session' }) - vi.spyOn(window, 'open').mockReturnValue(null) + vi.spyOn(workspaceApi, 'subscribe').mockResolvedValue({ + billing_op_id: 'op-legacy', + status: 'subscribed' + }) + vi.spyOn(workspaceApi, 'previewSubscribe').mockResolvedValue(LEGACY_QUOTE) + // A tab that opens, so these routing tests are not all reading as blocked. + vi.spyOn(window, 'open').mockReturnValue(window) vi.mocked(useBillingOperationStore().startOperation).mockResolvedValue({ status: 'succeeded' } as never) @@ -292,6 +333,161 @@ describe('resubscribe on the billing SDK rail', () => { }) }) +describe('subscribe on the billing SDK rail', () => { + it('issues through the workspace client while the rail is off', async () => { + await setupBilling().subscribe('pro-yearly', { promotionCode: 'LAUNCH' }) + + expect(workspaceApi.subscribe).toHaveBeenCalledWith('pro-yearly', { + promotionCode: 'LAUNCH' + }) + expect(mockCreateBillingSdk).not.toHaveBeenCalled() + }) + + it('maps the host options onto the generated request body', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue(SETTLED) + + const response = await setupBilling().subscribe('pro-yearly', { + confirmationToken: '', + savedPaymentMethodId: 'pm_123', + promotionCode: 'LAUNCH', + quoteId: 'quote-1', + quoteVersion: 3, + returnUrl: 'https://app.example/success', + cancelUrl: 'https://app.example/failed', + teamCreditStopId: 'stop-1', + billingCycle: 'yearly', + confirmReactivation: true, + prorationAt: '2026-10-01T00:00:00.000Z' + }) + + expect(harness.sdk.commands.subscribe).toHaveBeenCalledWith({ + plan_slug: 'pro-yearly', + confirmation_token: undefined, + saved_payment_method_id: 'pm_123', + promotion_code: 'LAUNCH', + quote_id: 'quote-1', + quote_version: 3, + return_url: 'https://app.example/success', + cancel_url: 'https://app.example/failed', + team_credit_stop_id: 'stop-1', + billing_cycle: 'yearly', + confirm_reactivation: true, + proration_at: '2026-10-01T00:00:00.000Z' + }) + expect(response).toEqual({ + billing_op_id: 'op-1', + status: 'subscribed', + requiredPayment: true + }) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) + + it('falls back to the workspace client once when the route is missing', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue(ROUTE_MISSING) + const billing = setupBilling() + + await billing.subscribe('pro-monthly') + await billing.subscribe('pro-monthly') + + expect(harness.sdk.commands.subscribe).toHaveBeenCalledOnce() + expect(workspaceApi.subscribe).toHaveBeenCalledTimes(2) + }) + + it('surfaces a reactivation block under the code the checkout branches on', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ + status: 'error', + code: 'REACTIVATION_CONFIRMATION_REQUIRED' + }) + + await expect(setupBilling().subscribe('pro-monthly')).rejects.toMatchObject( + { code: 'REACTIVATION_CONFIRMATION_REQUIRED' } + ) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) + + it('surfaces a refused transition under the server code', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ + status: 'error', + code: 'CONFLICT', + httpStatus: 409, + serverCode: serverCode('TRANSITION_NOT_ALLOWED') + }) + + await expect(setupBilling().subscribe('pro-monthly')).rejects.toMatchObject( + { code: 'TRANSITION_NOT_ALLOWED', status: 409 } + ) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) + + it('reports an operation that never settled as a failure', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ + status: 'ok', + value: { + phase: 'timed_out', + operation: settledOperation('timed_out', 'subscription') + } + }) + + await expect(setupBilling().subscribe('pro-monthly')).rejects.toMatchObject( + { + message: "We couldn't update your subscription. Please try again.", + code: 'timed_out' + } + ) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) +}) + +describe('preview subscribe on the billing SDK rail', () => { + it('quotes through the workspace client while the rail is off', async () => { + const quote = await setupBilling().previewSubscribe('pro-yearly', { + teamCreditStopId: 'stop-1' + }) + + expect(workspaceApi.previewSubscribe).toHaveBeenCalledWith('pro-yearly', { + teamCreditStopId: 'stop-1' + }) + expect(quote).toEqual(LEGACY_QUOTE) + }) + + it('quotes through the SDK command while the rail is on', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.previewSubscribe).mockResolvedValue({ + status: 'ok', + value: SDK_QUOTE + }) + + const quote = await setupBilling().previewSubscribe('pro-yearly', { + teamCreditStopId: 'stop-1', + promotionCode: 'LAUNCH' + }) + + expect(harness.sdk.commands.previewSubscribe).toHaveBeenCalledWith({ + planSlug: 'pro-yearly', + teamCreditStopId: 'stop-1', + promotionCode: 'LAUNCH' + }) + expect(quote).toEqual(SDK_QUOTE) + expect(workspaceApi.previewSubscribe).not.toHaveBeenCalled() + }) + + it('falls back to the workspace client when the route is missing', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.previewSubscribe).mockResolvedValue( + ROUTE_MISSING + ) + + const quote = await setupBilling().previewSubscribe('pro-yearly') + + expect(quote).toEqual(LEGACY_QUOTE) + }) +}) + describe('payment portal on the billing SDK rail', () => { it('opens the workspace client URL while the rail is off', async () => { await setupBilling().manageSubscription() diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 64abb06bb4e..e42757ed169 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,132 @@ 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.for([ + ['the legacy client', false, 'https://billing.example/portal'], + ['the SDK rail', true, 'https://billing.example/sdk-portal'] + ] as const)( + 'attempts %s when the hosted tab is blocked', + async ([, railEnabled, fallbackUrl]) => { + const openSpy = vi.fn(() => null) + 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 + mockRail.openPaymentPortal.mockResolvedValue({ + status: 'ok', + value: 'https://billing.example/sdk-portal' + }) + mockWorkspaceApi.getPaymentPortalUrl.mockResolvedValue({ + url: 'https://billing.example/portal' + }) + + const billing = setupBilling() + await billing.manageSubscription() + + expect(openSpy).toHaveBeenCalledWith( + 'https://billing.comfy.org/v1/payment-methods?product=comfyui&return_to=comfyui_workspace', + '_blank' + ) + expect(openSpy).toHaveBeenCalledWith(fallbackUrl, '_blank') + } + ) + + it('reaches the legacy portal when the hosted tab and the rail are both blocked', async () => { + const openSpy = vi.fn(() => null) + vi.stubGlobal('open', openSpy) + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + localStorage.setItem('ff:hosted_billing_destination', '"billing_web"') + mockRail.enabled = true + mockRail.openPaymentPortal.mockResolvedValue({ + status: 'ok', + value: 'https://billing.example/sdk-portal' + }) + mockWorkspaceApi.getPaymentPortalUrl.mockResolvedValue({ + url: 'https://billing.example/portal' + }) + + const billing = setupBilling() + await billing.manageSubscription() + + expect(mockWorkspaceApi.getPaymentPortalUrl).toHaveBeenCalledTimes(1) + expect(openSpy).toHaveBeenLastCalledWith( + 'https://billing.example/portal', + '_blank' + ) + }) + + 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 68ec60aad04..9910623370c 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -7,6 +7,11 @@ import { watch } from 'vue' +import type { + PreviewSubscribeInput, + SubscribeInput +} from '@comfyorg/account-core/billing' + import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useBillingPlans } from '@/platform/cloud/subscription/composables/useBillingPlans' import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' @@ -20,15 +25,18 @@ import type { CreateTopupResponse, PreviewSubscribeOptions, PreviewSubscribeResponse, - SubscribeOptions, - SubscribeResponse + SubscribeOptions } from '@/platform/workspace/api/workspaceApi' 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 type { + SettledSubscribeResponse, + SubscriptionRailOutcome +} from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useSubscriptionRail } from '@/platform/workspace/composables/useSubscriptionRail' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' @@ -115,6 +123,51 @@ async function resyncQuietly(refresh: () => Promise): Promise { /** The SDK rail refusing an action, distinct from any value it could return. */ const DECLINED = Symbol('subscription rail declined') +/** + * The host's options as the generated request body, field for field, including + * the two the workspace client drops when they arrive empty: JSON keeps `''`, + * so an empty credential would reach the server as present but meaningless. + * + * `SubscribeOptions` carries nothing the generated body lacks. `SubscribeInput` + * also has `checkout_attempt_id` and `idempotency_key`, which no host caller + * sets: the SDK mints the key itself, and the checkout attempt is carried on + * the quote rather than the subscribe. + */ +function subscribeInputFrom( + planSlug: string, + options: SubscribeOptions = {} +): SubscribeInput { + return { + plan_slug: planSlug, + confirmation_token: options.confirmationToken || undefined, + saved_payment_method_id: options.savedPaymentMethodId || undefined, + promotion_code: options.promotionCode, + quote_id: options.quoteId, + quote_version: options.quoteVersion, + return_url: options.returnUrl, + cancel_url: options.cancelUrl, + team_credit_stop_id: options.teamCreditStopId, + billing_cycle: options.billingCycle, + confirm_reactivation: options.confirmReactivation, + proration_at: options.prorationAt + } +} + +function previewSubscribeInputFrom( + planSlug: string, + options: PreviewSubscribeOptions = {} +): PreviewSubscribeInput { + return { + planSlug, + ...(options.promotionCode === undefined + ? {} + : { promotionCode: options.promotionCode }), + ...(options.teamCreditStopId === undefined + ? {} + : { teamCreditStopId: options.teamCreditStopId }) + } +} + interface SeatCapacity { maxSeats: number occupiedSeats: number @@ -371,7 +424,17 @@ export function useWorkspaceBilling(): BillingState & BillingActions { async function subscribe( planSlug: string, options?: SubscribeOptions - ): Promise { + ): Promise { + const rail = useSubscriptionRail() + if (rail) { + const response = await onSubscriptionRail(() => + rail.subscribe(subscribeInputFrom(planSlug, options)) + ) + // The SDK waited for the operation, so the refresh the legacy path fires + // and forgets has already run on the rail. + if (response !== DECLINED) return response + } + isLoading.value = true error.value = null try { @@ -390,6 +453,14 @@ export function useWorkspaceBilling(): BillingState & BillingActions { planSlug: string, options?: PreviewSubscribeOptions ): Promise { + const rail = useSubscriptionRail() + if (rail) { + const quote = await onSubscriptionRail(() => + rail.previewSubscribe(previewSubscribeInputFrom(planSlug, options)) + ) + if (quote !== DECLINED) return quote + } + isLoading.value = true error.value = null try { @@ -464,21 +535,34 @@ export function useWorkspaceBilling(): BillingState & BillingActions { } } - function openPortalWindow(url: string): void { + function openPortalWindow(url: string): boolean { + // 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() + if (!portalWindow) return false + refreshOnPortalReturn() + return true } + // 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 + if (openPortalWindow(hosted.url.href)) return + } + const rail = useSubscriptionRail() if (rail) { const url = await onSubscriptionRail(() => rail.openPaymentPortal(window.location.href) ) - if (url !== DECLINED) { - openPortalWindow(url) - return - } + if (url !== DECLINED && openPortalWindow(url)) return } isLoading.value = true