Skip to content
214 changes: 214 additions & 0 deletions browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts
Original file line number Diff line number Diff line change
@@ -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<CancelRoute> {
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()
})
})
11 changes: 11 additions & 0 deletions src/composables/useFeatureFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
125 changes: 124 additions & 1 deletion src/platform/workspace/billing/sdk/billingSdkStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
fakeBillingSdk,
failedTopup,
pendingTopup,
settledOperation,
settledTopup
} from './billingSdkTestUtils'
import type { HostedBillingDestination } from '@comfyorg/account/billing'
Expand All @@ -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<unknown>(import('@/composables/billing/useBillingContext'), () => ({
useBillingContext: () => ({
fetchStatus: mockFetchStatus,
fetchBalance: mockFetchBalance
fetchBalance: mockFetchBalance,
reconcileSubscriptionSuccess: mockReconcileSubscription
})
}))

Expand Down Expand Up @@ -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()
})
})
Loading
Loading