diff --git a/browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts b/browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts new file mode 100644 index 00000000000..5df1553e047 --- /dev/null +++ b/browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts @@ -0,0 +1,214 @@ +import { expect } from '@playwright/test' +import type { Page, Request } from '@playwright/test' + +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' + +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { CancelSubscriptionDialog } from '@e2e/fixtures/components/CancelSubscriptionDialog' +import { createBillingCapabilities } 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' + +/** + * Cancel subscription across the billing SDK rail — FE-2216. + * + * Both rails POST the same route, so the recorded request is what separates + * them: only the SDK transport sends an `Idempotency-Key` header. Drives a raw + * `page` so the cloud app boots against fully mocked endpoints, the same + * pattern as billingFacadeConsumers.spec.ts. + */ +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' + +const SUBSCRIPTION_STATUS: BillingStatusResponse = { + is_active: true, + has_funds: true, + subscription_status: 'active', + subscription_tier: 'PRO', + subscription_duration: 'MONTHLY', + billing_status: 'paid', + max_seats: 1, + occupied_seats: 1, + team_credit_stop: null, + scheduled_change: null, + plan_slug: 'pro-monthly', + renewal_date: '2099-02-20T10:00:00Z' +} + +interface CancelRoute { + /** Every POST the app made to the cancel route, in order. */ + readonly requests: Request[] + /** Answers the next POST with a 404, as a backend whose gate is closed does. */ + respondNotFound: () => void +} + +async function mockCloudBoot(page: Page): Promise { + const requests: Request[] = [] + let notFound = false + + await page.route('**/api/features', (r) => + r.fulfill(jsonRoute({ unified_cloud_auth: true })) + ) + 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 clicks on the dialog. + 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(SUBSCRIPTION_STATUS)) + ) + await page.route('**/api/billing/balance', (r) => + r.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) + ) + await page.route('**/api/billing/plans', (r) => + r.fulfill(jsonRoute({ plans: [] })) + ) + await page.route('**/api/billing/capabilities', (r) => + r.fulfill( + jsonRoute(createBillingCapabilities('ws-personal', { can_cancel: true })) + ) + ) + await page.route('**/customers/balance', (r) => + r.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) + ) + + await page.route('**/api/billing/subscription/cancel', async (r) => { + requests.push(r.request()) + if (notFound) { + notFound = false + await r.fulfill({ status: 404, body: '' }) + return + } + await r.fulfill( + jsonRoute({ billing_op_id: 'op-cancel-1', status: 'pending' }) + ) + }) + // Both rails poll the same operation route; it settles on the first read. + await page.route('**/api/billing/ops/**', (r) => + r.fulfill( + jsonRoute({ + id: 'op-cancel-1', + status: 'succeeded', + started_at: '2026-01-01T00:00:00Z', + completed_at: '2026-01-01T00:00:05Z' + }) + ) + ) + + return { + requests, + respondNotFound: () => { + notFound = true + } + } +} + +async function bootApp(page: Page) { + await new CloudAuthHelper(page).mockAuth() + await page.addInitScript(() => { + localStorage.setItem('Comfy.userId', 'test-user-e2e') + }) + await page.goto(APP_URL) + await page.waitForFunction(() => !!window.app?.extensionManager, null, { + timeout: 45_000 + }) +} + +/** The SDK transport sends this header; the legacy axios client never does. */ +function idempotencyKey(request: Request): string | undefined { + return request.headers()['idempotency-key'] +} + +test.describe('Cancel subscription rail (FE-2216)', { tag: '@cloud' }, () => { + test('keeps the legacy call while the SDK rail is off', async ({ page }) => { + test.setTimeout(60_000) + const cancelRoute = await mockCloudBoot(page) + await bootApp(page) + + const dialog = new CancelSubscriptionDialog(page) + await dialog.open('2099-12-31T12:00:00Z') + await dialog.confirmCancelButton.click() + + await expect(dialog.root).toBeHidden() + expect(cancelRoute.requests).toHaveLength(1) + expect(cancelRoute.requests[0].method()).toBe('POST') + expect(idempotencyKey(cancelRoute.requests[0])).toBeUndefined() + }) + + test('issues through the SDK transport while the rail is on', async ({ + page + }) => { + test.setTimeout(60_000) + const cancelRoute = await mockCloudBoot(page) + await bootApp(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + billing_sdk_subscription_enabled: true + }) + + const dialog = new CancelSubscriptionDialog(page) + await dialog.open('2099-12-31T12:00:00Z') + await dialog.confirmCancelButton.click() + + await expect(dialog.root).toBeHidden() + expect(cancelRoute.requests).toHaveLength(1) + const [issued] = cancelRoute.requests + expect(issued.method()).toBe('POST') + expect(idempotencyKey(issued)).toBeTruthy() + expect(issued.postDataJSON()).toMatchObject({ + idempotency_key: idempotencyKey(issued) + }) + }) + + test('falls back to the legacy call when the SDK route answers 404', async ({ + page + }) => { + test.setTimeout(60_000) + const cancelRoute = await mockCloudBoot(page) + await bootApp(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + billing_sdk_subscription_enabled: true + }) + cancelRoute.respondNotFound() + + const dialog = new CancelSubscriptionDialog(page) + await dialog.open('2099-12-31T12:00:00Z') + await dialog.confirmCancelButton.click() + + await expect(dialog.root).toBeHidden() + await expect.poll(() => cancelRoute.requests.length).toBe(2) + const [sdkAttempt, legacyAttempt] = cancelRoute.requests + expect(idempotencyKey(sdkAttempt)).toBeTruthy() + expect(idempotencyKey(legacyAttempt)).toBeUndefined() + }) +}) diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index af815393f51..0870aad2fc3 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -43,6 +43,7 @@ export enum ServerFeatureFlag { LEGACY_BILLING_MIGRATION_ENABLED = 'legacy_billing_migration_enabled', EMBEDDED_CHECKOUT_ENABLED = 'embedded_checked_enabled', BILLING_SDK_TOPUP_ENABLED = 'billing_sdk_topup_enabled', + BILLING_SDK_SUBSCRIPTION_ENABLED = 'billing_sdk_subscription_enabled', V1_PAYMENT_RECOVERY = 'v1_payment_recovery', FREE_TIER_JOB_ALLOWANCE_ENABLED = 'free_tier_job_allowance_enabled', CHURNKEY_APP_ID = 'churnkey_app_id', @@ -273,6 +274,14 @@ export function useFeatureFlags() { get billingSdkTopupRailEnabled() { return this.billingSdkTopupEnabled && this.unifiedCloudAuthEnabled }, + get billingSdkSubscriptionEnabled() { + return resolveFailClosedBooleanFlag( + ServerFeatureFlag.BILLING_SDK_SUBSCRIPTION_ENABLED + ) + }, + get billingSdkSubscriptionRailEnabled() { + return this.billingSdkSubscriptionEnabled && this.unifiedCloudAuthEnabled + }, get v1PaymentRecovery() { return resolveAuthGatedFlag( ServerFeatureFlag.V1_PAYMENT_RECOVERY, @@ -372,6 +381,8 @@ export function startFeatureFlagTelemetry() { flags.embeddedCheckoutEnabled, [ServerFeatureFlag.BILLING_SDK_TOPUP_ENABLED]: flags.billingSdkTopupEnabled, + [ServerFeatureFlag.BILLING_SDK_SUBSCRIPTION_ENABLED]: + flags.billingSdkSubscriptionEnabled, [ServerFeatureFlag.V1_PAYMENT_RECOVERY]: flags.v1PaymentRecovery, [ServerFeatureFlag.FREE_TIER_JOB_ALLOWANCE_ENABLED]: flags.freeTierJobAllowanceEnabled, diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 8d344fa5c5d..897b598f526 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, + settledOperation, settledTopup } from './billingSdkTestUtils' import type { HostedBillingDestination } from '@comfyorg/account/billing' @@ -27,10 +28,12 @@ vi.mock(import('./createBillingSdk'), () => ({ const mockFetchStatus = vi.hoisted(() => vi.fn(async () => undefined)) const mockFetchBalance = vi.hoisted(() => vi.fn(async () => undefined)) +const mockReconcileSubscription = vi.hoisted(() => vi.fn(async () => undefined)) vi.mock(import('@/composables/billing/useBillingContext'), () => ({ useBillingContext: () => ({ fetchStatus: mockFetchStatus, - fetchBalance: mockFetchBalance + fetchBalance: mockFetchBalance, + reconcileSubscriptionSuccess: mockReconcileSubscription }) })) @@ -364,4 +367,124 @@ describe('useBillingSdkStore', () => { expect(harness.sdk.lifecycle.wake).toHaveBeenCalledTimes(2) }) + + it('reports a cancel it issued, which no dialog reports on this rail', () => { + useBillingSdkStore() + + options.onTelemetry({ + name: 'billing.operation.succeeded', + billing_op_id: 'op-cancel', + operation_type: 'cancel', + presentation: 'hosted', + resumed: false, + duration_ms: 900 + }) + + expect(mockTrackBillingEvent).toHaveBeenCalledWith({ + operation: 'operation', + operation_type: 'cancel', + billing_op_id: 'op-cancel', + duration_ms: 900, + stage: 'succeeded', + outcome: 'success' + }) + }) +}) + +describe('useBillingSdkStore subscription commands', () => { + const SETTLED = { + status: 'ok', + value: { phase: 'succeeded', operation: settledOperation('succeeded') } + } as const + + const ROUTE_MISSING = { + status: 'error', + code: 'NOT_FOUND', + httpStatus: 404 + } as const + + it('refreshes what the poller refreshed after a cancel settles', async () => { + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( + SETTLED + ) + + await expect(useBillingSdkStore().cancelSubscription()).resolves.toEqual({ + status: 'ok', + value: undefined + }) + expect(mockFetchStatus).toHaveBeenCalledOnce() + expect(mockFetchBalance).toHaveBeenCalledOnce() + expect(mockCapabilitiesRefresh).toHaveBeenCalledOnce() + }) + + it('reconciles the subscription after a resubscribe settles', async () => { + vi.mocked(harness.sdk.commands.resubscribe).mockResolvedValue(SETTLED) + + await expect(useBillingSdkStore().resubscribe()).resolves.toEqual({ + status: 'ok', + value: undefined + }) + expect(mockReconcileSubscription).toHaveBeenCalledOnce() + expect(mockCapabilitiesRefresh).toHaveBeenCalledOnce() + }) + + it('stops sending to a route the backend answered 404, for every action', async () => { + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( + ROUTE_MISSING + ) + const store = useBillingSdkStore() + + await store.cancelSubscription() + await store.cancelSubscription() + await expect(store.resubscribe()).resolves.toEqual({ + status: 'unavailable' + }) + await expect( + store.openPaymentPortal('https://app.example/') + ).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(mockFetchStatus).not.toHaveBeenCalled() + }) + + it('hands back the portal URL without refreshing anything', async () => { + vi.mocked(harness.sdk.commands.openPaymentPortal).mockResolvedValue({ + status: 'ok', + value: { url: 'https://portal.example/session' } + }) + + await expect( + useBillingSdkStore().openPaymentPortal('https://app.example/') + ).resolves.toEqual({ + status: 'ok', + value: 'https://portal.example/session' + }) + expect(harness.sdk.commands.openPaymentPortal).toHaveBeenCalledWith({ + returnUrl: 'https://app.example/' + }) + expect(mockFetchStatus).not.toHaveBeenCalled() + }) + + it('drops the saved cards it holds when it hands the portal URL out', async () => { + vi.mocked(harness.sdk.commands.openPaymentPortal).mockResolvedValue({ + status: 'ok', + value: { url: 'https://portal.example/session' } + }) + + await useBillingSdkStore().openPaymentPortal('https://app.example/') + + expect(harness.sdk.paymentMethods.invalidate).toHaveBeenCalledOnce() + }) + + it('keeps the saved cards it holds when the portal never opened', async () => { + vi.mocked(harness.sdk.commands.openPaymentPortal).mockResolvedValue( + ROUTE_MISSING + ) + + await useBillingSdkStore().openPaymentPortal('https://app.example/') + + expect(harness.sdk.paymentMethods.invalidate).not.toHaveBeenCalled() + }) }) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index c4f591fdcf6..e5cf33729ad 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -9,7 +9,8 @@ import type { BillingOperationState, BillingOperationTelemetryEvent, EmbeddedChallengePort, - PendingBillingOperation + PendingBillingOperation, + SubscriptionCommandResult } from '@comfyorg/account/billing' import { BILLING_OPERATION_TELEMETRY_EVENT } from '@comfyorg/account/billing' import { loadStripe } from '@stripe/stripe-js/pure' @@ -33,6 +34,11 @@ import { useDialogStore } from '@/stores/dialogStore' import { toBillingTelemetryEvent } from './billingSdkTelemetry' import { createBillingSdk } from './createBillingSdk' +import type { SubscriptionRailOutcome } from './subscriptionOperationView' +import { + projectPaymentPortalResult, + projectSubscriptionResult +} from './subscriptionOperationView' import { declineDetail, projectTopupOperation, @@ -110,10 +116,15 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { // 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. + // this tab reattached to. A cancel or resubscribe has no such second + // reporter on this rail — the poller owned both ends of it on the legacy + // one — so the lifecycle's events are the only ones it emits. function reportTelemetry(event: BillingOperationTelemetryEvent) { - if (!event.resumed) return - if (event.name === BILLING_OPERATION_TELEMETRY_EVENT.started) { + if (event.operation_type === 'topup' && !event.resumed) return + if ( + event.resumed && + event.name === BILLING_OPERATION_TELEMETRY_EVENT.started + ) { resumedOperations.add(event.billing_op_id) } useTelemetry()?.trackBillingEvent(toBillingTelemetryEvent(event)) @@ -208,6 +219,69 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { return projectTopupResult(result, amountCents) } + // The backend gate on these routes is independent of the client flag, so a + // 404 means the rail is on too early. One answer settles it for the tab: + // every later action goes straight to the legacy call. + let subscriptionRouteAvailable = true + + async function runSubscriptionCommand( + command: () => Promise, + refresh: () => Promise + ): Promise { + if (!subscriptionRouteAvailable) return { status: 'unavailable' } + const outcome = projectSubscriptionResult(await command()) + if (outcome.status === 'unavailable') subscriptionRouteAvailable = false + if (outcome.status === 'ok') await refresh() + return outcome + } + + // What the poller refreshes when one of its operations succeeds, so the + // panels read the same state whichever rail settled the operation. + async function refreshAfterCancel(): Promise { + const billingContext = useBillingContext() + await Promise.allSettled([ + billingContext.fetchStatus(), + billingContext.fetchBalance(), + useBillingCapabilities().refresh() + ]) + } + + async function refreshAfterResubscribe(): Promise { + const billingContext = useBillingContext() + await Promise.allSettled([ + billingContext.reconcileSubscriptionSuccess(), + useBillingCapabilities().refresh() + ]) + } + + function cancelSubscription(): Promise { + return runSubscriptionCommand( + () => sdk.commands.cancelSubscription(), + refreshAfterCancel + ) + } + + function resubscribe(): Promise { + return runSubscriptionCommand( + () => sdk.commands.resubscribe(), + refreshAfterResubscribe + ) + } + + async function openPaymentPortal( + returnUrl: string + ): Promise> { + if (!subscriptionRouteAvailable) return { status: 'unavailable' } + const outcome = 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() + return outcome + } + function recover() { void sdk.lifecycle.recover() } @@ -228,6 +302,9 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { isAddingCredits, topupActionOperation, createTopup, + cancelSubscription, + resubscribe, + openPaymentPortal, recover, retryPaymentAuthentication, dismissOperation diff --git a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts index 4eb2b6faaf9..f74ad07d69d 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -1,15 +1,23 @@ import type { BillingDeclineReason, BillingOperationIdentity, + BillingOperationKind, BillingOperationLifecycle, BillingOperationState, + BillingServerCode, FailedBillingOperation, PendingBillingOperation } from '@comfyorg/account/billing' +import { readBillingErrorCode } from '@comfyorg/account/billing' import { vi } from 'vitest' import type { BillingSdk } from './createBillingSdk' +/** A server code minted the one sanctioned way, so a test cannot invent one. */ +export function serverCode(code: string): BillingServerCode | undefined { + return readBillingErrorCode({ code, message: 'server text' }) +} + const IDENTITY = { id: 'op-1', kind: 'topup', @@ -36,6 +44,28 @@ export function failedTopup( return { ...IDENTITY, phase: 'failed', declineReason, retryable: true } } +/** A settled subscription-rail operation, for a command result's `operation`. */ +export function settledOperation< + P extends 'succeeded' | 'timed_out' | 'reconciliation_needed' +>( + phase: P, + kind: BillingOperationKind = 'cancel' +): BillingOperationIdentity & { readonly phase: P } { + return { ...IDENTITY, kind, phase } +} + +export function failedOperation( + kind: BillingOperationKind = 'cancel' +): FailedBillingOperation { + return { + ...IDENTITY, + kind, + phase: 'failed', + declineReason: 'generic', + retryable: false + } +} + export function settledTopup< P extends 'succeeded' | 'timed_out' | 'reconciliation_needed' | 'superseded' >(phase: P): BillingOperationIdentity & { readonly phase: P } { @@ -84,6 +114,13 @@ export function fakeBillingSdk() { createTopupCheckout: vi.fn(), createHostedTopupCheckout: vi.fn() }, + commands: { + subscribe: vi.fn(), + previewSubscribe: vi.fn(), + resubscribe: vi.fn(), + cancelSubscription: vi.fn(), + openPaymentPortal: vi.fn() + }, driveChallenge: vi.fn(async () => 'completed' as const), dispose: vi.fn() } diff --git a/src/platform/workspace/billing/sdk/createBillingSdk.ts b/src/platform/workspace/billing/sdk/createBillingSdk.ts index b86a545e8f8..350fb75566b 100644 --- a/src/platform/workspace/billing/sdk/createBillingSdk.ts +++ b/src/platform/workspace/billing/sdk/createBillingSdk.ts @@ -1,11 +1,12 @@ /** * The app's one composition of `@comfyorg/account/billing`: the session-backed - * transport, the readers, the operation lifecycle, and the top-up command, + * transport, the readers, the operation lifecycle, and the payment commands, * wired once over ports the host supplies. Everything browser-bound (storage, * the payment-provider script, the document listeners) stays with the caller; * this module only assembles. */ import type { + BillingCommands, BillingOperationLifecycle, BillingOperationPointerStorage, BillingOperationTelemetryEvent, @@ -21,6 +22,7 @@ import type { TopupCommand } from '@comfyorg/account/billing' import { + createBillingCommands, createBillingOperationLifecycle, createBillingStatusReader, createCapabilitiesReader, @@ -56,6 +58,7 @@ export interface BillingSdk { readonly plans: PlansReader readonly paymentMethods: PaymentMethodsReader readonly topup: TopupCommand + readonly commands: BillingCommands readonly driveChallenge: ( operationId: string ) => Promise @@ -107,6 +110,13 @@ export function createBillingSdk(options: BillingSdkOptions): BillingSdk { capabilities, credits }) + const commands = createBillingCommands({ + transport, + lifecycle, + statusReader: status, + capabilities, + credits + }) return { lifecycle, @@ -116,6 +126,7 @@ export function createBillingSdk(options: BillingSdkOptions): BillingSdk { plans, paymentMethods, topup, + commands, driveChallenge: async (operationId) => driveEmbeddedChallenge( lifecycle, diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts new file mode 100644 index 00000000000..f6923abe515 --- /dev/null +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts @@ -0,0 +1,136 @@ +import type { SubscriptionCommandResult } from '@comfyorg/account/billing' +import { describe, expect, it } from 'vitest' + +import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' + +import { + failedOperation, + serverCode, + settledOperation +} from './billingSdkTestUtils' +import { + projectPaymentPortalResult, + projectSubscriptionResult +} from './subscriptionOperationView' + +describe('projectSubscriptionResult', () => { + it('reports a settled command as done', () => { + const result: SubscriptionCommandResult = { + status: 'ok', + value: { phase: 'succeeded', operation: settledOperation('succeeded') } + } + + expect(projectSubscriptionResult(result)).toEqual({ + status: 'ok', + value: undefined + }) + }) + + it('reports a request the server refused as already satisfied', () => { + expect( + projectSubscriptionResult({ status: 'ok', value: { phase: 'succeeded' } }) + ).toEqual({ status: 'ok', value: undefined }) + }) + + it.for([ + { phase: 'failed', operation: failedOperation(), detail: 'phase: failed' }, + { + phase: 'timed_out', + operation: settledOperation('timed_out'), + detail: 'phase: timed_out' + }, + { + phase: 'reconciliation_needed', + operation: settledOperation('reconciliation_needed'), + detail: 'phase: reconciliation_needed' + } + ] as const)( + 'reports a $phase operation as a failure the caller surfaces', + ({ phase, operation, detail }) => { + const outcome = projectSubscriptionResult({ + status: 'ok', + value: { phase, operation } + }) + + expect(outcome).toMatchObject({ status: 'error' }) + expect( + outcome.status === 'error' ? outcome.error.message : undefined + ).toBe(detail) + } + ) + + it('hands a missing route back so the caller keeps its legacy path', () => { + expect( + projectSubscriptionResult({ + status: 'error', + code: 'NOT_FOUND', + httpStatus: 404 + }) + ).toEqual({ status: 'unavailable' }) + }) + + it.for([ + [ + { status: 'error', code: 'REQUEST_FAILED', httpStatus: 503 }, + { status: 503, code: 'REQUEST_FAILED', message: 'REQUEST_FAILED (503)' } + ], + [ + { + status: 'error', + code: 'CONFLICT', + httpStatus: 409, + serverCode: serverCode('SUBSCRIPTION_LOCKED') + }, + { status: 409, code: 'SUBSCRIPTION_LOCKED', message: 'CONFLICT (409)' } + ], + [ + { status: 'error', code: 'SUPERSEDED' }, + { status: undefined, code: 'SUPERSEDED', message: 'SUPERSEDED' } + ] + ] as const)('surfaces %o as a workspace error', ([failure, expected]) => { + const outcome = projectSubscriptionResult(failure) + + expect(outcome.status).toBe('error') + const error = outcome.status === 'error' ? outcome.error : undefined + expect(error).toBeInstanceOf(WorkspaceApiError) + expect(error).toMatchObject(expected) + }) +}) + +describe('projectPaymentPortalResult', () => { + it('hands back the portal URL the host opens', () => { + expect( + projectPaymentPortalResult({ + status: 'ok', + value: { url: 'https://portal.example/session' } + }) + ).toEqual({ status: 'ok', value: 'https://portal.example/session' }) + }) + + it('hands a missing route back so the caller keeps its legacy path', () => { + expect( + projectPaymentPortalResult({ + status: 'error', + code: 'NOT_FOUND', + httpStatus: 404 + }) + ).toEqual({ status: 'unavailable' }) + }) + + it('surfaces a refusal as a workspace error', () => { + const outcome = projectPaymentPortalResult({ + status: 'error', + code: 'ACCESS_DENIED', + httpStatus: 403 + }) + + expect(outcome.status).toBe('error') + expect( + outcome.status === 'error' ? outcome.error : undefined + ).toMatchObject({ + status: 403, + code: 'ACCESS_DENIED', + message: 'ACCESS_DENIED (403)' + }) + }) +}) diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts new file mode 100644 index 00000000000..cd234d5461c --- /dev/null +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -0,0 +1,91 @@ +/** + * Projections from the SDK's subscription results onto what the workspace + * billing adapter already does with the legacy calls: succeed, throw a + * `WorkspaceApiError`, or hand the action back so the legacy call runs. + * + * A 404 is the third case. The backend gate on these routes is independent of + * the client flag, so a rail that is on before the routes are deployed must + * leave the customer on the path that still works. + */ +import type { + PaymentPortalResult, + SubscriptionCommandFailure, + SubscriptionCommandResult +} from '@comfyorg/account/billing' + +import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' + +export type SubscriptionRailOutcome = + | { readonly status: 'ok'; readonly value: T } + | { readonly status: 'error'; readonly error: Error } + /** The route is not deployed here; the caller runs its legacy path. */ + | { readonly status: 'unavailable' } + +/** + * The three 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. + */ +export interface SubscriptionRail { + cancelSubscription: () => Promise + resubscribe: () => Promise + openPaymentPortal: ( + returnUrl: string + ) => Promise> +} + +const UNAVAILABLE = { status: 'unavailable' } as const + +const SETTLED: SubscriptionRailOutcome = { status: 'ok', value: undefined } + +/** + * What the host renders under its own localized summary, so the two lines do + * not repeat each other. The SDK's failures carry no server text, so this is + * the code the command settled on plus the status the server answered with — + * `serverCode` stays out of it, being unbounded in shape and a value to match + * rather than to show. + */ +function describeFailure(code: string, httpStatus: number | undefined): string { + return httpStatus === undefined ? code : `${code} (${httpStatus})` +} + +/** + * The failure as the adapter's own error. `serverCode` lands where the + * adapter already keeps `WorkspaceApiError.code`. + */ +function projectFailure( + failure: SubscriptionCommandFailure +): SubscriptionRailOutcome { + const httpStatus = 'httpStatus' in failure ? failure.httpStatus : undefined + if (httpStatus === 404) return UNAVAILABLE + + const serverCode = 'serverCode' in failure ? failure.serverCode : undefined + return { + status: 'error', + error: new WorkspaceApiError( + describeFailure(failure.code, httpStatus), + httpStatus, + serverCode ?? failure.code + ) + } +} + +/** + * A command that settled anywhere but `succeeded` failed for the customer, + * exactly as a poller operation that ends in any other status does. + */ +export function projectSubscriptionResult( + result: SubscriptionCommandResult +): SubscriptionRailOutcome { + if (result.status === 'error') return projectFailure(result) + return result.value.phase === 'succeeded' + ? SETTLED + : { status: 'error', error: new Error(`phase: ${result.value.phase}`) } +} + +export function projectPaymentPortalResult( + result: PaymentPortalResult +): SubscriptionRailOutcome { + if (result.status === 'error') return projectFailure(result) + return { status: 'ok', value: result.value.url } +} diff --git a/src/platform/workspace/composables/useSubscriptionRail.ts b/src/platform/workspace/composables/useSubscriptionRail.ts new file mode 100644 index 00000000000..bce4464f8d2 --- /dev/null +++ b/src/platform/workspace/composables/useSubscriptionRail.ts @@ -0,0 +1,16 @@ +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { useBillingSdkStore } from '@/platform/workspace/billing/sdk/billingSdkStore' +import type { SubscriptionRail } from '@/platform/workspace/billing/sdk/subscriptionOperationView' + +/** + * Which rail cancel, resubscribe and the payment portal run on. Null is the + * legacy path. + * + * Read once at the start of an action and held for the whole of it, for the + * same reason as `useTopupOperation`: a flag flip mid-flow must not issue on + * one rail and observe the result on the other. + */ +export function useSubscriptionRail(): SubscriptionRail | null { + const { flags } = useFeatureFlags() + return flags.billingSdkSubscriptionRailEnabled ? useBillingSdkStore() : null +} diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts new file mode 100644 index 00000000000..0caa0d10a74 --- /dev/null +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -0,0 +1,285 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { effectScope } from 'vue' + +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' +import { + WorkspaceApiError, + workspaceApi +} from '@/platform/workspace/api/workspaceApi' +import { + fakeBillingSdk, + settledOperation +} from '@/platform/workspace/billing/sdk/billingSdkTestUtils' +import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingSdk' +import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' +import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' + +const flagState = vi.hoisted(() => ({ + billingSdkSubscriptionEnabled: false, + unifiedCloudAuthEnabled: true +})) +vi.mock(import('@/composables/useFeatureFlags'), () => ({ + useFeatureFlags: () => ({ + flags: { + billingSdkTopupRailEnabled: false, + embeddedCheckoutEnabled: false, + get billingSdkSubscriptionRailEnabled() { + return ( + flagState.billingSdkSubscriptionEnabled && + flagState.unifiedCloudAuthEnabled + ) + } + } + }) +})) + +vi.mock(import('@/composables/billing/useBillingContext')) + +vi.mock( + import('@/platform/cloud/subscription/composables/useBillingPlans'), + () => ({ + useBillingPlans: () => ({ + plans: { value: [] }, + currentPlanSlug: { value: null }, + error: { value: null }, + fetchPlans: vi.fn() + }) + }) +) + +vi.mock( + import('@/platform/cloud/subscription/composables/useSubscriptionDialog'), + () => ({ useSubscriptionDialog: () => ({ show: vi.fn() }) }) +) + +vi.mock( + import('@/platform/workspace/composables/useBillingCapabilities'), + () => ({ + useBillingCapabilities: () => ({ refresh: vi.fn(async () => undefined) }) + }) +) + +vi.mock(import('@/platform/telemetry'), () => ({ + useTelemetry: () => ({ trackBillingEvent: vi.fn() }) +})) + +const mockCreateBillingSdk = vi.hoisted(() => vi.fn<() => BillingSdk>()) +vi.mock(import('@/platform/workspace/billing/sdk/createBillingSdk'), () => ({ + createBillingSdk: mockCreateBillingSdk +})) + +const STATUS: BillingStatusResponse = { + is_active: true, + max_seats: 1, + occupied_seats: 1, + has_funds: true, + team_credit_stop: null, + scheduled_change: null, + subscription_status: 'canceled', + subscription_tier: 'CREATOR', + plan_slug: 'creator-monthly' +} + +const ROUTE_MISSING = { + status: 'error', + code: 'NOT_FOUND', + httpStatus: 404 +} as const + +const SETTLED = { + status: 'ok', + value: { phase: 'succeeded', operation: settledOperation('succeeded') } +} as const + +let harness: ReturnType + +function setupBilling() { + const billing = effectScope().run(() => useWorkspaceBilling()) + if (!billing) throw new Error('Failed to create billing composable') + return billing +} + +beforeEach(() => { + harness = fakeBillingSdk() + mockCreateBillingSdk.mockReturnValue(harness.sdk) + flagState.billingSdkSubscriptionEnabled = false + flagState.unifiedCloudAuthEnabled = true + vi.spyOn(workspaceApi, 'getBillingStatus').mockResolvedValue(STATUS) + vi.spyOn(workspaceApi, 'getBillingBalance').mockResolvedValue({ + amount_micros: 0, + currency: 'USD' + }) + vi.spyOn(workspaceApi, 'cancelSubscription').mockResolvedValue({ + billing_op_id: 'op-legacy', + cancel_at: '2099-12-31T12:00:00Z' + }) + vi.spyOn(workspaceApi, 'resubscribe').mockResolvedValue({ + billing_op_id: 'op-legacy', + status: 'active' + }) + vi.spyOn(workspaceApi, 'getPaymentPortalUrl').mockResolvedValue({ + url: 'https://portal.legacy.example/session' + }) + vi.spyOn(window, 'open').mockReturnValue(null) + vi.mocked(useBillingOperationStore().startOperation).mockResolvedValue({ + status: 'succeeded' + } as never) +}) + +describe('cancel subscription on the billing SDK rail', () => { + it('issues through the workspace client while the rail is off', async () => { + await setupBilling().cancelSubscription() + + expect(workspaceApi.cancelSubscription).toHaveBeenCalledOnce() + expect(mockCreateBillingSdk).not.toHaveBeenCalled() + }) + + it('stays on the workspace client while unified auth is off', async () => { + flagState.billingSdkSubscriptionEnabled = true + flagState.unifiedCloudAuthEnabled = false + + await setupBilling().cancelSubscription() + + expect(workspaceApi.cancelSubscription).toHaveBeenCalledOnce() + expect(mockCreateBillingSdk).not.toHaveBeenCalled() + }) + + it('issues through the SDK command while the rail is on', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( + SETTLED + ) + + await setupBilling().cancelSubscription() + + expect(harness.sdk.commands.cancelSubscription).toHaveBeenCalledOnce() + expect(workspaceApi.cancelSubscription).not.toHaveBeenCalled() + }) + + it('falls back to the workspace client once when the route is missing', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( + ROUTE_MISSING + ) + const billing = setupBilling() + + await billing.cancelSubscription() + await billing.cancelSubscription() + + expect(harness.sdk.commands.cancelSubscription).toHaveBeenCalledOnce() + expect(workspaceApi.cancelSubscription).toHaveBeenCalledTimes(2) + }) + + it.for([ + [ + { status: 'error', code: 'REQUEST_FAILED', httpStatus: 500 }, + 'REQUEST_FAILED (500)' + ], + [{ status: 'error', code: 'SUPERSEDED' }, 'SUPERSEDED'] + ] as const)( + 'reports %o as its own detail instead of retrying on legacy', + async ([failure, detail]) => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( + failure + ) + const billing = setupBilling() + + await expect(billing.cancelSubscription()).rejects.toBeInstanceOf( + WorkspaceApiError + ) + expect(billing.error.value).toBe(detail) + expect(workspaceApi.cancelSubscription).not.toHaveBeenCalled() + } + ) + + it('reports an operation that never settled as a failure', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue({ + status: 'ok', + value: { + phase: 'timed_out', + operation: settledOperation('timed_out') + } + }) + + await expect(setupBilling().cancelSubscription()).rejects.toThrow( + 'phase: timed_out' + ) + expect(workspaceApi.cancelSubscription).not.toHaveBeenCalled() + }) +}) + +describe('resubscribe on the billing SDK rail', () => { + it('issues through the workspace client while the rail is off', async () => { + await setupBilling().resubscribe() + + expect(workspaceApi.resubscribe).toHaveBeenCalledOnce() + expect(mockCreateBillingSdk).not.toHaveBeenCalled() + }) + + it('issues through the SDK command while the rail is on', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.resubscribe).mockResolvedValue(SETTLED) + + await setupBilling().resubscribe() + + expect(harness.sdk.commands.resubscribe).toHaveBeenCalledOnce() + expect(workspaceApi.resubscribe).not.toHaveBeenCalled() + }) + + it('falls back to the workspace client when the route is missing', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.resubscribe).mockResolvedValue(ROUTE_MISSING) + + await setupBilling().resubscribe() + + expect(workspaceApi.resubscribe).toHaveBeenCalledOnce() + }) +}) + +describe('payment portal on the billing SDK rail', () => { + it('opens the workspace client URL while the rail is off', async () => { + await setupBilling().manageSubscription() + + expect(workspaceApi.getPaymentPortalUrl).toHaveBeenCalledOnce() + expect(window.open).toHaveBeenCalledWith( + 'https://portal.legacy.example/session', + '_blank' + ) + }) + + it('opens the SDK URL for the current page while the rail is on', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.openPaymentPortal).mockResolvedValue({ + status: 'ok', + value: { url: 'https://portal.sdk.example/session' } + }) + + await setupBilling().manageSubscription() + + expect(harness.sdk.commands.openPaymentPortal).toHaveBeenCalledWith({ + returnUrl: window.location.href + }) + expect(workspaceApi.getPaymentPortalUrl).not.toHaveBeenCalled() + expect(window.open).toHaveBeenCalledWith( + 'https://portal.sdk.example/session', + '_blank' + ) + }) + + it('falls back to the workspace client when the route is missing', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.openPaymentPortal).mockResolvedValue( + ROUTE_MISSING + ) + + await setupBilling().manageSubscription() + + expect(workspaceApi.getPaymentPortalUrl).toHaveBeenCalledOnce() + expect(window.open).toHaveBeenCalledWith( + 'https://portal.legacy.example/session', + '_blank' + ) + }) +}) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 6c0a3159033..605e012a6f1 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -28,7 +28,9 @@ import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { useBillingSdkStore } from '@/platform/workspace/billing/sdk/billingSdkStore' +import type { 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' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -110,6 +112,9 @@ 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') + interface SeatCapacity { maxSeats: number occupiedSeats: number @@ -436,16 +441,52 @@ export function useWorkspaceBilling(): BillingState & BillingActions { }) } + /** + * Runs one action on the SDK rail and reports into this adapter's own + * state. `DECLINED` means the routes are not deployed on this backend, so + * the caller runs its legacy path. + */ + async function onSubscriptionRail( + run: () => Promise> + ): Promise { + isLoading.value = true + error.value = null + try { + const outcome = await run() + if (outcome.status === 'unavailable') return DECLINED + if (outcome.status === 'error') { + error.value = outcome.error.message + throw outcome.error + } + return outcome.value + } finally { + isLoading.value = false + } + } + + function openPortalWindow(url: string): void { + const portalWindow = window.open(url, '_blank') + if (portalWindow) refreshOnPortalReturn() + } + async function manageSubscription(): Promise { + const rail = useSubscriptionRail() + if (rail) { + const url = await onSubscriptionRail(() => + rail.openPaymentPortal(window.location.href) + ) + if (url !== DECLINED) { + openPortalWindow(url) + return + } + } + isLoading.value = true error.value = null try { const returnUrl = window.location.href const response = await workspaceApi.getPaymentPortalUrl(returnUrl) - if (response.url) { - const portalWindow = window.open(response.url, '_blank') - if (portalWindow) refreshOnPortalReturn() - } + if (response.url) openPortalWindow(response.url) } catch (err) { error.value = err instanceof Error ? err.message : 'Failed to open billing portal' @@ -456,6 +497,14 @@ export function useWorkspaceBilling(): BillingState & BillingActions { } async function cancelSubscription(): Promise { + const rail = useSubscriptionRail() + if ( + rail && + (await onSubscriptionRail(() => rail.cancelSubscription())) !== DECLINED + ) { + return + } + isLoading.value = true error.value = null const attemptStartedAt = Date.now() @@ -520,6 +569,14 @@ export function useWorkspaceBilling(): BillingState & BillingActions { // Workspace's resubscribe() call is itself the terminal reactivation, so // the click-time source isn't needed here the way the legacy adapter // needs it for its pending-checkout-recovery terminal event. + const rail = useSubscriptionRail() + if ( + rail && + (await onSubscriptionRail(() => rail.resubscribe())) !== DECLINED + ) { + return + } + isLoading.value = true error.value = null try {