From 0eb9a36510be63f73b4645b2a6d8f5d99eb96ca4 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 14:48:43 -0400 Subject: [PATCH 1/6] feat(billing): the subscription rail switch and the SDK's payment commands (FE-2216) Adds the billing_sdk_subscription_enabled server flag and the rail switch that pairs it with unified cloud auth, and wires createBillingCommands into the app's one SDK composition so the host can reach cancel, resubscribe and the payment portal. --- src/composables/useFeatureFlags.ts | 11 +++++++ .../billing/sdk/billingSdkTestUtils.ts | 30 +++++++++++++++++++ .../workspace/billing/sdk/createBillingSdk.ts | 13 +++++++- 3 files changed, 53 insertions(+), 1 deletion(-) 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/billingSdkTestUtils.ts b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts index 4eb2b6faaf9..2c1c80a3e9f 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -1,6 +1,7 @@ import type { BillingDeclineReason, BillingOperationIdentity, + BillingOperationKind, BillingOperationLifecycle, BillingOperationState, FailedBillingOperation, @@ -36,6 +37,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 +107,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, From 7d107c83c2743169039568c1b69e21a924613f87 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 14:49:11 -0400 Subject: [PATCH 2/6] feat(billing): cancel, resubscribe and the payment portal on the SDK rail (FE-2216) The SDK store gains the three subscription actions, projected onto what the workspace adapter already does with the legacy calls. A 404 means the backend gate is still closed, so that route is handed back once and stays handed back for the tab. The lifecycle now owns telemetry for a cancel or resubscribe, which no dialog reports on this rail. --- .../billing/sdk/billingSdkStore.test.ts | 108 +++++++++++++- .../workspace/billing/sdk/billingSdkStore.ts | 91 +++++++++++- .../billing/sdk/billingSdkTestUtils.ts | 7 + .../sdk/subscriptionOperationView.test.ts | 133 ++++++++++++++++++ .../billing/sdk/subscriptionOperationView.ts | 87 ++++++++++++ .../composables/useSubscriptionRail.ts | 16 +++ 6 files changed, 437 insertions(+), 5 deletions(-) create mode 100644 src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts create mode 100644 src/platform/workspace/billing/sdk/subscriptionOperationView.ts create mode 100644 src/platform/workspace/composables/useSubscriptionRail.ts diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 8d344fa5c5d..8fee3632725 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,107 @@ 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('Failed to cancel subscription') + ).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('Failed to 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('Failed to cancel subscription') + await store.cancelSubscription('Failed to cancel subscription') + await expect(store.resubscribe('Failed to resubscribe')).resolves.toEqual({ + status: 'unavailable' + }) + await expect( + store.openPaymentPortal( + 'https://app.example/', + 'Failed to open billing portal' + ) + ).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/', + 'Failed to open billing portal' + ) + ).resolves.toEqual({ + status: 'ok', + value: 'https://portal.example/session' + }) + expect(harness.sdk.commands.openPaymentPortal).toHaveBeenCalledWith({ + returnUrl: 'https://app.example/' + }) + expect(mockFetchStatus).not.toHaveBeenCalled() + }) }) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index c4f591fdcf6..9702d225e6e 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,75 @@ 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, + failureMessage: string, + refresh: () => Promise + ): Promise { + if (!subscriptionRouteAvailable) return { status: 'unavailable' } + const outcome = projectSubscriptionResult(await command(), failureMessage) + 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( + failureMessage: string + ): Promise { + return runSubscriptionCommand( + () => sdk.commands.cancelSubscription(), + failureMessage, + refreshAfterCancel + ) + } + + function resubscribe( + failureMessage: string + ): Promise { + return runSubscriptionCommand( + () => sdk.commands.resubscribe(), + failureMessage, + refreshAfterResubscribe + ) + } + + async function openPaymentPortal( + returnUrl: string, + failureMessage: string + ): Promise> { + if (!subscriptionRouteAvailable) return { status: 'unavailable' } + const outcome = projectPaymentPortalResult( + await sdk.commands.openPaymentPortal({ returnUrl }), + failureMessage + ) + if (outcome.status === 'unavailable') subscriptionRouteAvailable = false + return outcome + } + function recover() { void sdk.lifecycle.recover() } @@ -228,6 +308,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 2c1c80a3e9f..f74ad07d69d 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -4,13 +4,20 @@ import type { 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', 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..a34bd9c4a74 --- /dev/null +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts @@ -0,0 +1,133 @@ +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' + +const FAILURE_MESSAGE = 'Failed to cancel subscription' + +describe('projectSubscriptionResult', () => { + it('reports a settled command as done', () => { + const result: SubscriptionCommandResult = { + status: 'ok', + value: { phase: 'succeeded', operation: settledOperation('succeeded') } + } + + expect(projectSubscriptionResult(result, FAILURE_MESSAGE)).toEqual({ + status: 'ok', + value: undefined + }) + }) + + it('reports a request the server refused as already satisfied', () => { + expect( + projectSubscriptionResult( + { status: 'ok', value: { phase: 'succeeded' } }, + FAILURE_MESSAGE + ) + ).toEqual({ status: 'ok', value: undefined }) + }) + + it.for([ + { phase: 'failed', operation: failedOperation() }, + { + phase: 'timed_out', + operation: settledOperation('timed_out') + }, + { + phase: 'reconciliation_needed', + operation: settledOperation('reconciliation_needed') + } + ] as const)( + 'reports a $phase operation as a failure the caller surfaces', + ({ phase, operation }) => { + const outcome = projectSubscriptionResult( + { status: 'ok', value: { phase, operation } }, + FAILURE_MESSAGE + ) + + expect(outcome).toMatchObject({ status: 'error' }) + expect( + outcome.status === 'error' ? outcome.error.message : undefined + ).toBe(FAILURE_MESSAGE) + } + ) + + it('hands a missing route back so the caller keeps its legacy path', () => { + expect( + projectSubscriptionResult( + { status: 'error', code: 'NOT_FOUND', httpStatus: 404 }, + FAILURE_MESSAGE + ) + ).toEqual({ status: 'unavailable' }) + }) + + it.for([ + [ + { status: 'error', code: 'REQUEST_FAILED', httpStatus: 503 }, + { status: 503, code: 'REQUEST_FAILED' } + ], + [ + { + status: 'error', + code: 'CONFLICT', + httpStatus: 409, + serverCode: serverCode('SUBSCRIPTION_LOCKED') + }, + { status: 409, code: 'SUBSCRIPTION_LOCKED' } + ], + [ + { status: 'error', code: 'SUPERSEDED' }, + { status: undefined, code: 'SUPERSEDED' } + ] + ] as const)('surfaces %o as a workspace error', ([failure, expected]) => { + const outcome = projectSubscriptionResult(failure, FAILURE_MESSAGE) + + expect(outcome.status).toBe('error') + const error = outcome.status === 'error' ? outcome.error : undefined + expect(error).toBeInstanceOf(WorkspaceApiError) + expect(error).toMatchObject(expected) + expect(error?.message).toBe(FAILURE_MESSAGE) + }) +}) + +describe('projectPaymentPortalResult', () => { + it('hands back the portal URL the host opens', () => { + expect( + projectPaymentPortalResult( + { status: 'ok', value: { url: 'https://portal.example/session' } }, + 'Failed to open billing portal' + ) + ).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 }, + 'Failed to open billing portal' + ) + ).toEqual({ status: 'unavailable' }) + }) + + it('surfaces a refusal as a workspace error', () => { + const outcome = projectPaymentPortalResult( + { status: 'error', code: 'ACCESS_DENIED', httpStatus: 403 }, + 'Failed to open billing portal' + ) + + expect(outcome.status).toBe('error') + expect( + outcome.status === 'error' ? outcome.error : undefined + ).toMatchObject({ status: 403, code: 'ACCESS_DENIED' }) + }) +}) diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts new file mode 100644 index 00000000000..16c3390bf43 --- /dev/null +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -0,0 +1,87 @@ +/** + * 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: ( + failureMessage: string + ) => Promise + resubscribe: (failureMessage: string) => Promise + openPaymentPortal: ( + returnUrl: string, + failureMessage: string + ) => Promise> +} + +const UNAVAILABLE = { status: 'unavailable' } as const + +const SETTLED: SubscriptionRailOutcome = { status: 'ok', value: undefined } + +/** + * The failure as the adapter's own error. The SDK's codes never carry server + * text, so the message is the host's; `serverCode` lands where the adapter + * already keeps `WorkspaceApiError.code`. + */ +function projectFailure( + failure: SubscriptionCommandFailure, + failureMessage: string +): 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( + failureMessage, + 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, + failureMessage: string +): SubscriptionRailOutcome { + if (result.status === 'error') return projectFailure(result, failureMessage) + return result.value.phase === 'succeeded' + ? SETTLED + : { status: 'error', error: new Error(failureMessage) } +} + +export function projectPaymentPortalResult( + result: PaymentPortalResult, + failureMessage: string +): SubscriptionRailOutcome { + if (result.status === 'error') return projectFailure(result, failureMessage) + 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 +} From 7ab36ab2c69dc590d60fdc0276dbb7445fd35c67 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 14:49:38 -0400 Subject: [PATCH 3/6] feat(billing): route the workspace adapter's subscription actions by rail (FE-2216) cancel, resubscribe and manageSubscription read the rail once, before their first await, and hold it for the whole action. With the flag off the legacy bodies run unchanged; a rail that declines an action falls through to them. --- ...eWorkspaceBilling.subscriptionRail.test.ts | 282 ++++++++++++++++++ .../composables/useWorkspaceBilling.ts | 72 ++++- 2 files changed, 350 insertions(+), 4 deletions(-) create mode 100644 src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts 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..bc4d5d42611 --- /dev/null +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -0,0 +1,282 @@ +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([ + ['REQUEST_FAILED', { status: 'error', code: 'REQUEST_FAILED' }], + ['SUPERSEDED', { status: 'error', code: 'SUPERSEDED' }] + ] as const)( + 'reports a %s refusal instead of retrying on legacy', + async ([, failure]) => { + 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('Failed to cancel subscription') + 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( + 'Failed to cancel subscription' + ) + 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..4c1b1a602d3 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,55 @@ 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, + 'Failed to open billing portal' + ) + ) + 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 +500,16 @@ export function useWorkspaceBilling(): BillingState & BillingActions { } async function cancelSubscription(): Promise { + const rail = useSubscriptionRail() + if ( + rail && + (await onSubscriptionRail(() => + rail.cancelSubscription('Failed to cancel subscription') + )) !== DECLINED + ) { + return + } + isLoading.value = true error.value = null const attemptStartedAt = Date.now() @@ -520,6 +574,16 @@ 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('Failed to resubscribe') + )) !== DECLINED + ) { + return + } + isLoading.value = true error.value = null try { From f437d976bd4cb867c628c41b261715a849eadd2d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 14:50:03 -0400 Subject: [PATCH 4/6] test(billing): cover the cancel rail end to end on cloud (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. Covers flag off, flag on, and the 404 that sends the action back to the legacy call. --- .../dialogs/cancelSubscriptionSdkRail.spec.ts | 214 ++++++++++++++++++ 1 file changed, 214 insertions(+) create mode 100644 browser_tests/tests/dialogs/cancelSubscriptionSdkRail.spec.ts 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() + }) +}) From 659194e1e279a135eb32686a9908e77c6463e30f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 15:33:11 -0400 Subject: [PATCH 5/6] fix(billing): give an SDK-rail failure its own detail line (FE-2216) --- .../billing/sdk/billingSdkStore.test.ts | 30 +++---- .../workspace/billing/sdk/billingSdkStore.ts | 19 ++--- .../sdk/subscriptionOperationView.test.ts | 79 ++++++++++--------- .../billing/sdk/subscriptionOperationView.ts | 42 +++++----- ...eWorkspaceBilling.subscriptionRail.test.ts | 15 ++-- .../composables/useWorkspaceBilling.ts | 13 +-- 6 files changed, 94 insertions(+), 104 deletions(-) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 8fee3632725..2cc29a017ab 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -408,9 +408,10 @@ describe('useBillingSdkStore subscription commands', () => { SETTLED ) - await expect( - useBillingSdkStore().cancelSubscription('Failed to cancel subscription') - ).resolves.toEqual({ status: 'ok', value: undefined }) + await expect(useBillingSdkStore().cancelSubscription()).resolves.toEqual({ + status: 'ok', + value: undefined + }) expect(mockFetchStatus).toHaveBeenCalledOnce() expect(mockFetchBalance).toHaveBeenCalledOnce() expect(mockCapabilitiesRefresh).toHaveBeenCalledOnce() @@ -419,9 +420,10 @@ describe('useBillingSdkStore subscription commands', () => { it('reconciles the subscription after a resubscribe settles', async () => { vi.mocked(harness.sdk.commands.resubscribe).mockResolvedValue(SETTLED) - await expect( - useBillingSdkStore().resubscribe('Failed to resubscribe') - ).resolves.toEqual({ status: 'ok', value: undefined }) + await expect(useBillingSdkStore().resubscribe()).resolves.toEqual({ + status: 'ok', + value: undefined + }) expect(mockReconcileSubscription).toHaveBeenCalledOnce() expect(mockCapabilitiesRefresh).toHaveBeenCalledOnce() }) @@ -432,16 +434,13 @@ describe('useBillingSdkStore subscription commands', () => { ) const store = useBillingSdkStore() - await store.cancelSubscription('Failed to cancel subscription') - await store.cancelSubscription('Failed to cancel subscription') - await expect(store.resubscribe('Failed to resubscribe')).resolves.toEqual({ + await store.cancelSubscription() + await store.cancelSubscription() + await expect(store.resubscribe()).resolves.toEqual({ status: 'unavailable' }) await expect( - store.openPaymentPortal( - 'https://app.example/', - 'Failed to open billing portal' - ) + store.openPaymentPortal('https://app.example/') ).resolves.toEqual({ status: 'unavailable' }) expect(harness.sdk.commands.cancelSubscription).toHaveBeenCalledOnce() @@ -457,10 +456,7 @@ describe('useBillingSdkStore subscription commands', () => { }) await expect( - useBillingSdkStore().openPaymentPortal( - 'https://app.example/', - 'Failed to open billing portal' - ) + useBillingSdkStore().openPaymentPortal('https://app.example/') ).resolves.toEqual({ status: 'ok', value: 'https://portal.example/session' diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index 9702d225e6e..56e2a8054bc 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -226,11 +226,10 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { async function runSubscriptionCommand( command: () => Promise, - failureMessage: string, refresh: () => Promise ): Promise { if (!subscriptionRouteAvailable) return { status: 'unavailable' } - const outcome = projectSubscriptionResult(await command(), failureMessage) + const outcome = projectSubscriptionResult(await command()) if (outcome.status === 'unavailable') subscriptionRouteAvailable = false if (outcome.status === 'ok') await refresh() return outcome @@ -255,34 +254,26 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { ]) } - function cancelSubscription( - failureMessage: string - ): Promise { + function cancelSubscription(): Promise { return runSubscriptionCommand( () => sdk.commands.cancelSubscription(), - failureMessage, refreshAfterCancel ) } - function resubscribe( - failureMessage: string - ): Promise { + function resubscribe(): Promise { return runSubscriptionCommand( () => sdk.commands.resubscribe(), - failureMessage, refreshAfterResubscribe ) } async function openPaymentPortal( - returnUrl: string, - failureMessage: string + returnUrl: string ): Promise> { if (!subscriptionRouteAvailable) return { status: 'unavailable' } const outcome = projectPaymentPortalResult( - await sdk.commands.openPaymentPortal({ returnUrl }), - failureMessage + await sdk.commands.openPaymentPortal({ returnUrl }) ) if (outcome.status === 'unavailable') subscriptionRouteAvailable = false return outcome diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts index a34bd9c4a74..f6923abe515 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts @@ -13,8 +13,6 @@ import { projectSubscriptionResult } from './subscriptionOperationView' -const FAILURE_MESSAGE = 'Failed to cancel subscription' - describe('projectSubscriptionResult', () => { it('reports a settled command as done', () => { const result: SubscriptionCommandResult = { @@ -22,7 +20,7 @@ describe('projectSubscriptionResult', () => { value: { phase: 'succeeded', operation: settledOperation('succeeded') } } - expect(projectSubscriptionResult(result, FAILURE_MESSAGE)).toEqual({ + expect(projectSubscriptionResult(result)).toEqual({ status: 'ok', value: undefined }) @@ -30,51 +28,51 @@ describe('projectSubscriptionResult', () => { it('reports a request the server refused as already satisfied', () => { expect( - projectSubscriptionResult( - { status: 'ok', value: { phase: 'succeeded' } }, - FAILURE_MESSAGE - ) + projectSubscriptionResult({ status: 'ok', value: { phase: 'succeeded' } }) ).toEqual({ status: 'ok', value: undefined }) }) it.for([ - { phase: 'failed', operation: failedOperation() }, + { phase: 'failed', operation: failedOperation(), detail: 'phase: failed' }, { phase: 'timed_out', - operation: settledOperation('timed_out') + operation: settledOperation('timed_out'), + detail: 'phase: timed_out' }, { phase: 'reconciliation_needed', - operation: settledOperation('reconciliation_needed') + operation: settledOperation('reconciliation_needed'), + detail: 'phase: reconciliation_needed' } ] as const)( 'reports a $phase operation as a failure the caller surfaces', - ({ phase, operation }) => { - const outcome = projectSubscriptionResult( - { status: 'ok', value: { phase, operation } }, - FAILURE_MESSAGE - ) + ({ 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(FAILURE_MESSAGE) + ).toBe(detail) } ) it('hands a missing route back so the caller keeps its legacy path', () => { expect( - projectSubscriptionResult( - { status: 'error', code: 'NOT_FOUND', httpStatus: 404 }, - FAILURE_MESSAGE - ) + 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' } + { status: 503, code: 'REQUEST_FAILED', message: 'REQUEST_FAILED (503)' } ], [ { @@ -83,51 +81,56 @@ describe('projectSubscriptionResult', () => { httpStatus: 409, serverCode: serverCode('SUBSCRIPTION_LOCKED') }, - { status: 409, code: 'SUBSCRIPTION_LOCKED' } + { status: 409, code: 'SUBSCRIPTION_LOCKED', message: 'CONFLICT (409)' } ], [ { status: 'error', code: 'SUPERSEDED' }, - { status: undefined, code: 'SUPERSEDED' } + { status: undefined, code: 'SUPERSEDED', message: 'SUPERSEDED' } ] ] as const)('surfaces %o as a workspace error', ([failure, expected]) => { - const outcome = projectSubscriptionResult(failure, FAILURE_MESSAGE) + 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) - expect(error?.message).toBe(FAILURE_MESSAGE) }) }) describe('projectPaymentPortalResult', () => { it('hands back the portal URL the host opens', () => { expect( - projectPaymentPortalResult( - { status: 'ok', value: { url: 'https://portal.example/session' } }, - 'Failed to open billing portal' - ) + 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 }, - 'Failed to open billing portal' - ) + 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 }, - 'Failed to open billing portal' - ) + 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' }) + ).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 index 16c3390bf43..cd234d5461c 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -27,13 +27,10 @@ export type SubscriptionRailOutcome = * the host opens. */ export interface SubscriptionRail { - cancelSubscription: ( - failureMessage: string - ) => Promise - resubscribe: (failureMessage: string) => Promise + cancelSubscription: () => Promise + resubscribe: () => Promise openPaymentPortal: ( - returnUrl: string, - failureMessage: string + returnUrl: string ) => Promise> } @@ -42,13 +39,22 @@ const UNAVAILABLE = { status: 'unavailable' } as const const SETTLED: SubscriptionRailOutcome = { status: 'ok', value: undefined } /** - * The failure as the adapter's own error. The SDK's codes never carry server - * text, so the message is the host's; `serverCode` lands where the adapter - * already keeps `WorkspaceApiError.code`. + * 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, - failureMessage: string + failure: SubscriptionCommandFailure ): SubscriptionRailOutcome { const httpStatus = 'httpStatus' in failure ? failure.httpStatus : undefined if (httpStatus === 404) return UNAVAILABLE @@ -57,7 +63,7 @@ function projectFailure( return { status: 'error', error: new WorkspaceApiError( - failureMessage, + describeFailure(failure.code, httpStatus), httpStatus, serverCode ?? failure.code ) @@ -69,19 +75,17 @@ function projectFailure( * exactly as a poller operation that ends in any other status does. */ export function projectSubscriptionResult( - result: SubscriptionCommandResult, - failureMessage: string + result: SubscriptionCommandResult ): SubscriptionRailOutcome { - if (result.status === 'error') return projectFailure(result, failureMessage) + if (result.status === 'error') return projectFailure(result) return result.value.phase === 'succeeded' ? SETTLED - : { status: 'error', error: new Error(failureMessage) } + : { status: 'error', error: new Error(`phase: ${result.value.phase}`) } } export function projectPaymentPortalResult( - result: PaymentPortalResult, - failureMessage: string + result: PaymentPortalResult ): SubscriptionRailOutcome { - if (result.status === 'error') return projectFailure(result, failureMessage) + if (result.status === 'error') return projectFailure(result) return { status: 'ok', value: result.value.url } } diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index bc4d5d42611..0caa0d10a74 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -171,11 +171,14 @@ describe('cancel subscription on the billing SDK rail', () => { }) it.for([ - ['REQUEST_FAILED', { status: 'error', code: 'REQUEST_FAILED' }], - ['SUPERSEDED', { status: 'error', code: 'SUPERSEDED' }] + [ + { status: 'error', code: 'REQUEST_FAILED', httpStatus: 500 }, + 'REQUEST_FAILED (500)' + ], + [{ status: 'error', code: 'SUPERSEDED' }, 'SUPERSEDED'] ] as const)( - 'reports a %s refusal instead of retrying on legacy', - async ([, failure]) => { + '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 @@ -185,7 +188,7 @@ describe('cancel subscription on the billing SDK rail', () => { await expect(billing.cancelSubscription()).rejects.toBeInstanceOf( WorkspaceApiError ) - expect(billing.error.value).toBe('Failed to cancel subscription') + expect(billing.error.value).toBe(detail) expect(workspaceApi.cancelSubscription).not.toHaveBeenCalled() } ) @@ -201,7 +204,7 @@ describe('cancel subscription on the billing SDK rail', () => { }) await expect(setupBilling().cancelSubscription()).rejects.toThrow( - 'Failed to cancel subscription' + 'phase: timed_out' ) expect(workspaceApi.cancelSubscription).not.toHaveBeenCalled() }) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 4c1b1a602d3..605e012a6f1 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -473,10 +473,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { const rail = useSubscriptionRail() if (rail) { const url = await onSubscriptionRail(() => - rail.openPaymentPortal( - window.location.href, - 'Failed to open billing portal' - ) + rail.openPaymentPortal(window.location.href) ) if (url !== DECLINED) { openPortalWindow(url) @@ -503,9 +500,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { const rail = useSubscriptionRail() if ( rail && - (await onSubscriptionRail(() => - rail.cancelSubscription('Failed to cancel subscription') - )) !== DECLINED + (await onSubscriptionRail(() => rail.cancelSubscription())) !== DECLINED ) { return } @@ -577,9 +572,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { const rail = useSubscriptionRail() if ( rail && - (await onSubscriptionRail(() => - rail.resubscribe('Failed to resubscribe') - )) !== DECLINED + (await onSubscriptionRail(() => rail.resubscribe())) !== DECLINED ) { return } From 4dd35a7a36f86ba58226905a4e4b3fda700319aa Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 16:57:19 -0400 Subject: [PATCH 6/6] fix(billing): drop the saved cards the payment portal can change (FE-2216) The payment portal adds or removes a card outside the reader, and nothing tells this tab which. Invalidate the saved-card list when the portal URL is handed out, which is the last moment the list is known good. --- .../billing/sdk/billingSdkStore.test.ts | 21 +++++++++++++++++++ .../workspace/billing/sdk/billingSdkStore.ts | 3 +++ 2 files changed, 24 insertions(+) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 2cc29a017ab..897b598f526 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -466,4 +466,25 @@ describe('useBillingSdkStore subscription commands', () => { }) 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 56e2a8054bc..e5cf33729ad 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -276,6 +276,9 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { 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 }