From ba383362c9206bf7ee211dc7eecadb43009bc3f7 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 15:06:48 -0400 Subject: [PATCH 01/15] fix(account): let the server price a plan change (FE-2216) subscribe() short-circuited an active subscription to ALREADY_HELD, so every upgrade, downgrade and duration change was refused on the client while the host's own POST /billing/subscribe has never gated one. Eligibility now only picks the route: active and free both issue, canceled still reactivates. Reads the preview's cents as numbers rather than the generated bigints, so the quote the SDK hands back is the shape the host already renders. --- .../billing-web/src/test/fakeBillingClient.ts | 16 ++--- .../core/billing/subscriptionCommands.test.ts | 61 ++++++++++++++++--- .../src/core/billing/subscriptionCommands.ts | 55 ++++++++++++++--- .../docs/billing-command-eligibility.md | 56 +++++++++++++++++ 4 files changed, 163 insertions(+), 25 deletions(-) create mode 100644 packages/account/docs/billing-command-eligibility.md diff --git a/apps/billing-web/src/test/fakeBillingClient.ts b/apps/billing-web/src/test/fakeBillingClient.ts index 4050f5d5628..ff47464fb19 100644 --- a/apps/billing-web/src/test/fakeBillingClient.ts +++ b/apps/billing-web/src/test/fakeBillingClient.ts @@ -166,21 +166,21 @@ export function previewOf( ): SubscriptionPreview { return { allowed: true, - cost_today_cents: 2800n, - cost_next_period_cents: 2800n, - credits_today_cents: 6900n, - credits_next_period_cents: 6900n, + cost_today_cents: 2800, + cost_next_period_cents: 2800, + credits_today_cents: 6900, + credits_next_period_cents: 6900, effective_at: '2026-10-01T00:00:00.000Z', is_immediate: true, transition_type: 'upgrade', new_plan: { - credits_cents: 6900n, + credits_cents: 6900, duration: 'MONTHLY', - price_cents: 2800n, + price_cents: 2800, seat_summary: { seat_count: 1, - total_cost_cents: 2800n, - total_credits_cents: 6900n + total_cost_cents: 2800, + total_credits_cents: 6900 }, slug: 'creator_monthly', tier: 'CREATOR' diff --git a/packages/account-core/src/core/billing/subscriptionCommands.test.ts b/packages/account-core/src/core/billing/subscriptionCommands.test.ts index e6f3c4571ae..5e9c4daa90a 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.test.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.test.ts @@ -307,14 +307,43 @@ describe('createBillingCommands', () => { expect(h.lifecycle.getSnapshot()).toEqual([]) }) - it('PRO active: subscribe is a no-op success without a request', async () => { - const h = harness({ status: PRO_ACTIVE }) + it('PRO active: subscribe issues the plan change the server has to price', async () => { + const h = harness({ + status: PRO_ACTIVE, + script: { [POST_SUBSCRIBE]: [subscribed], [GET_OP]: settledOk } + }) + + const result = await h.commands.subscribe({ plan_slug: 'pro-yearly' }) + + expect(result).toMatchObject({ + status: 'ok', + value: { phase: 'succeeded', operation: { id: 'op-1' } } + }) + expect(h.posts()).toEqual([ + expect.objectContaining({ + route: SUBSCRIBE_ROUTE, + body: { plan_slug: 'pro-yearly', idempotency_key: 'key-1' } + }) + ]) + expect(h.invalidate).toHaveBeenCalledOnce() + }) + + it('PRO active: subscribe leaves the server to refuse a transition, code intact', async () => { + const h = harness({ + status: PRO_ACTIVE, + script: { + [POST_SUBSCRIBE]: [serverError(409, 'TRANSITION_NOT_ALLOWED')] + } + }) const result = await h.commands.subscribe(PLAN) - expect(result).toEqual({ status: 'ok', value: { phase: 'succeeded' } }) - expect(h.calls).toEqual([]) - expect(h.invalidate).not.toHaveBeenCalled() + expect(result).toMatchObject({ + status: 'error', + serverCode: 'TRANSITION_NOT_ALLOWED', + httpStatus: 409 + }) + expect(h.posts().map((call) => call.route)).toEqual([SUBSCRIBE_ROUTE]) }) it('PRO active: resubscribe already holds and re-reads status', async () => { @@ -384,6 +413,22 @@ describe('createBillingCommands', () => { expect(h.posts().map((call) => call.route)).toEqual([RESUBSCRIBE_ROUTE]) }) + it('PRO canceled: subscribe reports the already-held code as a success', async () => { + const h = harness({ + status: PRO_CANCELED, + script: { + [POST_RESUBSCRIBE]: [ + serverError(409, 'NOT_SCHEDULED_FOR_CANCELLATION') + ] + } + }) + + const result = await h.commands.subscribe(PLAN) + + expect(result).toEqual({ status: 'ok', value: { phase: 'succeeded' } }) + expect(h.invalidate).toHaveBeenCalledOnce() + }) + it('PRO canceled: resubscribe settles a pending reactivation through the lifecycle', async () => { const h = harness({ status: PRO_CANCELED, @@ -531,8 +576,8 @@ describe('createBillingCommands', () => { status: 'ok', value: { allowed: true, - cost_today_cents: 1500n, - new_plan: { slug: 'pro-monthly', price_cents: 2000n }, + cost_today_cents: 1500, + new_plan: { slug: 'pro-monthly', price_cents: 2000 }, transition_type: 'upgrade' } }) @@ -579,7 +624,7 @@ describe('createBillingCommands', () => { value: expect.objectContaining({ discounts: [ { - amount_off_cents: 500n, + amount_off_cents: 500, code: 'LAUNCH', kind: 'promotion', name: 'Launch offer' diff --git a/packages/account-core/src/core/billing/subscriptionCommands.ts b/packages/account-core/src/core/billing/subscriptionCommands.ts index 4ffafe92fe7..28b79d4e7a3 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.ts @@ -7,20 +7,23 @@ * lifecycle: it only quotes a change. * * Eligibility is decided from the server's own status fields, never from a - * client-side notion of the plan (`docs/billing-command-eligibility.md`). - * Server codes are matched against the closed set named here; a code outside - * it reaches the caller only as the transport's coded failure. + * client-side notion of the plan, and it only ever picks the route — it never + * refuses (`../../../docs/billing-command-eligibility.md`). Server codes are + * matched against the closed set named here; a code outside it reaches the + * caller only as the transport's coded failure. */ import { zCancelSubscriptionResponse2, zPaymentPortalResponse, + zPreviewPlanInfo, zPreviewSubscribeRequest, zPreviewSubscribeResponse, zResubscribeResponse, zSubscribeRequest, - zSubscribeResponse + zSubscribeResponse, + zSubscriptionDiscount } from '@comfyorg/ingest-types/zod' -import type { z } from 'zod' +import { z } from 'zod' import type { BillingFailure, BillingTransport } from './billingContracts.js' import { matchesServerCode } from './billingContracts.js' @@ -90,6 +93,38 @@ export type PaymentPortalResult = | { readonly status: 'ok'; readonly value: { readonly url: string } } | BillingFailure +/** + * The generated schema coerces every int64 to a `bigint`, which no caller can + * add to a price or hand to a currency formatter — and the generated *type* + * for the same field is a `number`. Money on this route is bounded to cents + * well inside the JavaScript-safe range, so the cents are read as numbers, the + * way `capabilities` reads `revision`. + */ +const cents = z.number() + +const PlanInfoSchema = zPreviewPlanInfo.extend({ + credits_cents: cents, + price_cents: cents, + seat_summary: zPreviewPlanInfo.shape.seat_summary.extend({ + total_cost_cents: cents, + total_credits_cents: cents + }) +}) + +const PreviewSchema = zPreviewSubscribeResponse.extend({ + amount_due_cents: cents.optional(), + cost_next_period_cents: cents, + cost_today_cents: cents, + credits_next_period_cents: cents, + credits_today_cents: cents, + renewal_amount_cents: cents.optional(), + current_plan: PlanInfoSchema.optional(), + new_plan: PlanInfoSchema, + discounts: z + .array(zSubscriptionDiscount.extend({ amount_off_cents: cents.optional() })) + .optional() +}) + /** * The quote the server returns for a plan change, in the generated field names. * @@ -98,7 +133,7 @@ export type PaymentPortalResult = * `promotion` one carries back the very `promotionCode` the caller sent, so a * host renders `code` and `name` rather than matching them. */ -export type SubscriptionPreview = z.infer +export type SubscriptionPreview = z.infer export interface PreviewSubscribeInput { readonly planSlug: string @@ -370,10 +405,12 @@ export function createBillingCommands( const status = await statusReader.read() if (status.status === 'error') return status switch (eligibilityOf(status.value.status)) { - case 'active': - return ALREADY_HELD case 'canceled': return resubscribe() + // A plan change is a subscribe against a live subscription, and only the + // server can price one. Refusing it here on the client would deny every + // upgrade, downgrade and duration change the host already allows. + case 'active': case 'free': return settle('subscription', () => issueSubscribe(request)) } @@ -398,7 +435,7 @@ export function createBillingCommands( ? {} : { timeoutMs: options.timeoutMs }) }, - (raw) => zPreviewSubscribeResponse.safeParse(raw) + (raw) => PreviewSchema.safeParse(raw) ) return response.status === 'error' ? response diff --git a/packages/account/docs/billing-command-eligibility.md b/packages/account/docs/billing-command-eligibility.md new file mode 100644 index 00000000000..3a29c90ec67 --- /dev/null +++ b/packages/account/docs/billing-command-eligibility.md @@ -0,0 +1,56 @@ +# Billing command eligibility + +`createBillingCommands` reads `GET /billing/status` before it issues a +subscription command, and uses it to pick a route. It never uses it to refuse +one: pricing a change, rejecting a duplicate and confirming a reactivation are +all server decisions, and a client that second-guesses them denies transitions +the server would have allowed. + +`eligibilityOf` collapses the status into three cases: + +| Eligibility | Status fields | +| ----------- | ---------------------------------------------------------- | +| `free` | `is_active` false, or `subscription_tier` absent or `FREE` | +| `canceled` | paid, and `subscription_status === 'canceled'` | +| `active` | paid, and any other `subscription_status` | + +## Routes + +| Command | `free` | `active` | `canceled` | +| ------------- | ------------------------- | ------------------------- | ---------------------- | +| `subscribe` | `POST /billing/subscribe` | `POST /billing/subscribe` | `resubscribe()` | +| `resubscribe` | `POST .../resubscribe` | `POST .../resubscribe` | `POST .../resubscribe` | +| `cancel` | `POST .../cancel` | `POST .../cancel` | `POST .../cancel` | + +`subscribe` on `active` is a plan change: an upgrade, a downgrade, or a +duration change, priced and prorated by the server. `subscribe` on `canceled` +is a reactivation, which the backend exposes as its own route rather than as a +subscribe. + +## Already-held answers + +A command whose requested state already holds is a success, not a failure: the +caller's intent is satisfied and the request changed nothing. `mapServerCode` +recognises one such code per command, and only from a 4xx — a 5xx that happens +to echo the code is an upstream failure, and the requested state cannot be +assumed to hold. + +| Command | Already-held server code | +| ------------- | -------------------------------- | +| `resubscribe` | `NOT_SCHEDULED_FOR_CANCELLATION` | +| `cancel` | `ALREADY_CANCELED` | +| `subscribe` | none documented on the route | + +The subscribe route documents no already-held code, so `subscribe` reaches one +only through the `canceled` route's `resubscribe()`. A repeat subscribe against +a live subscription surfaces whatever the server answers, exactly as the host's +own `POST /billing/subscribe` call does. + +## Codes the command maps itself + +- `REACTIVATION_CONFIRMATION_REQUIRED` — the server wants the host to + re-preview and resend with `confirm_reactivation`. +- `NO_ACTIVE_SUBSCRIPTION` — resubscribe or cancel with nothing to act on. + +Every other server code reaches the caller as the transport's coded failure, +with `serverCode` intact. From c9e19465b5819edc58cec45e5381fe5b103b7735 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 15:19:00 -0400 Subject: [PATCH 02/15] feat(billing): subscribe and its quote on the SDK rail (FE-2216) Routes the workspace adapter's subscribe and previewSubscribe through the SDK behind the same rail switch, 404 latch and WorkspaceApiError projection cancel already uses, so useSubscriptionCheckout and useDowngradeToPersonal keep branching on the server codes they branch on today. The SDK settles the operation itself, so the store performs the two customer steps the checkout performed for the legacy response: it drives the in-page challenge and opens the hosted payment page. --- .../billing/sdk/billingSdkStore.test.ts | 99 +++++++++ .../workspace/billing/sdk/billingSdkStore.ts | 88 ++++++-- .../billing/sdk/billingSdkTestUtils.ts | 13 ++ .../billing/sdk/subscriptionOperationView.ts | 52 ++++- ...eWorkspaceBilling.subscriptionRail.test.ts | 207 +++++++++++++++++- .../composables/useWorkspaceBilling.ts | 68 ++++++ 6 files changed, 509 insertions(+), 18 deletions(-) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 6fe6143b5af..78b191dda0e 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -12,6 +12,7 @@ import { fakeBillingSdk, failedTopup, pendingTopup, + pendingSubscription, settledOperation, settledTopup } from './billingSdkTestUtils' @@ -403,6 +404,29 @@ describe('useBillingSdkStore subscription commands', () => { httpStatus: 404 } as const + const QUOTE = { + allowed: true, + cost_next_period_cents: 2000, + cost_today_cents: 1500, + credits_next_period_cents: 2000, + credits_today_cents: 1500, + effective_at: '2026-10-01T00:00:00.000Z', + is_immediate: true, + new_plan: { + credits_cents: 2000, + duration: 'MONTHLY', + price_cents: 2000, + seat_summary: { + seat_count: 1, + total_cost_cents: 2000, + total_credits_cents: 2000 + }, + slug: 'pro-monthly', + tier: 'PRO' + }, + transition_type: 'upgrade' + } as const + it('refreshes what the poller refreshed after a cancel settles', async () => { vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( SETTLED @@ -442,13 +466,88 @@ describe('useBillingSdkStore subscription commands', () => { await expect( store.openPaymentPortal('https://app.example/') ).resolves.toEqual({ status: 'unavailable' }) + await expect( + store.subscribe({ plan_slug: 'pro-yearly' }) + ).resolves.toEqual({ status: 'unavailable' }) + await expect( + store.previewSubscribe({ planSlug: 'pro-yearly' }) + ).resolves.toEqual({ status: 'unavailable' }) expect(harness.sdk.commands.cancelSubscription).toHaveBeenCalledOnce() expect(harness.sdk.commands.resubscribe).not.toHaveBeenCalled() expect(harness.sdk.commands.openPaymentPortal).not.toHaveBeenCalled() + expect(harness.sdk.commands.subscribe).not.toHaveBeenCalled() + expect(harness.sdk.commands.previewSubscribe).not.toHaveBeenCalled() expect(mockFetchStatus).not.toHaveBeenCalled() }) + it('reconciles the subscription after a plan change settles', async () => { + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue(SETTLED) + + await expect( + useBillingSdkStore().subscribe({ plan_slug: 'pro-yearly' }) + ).resolves.toEqual({ + status: 'ok', + value: { billing_op_id: 'op-1', status: 'subscribed' } + }) + expect(harness.sdk.commands.subscribe).toHaveBeenCalledWith({ + plan_slug: 'pro-yearly' + }) + expect(mockReconcileSubscription).toHaveBeenCalledOnce() + expect(mockCapabilitiesRefresh).toHaveBeenCalledOnce() + }) + + it('hands back the quote without refreshing anything', async () => { + vi.mocked(harness.sdk.commands.previewSubscribe).mockResolvedValue({ + status: 'ok', + value: QUOTE + }) + + await expect( + useBillingSdkStore().previewSubscribe({ planSlug: 'pro-yearly' }) + ).resolves.toEqual({ status: 'ok', value: QUOTE }) + expect(mockReconcileSubscription).not.toHaveBeenCalled() + expect(mockFetchStatus).not.toHaveBeenCalled() + }) + + it('opens the hosted payment page once for a subscribe parked on the customer', () => { + const openPage = vi.spyOn(window, 'open').mockReturnValue(null) + useBillingSdkStore() + const toasts = useToastStore() + + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/op-1' }) + ) + harness.publish( + pendingSubscription({ + actionUrl: 'https://pay.example/op-1', + customerActionSeen: true + }) + ) + + expect(openPage).toHaveBeenCalledExactlyOnceWith( + 'https://pay.example/op-1', + '_blank' + ) + expect(toasts.messagesToAdd).toEqual([ + expect.objectContaining({ severity: 'warn' }) + ]) + }) + + it('drives the in-page challenge a subscribe raises, as it does for a top-up', async () => { + useBillingSdkStore() + + harness.publish( + pendingSubscription({ + presentation: 'embedded', + challenge: { clientSecret: 'cs_1', status: 'required' } + }) + ) + await nextTick() + + expect(harness.sdk.driveChallenge).toHaveBeenCalledExactlyOnceWith('op-1') + }) + it('hands back the portal URL without refreshing anything', async () => { vi.mocked(harness.sdk.commands.openPaymentPortal).mockResolvedValue({ status: 'ok', diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index bea9ee91618..6d617217756 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -10,7 +10,8 @@ import type { BillingOperationTelemetryEvent, EmbeddedChallengePort, PendingBillingOperation, - SubscriptionCommandResult + PreviewSubscribeInput, + SubscribeInput } from '@comfyorg/account-core/billing' import { BILLING_OPERATION_TELEMETRY_EVENT } from '@comfyorg/account-core/billing' import { loadStripe } from '@stripe/stripe-js/pure' @@ -25,7 +26,11 @@ import { isCloud } from '@/platform/distribution/types' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' import { useTelemetry } from '@/platform/telemetry' import { useToastStore } from '@/platform/updates/common/toastStore' -import type { CreateTopupResponse } from '@/platform/workspace/api/workspaceApi' +import type { + CreateTopupResponse, + PreviewSubscribeResponse, + SubscribeResponse +} from '@/platform/workspace/api/workspaceApi' import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl' import { needsCustomerAttention } from '@/platform/workspace/billing/customerAttention' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' @@ -37,6 +42,8 @@ import { createBillingSdk } from './createBillingSdk' import type { SubscriptionRailOutcome } from './subscriptionOperationView' import { projectPaymentPortalResult, + projectPreviewSubscribeResult, + projectSubscribeResult, projectSubscriptionResult } from './subscriptionOperationView' import { @@ -69,6 +76,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { const dismissed = shallowRef>(new Set()) const resumedOperations = new Set() const drivenChallenges = new Set() + const openedActions = new Set() const progressToasts = new Map< string, { kind: ProgressKind; message: ToastMessage } @@ -90,6 +98,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { sdk.lifecycle.subscribe((state) => { operations.value = sdk.lifecycle.getSnapshot() if (state.kind === 'topup') onTopupChanged(state) + else onSubscriptionChanged(state) }) const wake = () => { @@ -175,6 +184,27 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { progressToasts.delete(operationId) } + // A subscribe the SDK settles has no dialog watching it, so the two customer + // steps the checkout performs for the legacy response — driving the in-page + // challenge and opening the hosted payment page — are performed here, or the + // operation waits on a customer who was never shown anything. + function onSubscriptionChanged(state: BillingOperationState) { + if (state.phase !== 'pending') return + void driveRequiredChallenge(state) + openHostedAction(state) + } + + function openHostedAction(state: PendingBillingOperation) { + if (state.actionUrl === undefined || openedActions.has(state.id)) return + openedActions.add(state.id) + if (window.open(state.actionUrl, '_blank')) return + toastStore.add({ + severity: 'warn', + summary: t('g.warning'), + detail: t('subscription.preview.paymentPopupBlocked') + }) + } + // One in-page challenge per operation, as the poller drives it: a later // challenge for the same operation waits for the customer's retry. async function driveRequiredChallenge(state: PendingBillingOperation) { @@ -224,13 +254,20 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { // every later action goes straight to the legacy call. let subscriptionRouteAvailable = true - async function runSubscriptionCommand( - command: () => Promise, - refresh: () => Promise - ): Promise { + async function onSubscriptionRoute( + run: () => Promise> + ): Promise> { if (!subscriptionRouteAvailable) return { status: 'unavailable' } - const outcome = projectSubscriptionResult(await command()) + const outcome = await run() if (outcome.status === 'unavailable') subscriptionRouteAvailable = false + return outcome + } + + async function runSubscriptionCommand( + command: () => Promise>, + refresh: () => Promise + ): Promise> { + const outcome = await onSubscriptionRoute(command) if (outcome.status === 'ok') await refresh() return outcome } @@ -246,7 +283,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { ]) } - async function refreshAfterResubscribe(): Promise { + async function refreshAfterSubscriptionChange(): Promise { const billingContext = useBillingContext() await Promise.allSettled([ billingContext.reconcileSubscriptionSuccess(), @@ -256,26 +293,45 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { function cancelSubscription(): Promise { return runSubscriptionCommand( - () => sdk.commands.cancelSubscription(), + async () => projectSubscriptionResult(await sdk.commands.cancelSubscription()), refreshAfterCancel ) } function resubscribe(): Promise { return runSubscriptionCommand( - () => sdk.commands.resubscribe(), - refreshAfterResubscribe + async () => projectSubscriptionResult(await sdk.commands.resubscribe()), + refreshAfterSubscriptionChange + ) + } + + function subscribe( + input: SubscribeInput + ): Promise> { + return runSubscriptionCommand( + async () => projectSubscribeResult(await sdk.commands.subscribe(input)), + refreshAfterSubscriptionChange + ) + } + + // A quote changes nothing, so it refreshes nothing; it shares the route + // latch because the backend gates it with the rest of them. + async function previewSubscribe( + input: PreviewSubscribeInput + ): Promise> { + return onSubscriptionRoute(async () => + projectPreviewSubscribeResult(await sdk.commands.previewSubscribe(input)) ) } async function openPaymentPortal( returnUrl: string ): Promise> { - if (!subscriptionRouteAvailable) return { status: 'unavailable' } - const outcome = projectPaymentPortalResult( - await sdk.commands.openPaymentPortal({ returnUrl }) + const outcome = await onSubscriptionRoute(async () => + projectPaymentPortalResult( + await sdk.commands.openPaymentPortal({ returnUrl }) + ) ) - if (outcome.status === 'unavailable') subscriptionRouteAvailable = false // The portal may add or remove a card and says nothing on the way back, so // handing the URL out is the last moment this tab's list is known good. if (outcome.status === 'ok') sdk.paymentMethods.invalidate() @@ -302,6 +358,8 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { isAddingCredits, topupActionOperation, createTopup, + subscribe, + previewSubscribe, cancelSubscription, resubscribe, openPaymentPortal, diff --git a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts index c236ff7572e..41d1854edaf 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -59,6 +59,19 @@ export function pendingTopup( } } +/** A subscribe the lifecycle is still driving, for the store's own effects. */ +export function pendingSubscription( + overrides: Partial = {} +): PendingBillingOperation { + return { + ...IDENTITY, + kind: 'subscription', + phase: 'pending', + customerActionSeen: false, + ...overrides + } +} + export function failedTopup( declineReason: BillingDeclineReason = 'card_declined' ): FailedBillingOperation { diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts index 208f5586d6e..bc8dc3d51bd 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -9,12 +9,19 @@ */ import type { PaymentPortalResult, + PreviewSubscribeInput, + PreviewSubscribeResult, + SubscribeInput, SubscriptionCommandFailure, SubscriptionCommandOutcome, SubscriptionCommandResult } from '@comfyorg/account-core/billing' import { t } from '@/i18n' +import type { + PreviewSubscribeResponse, + SubscribeResponse +} from '@/platform/workspace/api/workspaceApi' import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { declineDetail } from './topupOperationView' @@ -26,11 +33,18 @@ export type SubscriptionRailOutcome = | { readonly status: 'unavailable' } /** - * The three subscription actions the host routes through the SDK. Cancel and + * The subscription actions the host routes through the SDK. Cancel and * resubscribe report only whether they settled; the portal hands back the URL - * the host opens. + * the host opens; subscribe and its quote hand back the bodies the checkout + * already reads. */ export interface SubscriptionRail { + subscribe: ( + input: SubscribeInput + ) => Promise> + previewSubscribe: ( + input: PreviewSubscribeInput + ) => Promise> cancelSubscription: () => Promise resubscribe: () => Promise openPaymentPortal: ( @@ -109,6 +123,40 @@ export function projectSubscriptionResult( : projectUnsuccessfulSettle(result.value) } +/** + * A settled subscribe as the body `handleSubscribeResponse` already handles. + * The SDK waits for the operation, so by the time this projects there is + * nothing left to poll: the status is always the settled `subscribed`, never + * the response's `needs_payment_method` or `pending_payment`, both of which + * the lifecycle drove to a conclusion first. + * + * `billing_op_id` is empty when the server answered that the requested state + * already held: nothing was issued, so there is no operation to attribute the + * success to. Both callers read the id only to report telemetry, and both + * treat an absent response as a failure — which this is not. + */ +export function projectSubscribeResult( + result: SubscriptionCommandResult +): SubscriptionRailOutcome { + if (result.status === 'error') return projectFailure(result) + const { phase, operation } = result.value + if (phase !== 'succeeded') { + return { status: 'error', error: new Error(`phase: ${phase}`) } + } + return { + status: 'ok', + value: { billing_op_id: operation?.id ?? '', status: 'subscribed' } + } +} + +export function projectPreviewSubscribeResult( + result: PreviewSubscribeResult +): SubscriptionRailOutcome { + return result.status === 'error' + ? projectFailure(result) + : { status: 'ok', value: result.value } +} + export function projectPaymentPortalResult( result: PaymentPortalResult ): SubscriptionRailOutcome { diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index de1f763a83b..3157503ae79 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -2,13 +2,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope } from 'vue' import type { BillingTelemetryEvent } from '@/platform/telemetry/types' -import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' +import type { + BillingStatusResponse, + PreviewSubscribeResponse +} from '@/platform/workspace/api/workspaceApi' import { WorkspaceApiError, workspaceApi } from '@/platform/workspace/api/workspaceApi' import { fakeBillingSdk, + serverCode, settledOperation } from '@/platform/workspace/billing/sdk/billingSdkTestUtils' import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingSdk' @@ -95,6 +99,37 @@ const SETTLED = { value: { phase: 'succeeded', operation: settledOperation('succeeded') } } as const +const PLAN_INFO = { + credits_cents: 2000, + duration: 'MONTHLY', + price_cents: 2000, + seat_summary: { + seat_count: 1, + total_cost_cents: 2000, + total_credits_cents: 2000 + }, + slug: 'pro-monthly', + tier: 'PRO' +} as const + +const LEGACY_QUOTE: PreviewSubscribeResponse = { + allowed: true, + cost_next_period_cents: 2000, + cost_today_cents: 1500, + credits_next_period_cents: 2000, + credits_today_cents: 1500, + effective_at: '2026-10-01T00:00:00.000Z', + is_immediate: true, + new_plan: PLAN_INFO, + transition_type: 'upgrade' +} + +const SDK_QUOTE: PreviewSubscribeResponse = { + ...LEGACY_QUOTE, + cost_today_cents: 900, + transition_type: 'downgrade' +} + let harness: ReturnType function setupBilling() { @@ -125,6 +160,11 @@ beforeEach(() => { vi.spyOn(workspaceApi, 'getPaymentPortalUrl').mockResolvedValue({ url: 'https://portal.legacy.example/session' }) + vi.spyOn(workspaceApi, 'subscribe').mockResolvedValue({ + billing_op_id: 'op-legacy', + status: 'subscribed' + }) + vi.spyOn(workspaceApi, 'previewSubscribe').mockResolvedValue(LEGACY_QUOTE) vi.spyOn(window, 'open').mockReturnValue(null) vi.mocked(useBillingOperationStore().startOperation).mockResolvedValue({ status: 'succeeded' @@ -292,6 +332,171 @@ describe('resubscribe on the billing SDK rail', () => { }) }) +describe('subscribe on the billing SDK rail', () => { + it('issues through the workspace client while the rail is off', async () => { + await setupBilling().subscribe('pro-yearly', { promotionCode: 'LAUNCH' }) + + expect(workspaceApi.subscribe).toHaveBeenCalledWith('pro-yearly', { + promotionCode: 'LAUNCH' + }) + expect(mockCreateBillingSdk).not.toHaveBeenCalled() + }) + + it('maps the host options onto the generated request body', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue(SETTLED) + + const response = await setupBilling().subscribe('pro-yearly', { + confirmationToken: '', + savedPaymentMethodId: 'pm_123', + promotionCode: 'LAUNCH', + quoteId: 'quote-1', + quoteVersion: 3, + returnUrl: 'https://app.example/success', + cancelUrl: 'https://app.example/failed', + teamCreditStopId: 'stop-1', + billingCycle: 'yearly', + confirmReactivation: true, + prorationAt: '2026-10-01T00:00:00.000Z' + }) + + expect(harness.sdk.commands.subscribe).toHaveBeenCalledWith({ + plan_slug: 'pro-yearly', + confirmation_token: undefined, + saved_payment_method_id: 'pm_123', + promotion_code: 'LAUNCH', + quote_id: 'quote-1', + quote_version: 3, + return_url: 'https://app.example/success', + cancel_url: 'https://app.example/failed', + team_credit_stop_id: 'stop-1', + billing_cycle: 'yearly', + confirm_reactivation: true, + proration_at: '2026-10-01T00:00:00.000Z' + }) + expect(response).toEqual({ + billing_op_id: 'op-1', + status: 'subscribed' + }) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) + + it('reports an already-held plan as a settled subscribe', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ + status: 'ok', + value: { phase: 'succeeded' } + }) + + await expect(setupBilling().subscribe('pro-monthly')).resolves.toEqual({ + billing_op_id: '', + status: 'subscribed' + }) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) + + it('falls back to the workspace client once when the route is missing', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue(ROUTE_MISSING) + const billing = setupBilling() + + await billing.subscribe('pro-monthly') + await billing.subscribe('pro-monthly') + + expect(harness.sdk.commands.subscribe).toHaveBeenCalledOnce() + expect(workspaceApi.subscribe).toHaveBeenCalledTimes(2) + }) + + it('surfaces a reactivation block under the code the checkout branches on', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ + status: 'error', + code: 'REACTIVATION_CONFIRMATION_REQUIRED' + }) + + await expect(setupBilling().subscribe('pro-monthly')).rejects.toMatchObject( + { code: 'REACTIVATION_CONFIRMATION_REQUIRED' } + ) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) + + it('surfaces a refused transition under the server code', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ + status: 'error', + code: 'CONFLICT', + httpStatus: 409, + serverCode: serverCode('TRANSITION_NOT_ALLOWED') + }) + + await expect(setupBilling().subscribe('pro-monthly')).rejects.toMatchObject( + { code: 'TRANSITION_NOT_ALLOWED', status: 409 } + ) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) + + it('reports an operation that never settled as a failure', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ + status: 'ok', + value: { + phase: 'timed_out', + operation: settledOperation('timed_out', 'subscription') + } + }) + + await expect(setupBilling().subscribe('pro-monthly')).rejects.toThrow( + 'phase: timed_out' + ) + expect(workspaceApi.subscribe).not.toHaveBeenCalled() + }) +}) + +describe('preview subscribe on the billing SDK rail', () => { + it('quotes through the workspace client while the rail is off', async () => { + const quote = await setupBilling().previewSubscribe('pro-yearly', { + teamCreditStopId: 'stop-1' + }) + + expect(workspaceApi.previewSubscribe).toHaveBeenCalledWith('pro-yearly', { + teamCreditStopId: 'stop-1' + }) + expect(quote).toEqual(LEGACY_QUOTE) + }) + + it('quotes through the SDK command while the rail is on', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.previewSubscribe).mockResolvedValue({ + status: 'ok', + value: SDK_QUOTE + }) + + const quote = await setupBilling().previewSubscribe('pro-yearly', { + teamCreditStopId: 'stop-1', + promotionCode: 'LAUNCH' + }) + + expect(harness.sdk.commands.previewSubscribe).toHaveBeenCalledWith({ + planSlug: 'pro-yearly', + teamCreditStopId: 'stop-1', + promotionCode: 'LAUNCH' + }) + expect(quote).toEqual(SDK_QUOTE) + expect(workspaceApi.previewSubscribe).not.toHaveBeenCalled() + }) + + it('falls back to the workspace client when the route is missing', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.previewSubscribe).mockResolvedValue( + ROUTE_MISSING + ) + + const quote = await setupBilling().previewSubscribe('pro-yearly') + + expect(quote).toEqual(LEGACY_QUOTE) + }) +}) + describe('payment portal on the billing SDK rail', () => { it('opens the workspace client URL while the rail is off', async () => { await setupBilling().manageSubscription() diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 68ec60aad04..461b29ea0a9 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -7,6 +7,11 @@ import { watch } from 'vue' +import type { + PreviewSubscribeInput, + SubscribeInput +} from '@comfyorg/account-core/billing' + import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useBillingPlans } from '@/platform/cloud/subscription/composables/useBillingPlans' import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' @@ -115,6 +120,51 @@ async function resyncQuietly(refresh: () => Promise): Promise { /** The SDK rail refusing an action, distinct from any value it could return. */ const DECLINED = Symbol('subscription rail declined') +/** + * The host's options as the generated request body, field for field, including + * the two the workspace client drops when they arrive empty: JSON keeps `''`, + * so an empty credential would reach the server as present but meaningless. + * + * `SubscribeOptions` carries nothing the generated body lacks. `SubscribeInput` + * also has `checkout_attempt_id` and `idempotency_key`, which no host caller + * sets: the SDK mints the key itself, and the checkout attempt is carried on + * the quote rather than the subscribe. + */ +function subscribeInputFrom( + planSlug: string, + options: SubscribeOptions = {} +): SubscribeInput { + return { + plan_slug: planSlug, + confirmation_token: options.confirmationToken || undefined, + saved_payment_method_id: options.savedPaymentMethodId || undefined, + promotion_code: options.promotionCode, + quote_id: options.quoteId, + quote_version: options.quoteVersion, + return_url: options.returnUrl, + cancel_url: options.cancelUrl, + team_credit_stop_id: options.teamCreditStopId, + billing_cycle: options.billingCycle, + confirm_reactivation: options.confirmReactivation, + proration_at: options.prorationAt + } +} + +function previewSubscribeInputFrom( + planSlug: string, + options: PreviewSubscribeOptions = {} +): PreviewSubscribeInput { + return { + planSlug, + ...(options.promotionCode === undefined + ? {} + : { promotionCode: options.promotionCode }), + ...(options.teamCreditStopId === undefined + ? {} + : { teamCreditStopId: options.teamCreditStopId }) + } +} + interface SeatCapacity { maxSeats: number occupiedSeats: number @@ -372,6 +422,16 @@ export function useWorkspaceBilling(): BillingState & BillingActions { planSlug: string, options?: SubscribeOptions ): Promise { + const rail = useSubscriptionRail() + if (rail) { + const response = await onSubscriptionRail(() => + rail.subscribe(subscribeInputFrom(planSlug, options)) + ) + // The SDK waited for the operation, so the refresh the legacy path fires + // and forgets has already run on the rail. + if (response !== DECLINED) return response + } + isLoading.value = true error.value = null try { @@ -390,6 +450,14 @@ export function useWorkspaceBilling(): BillingState & BillingActions { planSlug: string, options?: PreviewSubscribeOptions ): Promise { + const rail = useSubscriptionRail() + if (rail) { + const quote = await onSubscriptionRail(() => + rail.previewSubscribe(previewSubscribeInputFrom(planSlug, options)) + ) + if (quote !== DECLINED) return quote + } + isLoading.value = true error.value = null try { From 737c3d3b6563a704b19a3e6ee1e8b1f6a4073934 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 15:28:14 -0400 Subject: [PATCH 03/15] test(billing): cover the plan-change rail end to end on cloud (FE-2216) Upgrades an active plan from the pricing deep link on both rails. The recorded requests separate them: the SDK transport's subscribe carries an Idempotency-Key and the legacy one does not, and neither rail sends one for the quote. A 404 on the SDK route falls back to the legacy call in the same click. --- .../tests/dialogs/planChangeSdkRail.spec.ts | 292 ++++++++++++++++++ 1 file changed, 292 insertions(+) create mode 100644 browser_tests/tests/dialogs/planChangeSdkRail.spec.ts diff --git a/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts b/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts new file mode 100644 index 00000000000..af7aac9f177 --- /dev/null +++ b/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts @@ -0,0 +1,292 @@ +import { expect } from '@playwright/test' +import type { Page, Request } from '@playwright/test' +import type { + BillingOpStatusResponse, + BillingPlansResponse, + BillingStatusResponse, + Plan, + PreviewSubscribeResponse, + SubscribeResponse +} from '@comfyorg/ingest-types' + +import type { RemoteConfig } from '@/platform/remoteConfig/types' + +import { + cloudAppExpect, + cloudAppFixture as test +} from '@e2e/fixtures/cloudAppFixture' +import { createWorkspaceBillingCapabilities } from '@e2e/fixtures/data/billingCapabilities' +import { FeatureFlagHelper } from '@e2e/fixtures/helpers/FeatureFlagHelper' +import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' +import { bootCloud, mockCloudBoot } from '@e2e/fixtures/utils/cloudBootMocks' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' + +/** + * Changing plan across the billing SDK rail — FE-2216. + * + * Both rails quote through `POST /billing/preview-subscribe` and commit through + * `POST /billing/subscribe`, so the recorded requests are what separate them: + * only the SDK transport sends an `Idempotency-Key`, and only on the write — + * the quote is a read the backend happens to shape as a POST, so it carries + * none on either rail. + */ +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' + +const BOOT_FEATURES = { + billing_control_enabled: true, + unified_cloud_auth: true +} satisfies RemoteConfig + +const STANDARD_ANNUAL_PLAN = { + slug: 'standard-annual', + tier: 'STANDARD', + duration: 'ANNUAL', + price_cents: 19_200, + credits_cents: 4_200, + max_seats: 1, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: 19_200, + total_credits_cents: 4_200 + } +} satisfies Plan + +const CREATOR_ANNUAL_PLAN = { + slug: 'creator-annual', + tier: 'CREATOR', + duration: 'ANNUAL', + price_cents: 33_600, + credits_cents: 7_400, + max_seats: 5, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: 33_600, + total_credits_cents: 7_400 + } +} satisfies Plan + +const ACTIVE_STANDARD_STATUS = { + is_active: true, + subscription_status: 'active', + subscription_tier: 'STANDARD', + subscription_duration: 'ANNUAL', + plan_slug: 'standard-annual', + billing_rail: 'stripe', + billing_status: 'paid', + has_funds: true, + renewal_date: '2099-02-20T00:00:00Z', + team_credit_stop: null, + scheduled_change: null, + max_seats: 1, + occupied_seats: 1 +} satisfies BillingStatusResponse + +const PLANS = { + current_plan_slug: 'standard-annual', + plans: [STANDARD_ANNUAL_PLAN, CREATOR_ANNUAL_PLAN] +} satisfies BillingPlansResponse + +const CREATOR_UPGRADE_QUOTE = { + allowed: true, + transition_type: 'upgrade', + effective_at: '2026-09-16T00:00:00Z', + is_immediate: true, + cost_today_cents: 14_400, + cost_next_period_cents: 33_600, + credits_today_cents: 3_200, + credits_next_period_cents: 7_400, + current_plan: { + slug: STANDARD_ANNUAL_PLAN.slug, + tier: STANDARD_ANNUAL_PLAN.tier, + duration: STANDARD_ANNUAL_PLAN.duration, + price_cents: STANDARD_ANNUAL_PLAN.price_cents, + credits_cents: STANDARD_ANNUAL_PLAN.credits_cents, + seat_summary: STANDARD_ANNUAL_PLAN.seat_summary, + period_end: '2099-02-20T00:00:00Z' + }, + new_plan: { + slug: CREATOR_ANNUAL_PLAN.slug, + tier: CREATOR_ANNUAL_PLAN.tier, + duration: CREATOR_ANNUAL_PLAN.duration, + price_cents: CREATOR_ANNUAL_PLAN.price_cents, + credits_cents: CREATOR_ANNUAL_PLAN.credits_cents, + seat_summary: CREATOR_ANNUAL_PLAN.seat_summary + } +} satisfies PreviewSubscribeResponse + +const CHANGE_OPERATION_ID = 'op-plan-change' + +const SUBSCRIBED_RESPONSE = { + billing_op_id: CHANGE_OPERATION_ID, + status: 'subscribed', + effective_at: '2026-09-16T00:00:00Z' +} satisfies SubscribeResponse + +const SETTLED_OPERATION = { + id: CHANGE_OPERATION_ID, + status: 'succeeded', + started_at: '2026-09-16T00:00:00Z', + completed_at: '2026-09-16T00:00:05Z' +} satisfies BillingOpStatusResponse + +interface PlanChangeRoutes { + /** Every POST the app made to the quote route, in order. */ + readonly previewRequests: Request[] + /** Every POST the app made to the subscribe route, in order. */ + readonly subscribeRequests: Request[] + /** Answers the next subscribe with a 404, as a closed backend gate does. */ + respondNotFound: () => void +} + +// The deep-link loader runs at the tail of GraphCanvas onMounted, so the boot +// chain must not throw before it. +async function mockGraphBootExtras(page: Page) { + await page.route('**/api/settings/**', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({})) + }) + await page.route('**/api/assets**', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ assets: [], total: 0, has_more: false })) + }) + await page.route('**/api/prompt', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ exec_info: { queue_remaining: 0 } })) + }) + await page.route('**/api/queue', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ queue_running: [], queue_pending: [] })) + }) +} + +async function setupPlanChange(page: Page): Promise { + const ws = workspace('personal', 'owner') + const previewRequests: Request[] = [] + const subscribeRequests: Request[] = [] + let notFound = false + + await mockCloudBoot(page, { + features: BOOT_FEATURES, + settings: { 'Comfy.TutorialCompleted': true } + }) + await mockGraphBootExtras(page) + await mockBilling(page, { + workspaceId: ws.id, + billingStatus: ACTIVE_STANDARD_STATUS, + billingCapabilities: createWorkspaceBillingCapabilities(ws) + }) + await mockWorkspace(page, ws, []) + + await page.route('**/api/billing/plans', (route) => + route.fulfill(jsonRoute(PLANS)) + ) + await page.route('**/api/billing/preview-subscribe', (route) => { + previewRequests.push(route.request()) + return route.fulfill(jsonRoute(CREATOR_UPGRADE_QUOTE)) + }) + await page.route('**/api/billing/subscribe', async (route) => { + subscribeRequests.push(route.request()) + if (notFound) { + notFound = false + await route.fulfill({ status: 404, body: '' }) + return + } + await route.fulfill(jsonRoute(SUBSCRIBED_RESPONSE)) + }) + // Only the SDK rail polls a `subscribed` response; the legacy path reports + // success straight from the body. + await page.route(`**/api/billing/ops/${CHANGE_OPERATION_ID}`, (route) => + route.fulfill(jsonRoute(SETTLED_OPERATION)) + ) + + await bootCloud(page) + return { + previewRequests, + subscribeRequests, + respondNotFound: () => { + notFound = true + } + } +} + +/** The SDK transport sends this header; the legacy axios client never does. */ +function idempotencyKey(request: Request): string | undefined { + return request.headers()['idempotency-key'] +} + +async function openCreatorUpgrade(page: Page) { + await page.goto(`${APP_URL}/?pricing=creator&cycle=yearly`) + await cloudAppExpect( + page.getByRole('heading', { name: 'Confirm your upgrade' }) + ).toBeVisible() +} + +const confirmButton = (page: Page) => + page.getByRole('button', { name: 'Confirm upgrade' }) + +const successHeading = (page: Page) => + page.getByRole('heading', { name: "You're all set" }) + +test.describe('Plan change rail (FE-2216)', { tag: '@cloud' }, () => { + test('keeps the legacy calls while the SDK rail is off', async ({ page }) => { + test.setTimeout(60_000) + const routes = await setupPlanChange(page) + + await openCreatorUpgrade(page) + await confirmButton(page).click() + + await expect(successHeading(page)).toBeVisible() + expect(routes.subscribeRequests).toHaveLength(1) + expect(idempotencyKey(routes.subscribeRequests[0])).toBeUndefined() + expect(routes.previewRequests.length).toBeGreaterThan(0) + expect(idempotencyKey(routes.previewRequests[0])).toBeUndefined() + }) + + test('issues through the SDK transport while the rail is on', async ({ + page + }) => { + test.setTimeout(60_000) + const routes = await setupPlanChange(page) + await openCreatorUpgrade(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + billing_sdk_subscription_enabled: true + }) + + await confirmButton(page).click() + + await expect(successHeading(page)).toBeVisible() + expect(routes.subscribeRequests).toHaveLength(1) + const [issued] = routes.subscribeRequests + expect(issued.method()).toBe('POST') + expect(idempotencyKey(issued)).toBeTruthy() + expect(issued.postDataJSON()).toMatchObject({ + plan_slug: 'creator-annual', + idempotency_key: idempotencyKey(issued) + }) + // The quote is a read; the SDK sends no key for it on either rail. + expect(idempotencyKey(routes.previewRequests.at(-1)!)).toBeUndefined() + }) + + test('falls back to the legacy call when the SDK route answers 404', async ({ + page + }) => { + test.setTimeout(60_000) + const routes = await setupPlanChange(page) + await openCreatorUpgrade(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + billing_sdk_subscription_enabled: true + }) + routes.respondNotFound() + + await confirmButton(page).click() + + await expect(successHeading(page)).toBeVisible() + await expect.poll(() => routes.subscribeRequests.length).toBe(2) + const [sdkAttempt, legacyAttempt] = routes.subscribeRequests + expect(idempotencyKey(sdkAttempt)).toBeTruthy() + expect(idempotencyKey(legacyAttempt)).toBeUndefined() + }) +}) From 05644b4d78288b3b5826f65bdf97386602891965 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 15:42:53 -0400 Subject: [PATCH 04/15] fix(account): subscribe never short-circuits on a scheduled cancel (FE-2216) subscribe() routed a scheduled-cancel subscription to resubscribe(), which drops the requested plan_slug and resumes the old plan. The host's legacy POST /billing/subscribe has never done that: it posts the requested plan and lets the server reactivate with it or answer REACTIVATION_CONFIRMATION_REQUIRED, a code that exists for exactly this case. The rule already applied to an active subscription now covers every state: the client never decides. The status read subscribe made for that decision is gone with it, and so is eligibilityOf, which nothing else consulted. Subscribe can no longer settle without an operation, so the rail projection stops synthesizing an empty billing_op_id for it. --- .../core/billing/subscriptionCommands.test.ts | 42 +++++++++------- .../src/core/billing/subscriptionCommands.ts | 35 +++----------- .../docs/billing-command-eligibility.md | 48 ++++++++----------- .../billing/sdk/billingSdkStore.test.ts | 6 +-- .../workspace/billing/sdk/billingSdkStore.ts | 3 +- .../billing/sdk/subscriptionOperationView.ts | 11 ++--- ...eWorkspaceBilling.subscriptionRail.test.ts | 14 ------ 7 files changed, 63 insertions(+), 96 deletions(-) diff --git a/packages/account-core/src/core/billing/subscriptionCommands.test.ts b/packages/account-core/src/core/billing/subscriptionCommands.test.ts index 5e9c4daa90a..cdfc0d4682a 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.test.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.test.ts @@ -253,7 +253,7 @@ beforeEach(() => { }) describe('createBillingCommands', () => { - describe('eligibility from the status snapshot', () => { + describe('each command against the subscription state', () => { it('FREE: subscribe issues the checkout and settles the operation', async () => { const h = harness({ status: FREE, @@ -393,40 +393,50 @@ describe('createBillingCommands', () => { expect(h.invalidate).toHaveBeenCalledOnce() }) - it('PRO canceled: subscribe routes to the resubscribe endpoint', async () => { + it('PRO canceled: subscribe carries the requested plan to the subscribe route', async () => { const h = harness({ status: PRO_CANCELED, - script: { - [POST_RESUBSCRIBE]: [ - http(200, { billing_op_id: 'op-1', status: 'active' }) - ], - [GET_OP]: settledOk - } + script: { [POST_SUBSCRIBE]: [subscribed], [GET_OP]: settledOk } }) - const result = await h.commands.subscribe(PLAN) + const result = await h.commands.subscribe({ + plan_slug: 'pro-yearly', + confirm_reactivation: true + }) expect(result).toMatchObject({ status: 'ok', - value: { phase: 'succeeded', operation: { kind: 'subscription' } } + value: { phase: 'succeeded', operation: { id: 'op-1' } } }) - expect(h.posts().map((call) => call.route)).toEqual([RESUBSCRIBE_ROUTE]) + expect(h.posts()).toEqual([ + expect.objectContaining({ + route: SUBSCRIBE_ROUTE, + body: { + plan_slug: 'pro-yearly', + confirm_reactivation: true, + idempotency_key: 'key-1' + } + }) + ]) }) - it('PRO canceled: subscribe reports the already-held code as a success', async () => { + it('PRO canceled: subscribe hands the server its reactivation block back', async () => { const h = harness({ status: PRO_CANCELED, script: { - [POST_RESUBSCRIBE]: [ - serverError(409, 'NOT_SCHEDULED_FOR_CANCELLATION') + [POST_SUBSCRIBE]: [ + serverError(409, 'REACTIVATION_CONFIRMATION_REQUIRED') ] } }) const result = await h.commands.subscribe(PLAN) - expect(result).toEqual({ status: 'ok', value: { phase: 'succeeded' } }) - expect(h.invalidate).toHaveBeenCalledOnce() + expect(result).toEqual({ + status: 'error', + code: 'REACTIVATION_CONFIRMATION_REQUIRED' + }) + expect(h.posts().map((call) => call.route)).toEqual([SUBSCRIBE_ROUTE]) }) it('PRO canceled: resubscribe settles a pending reactivation through the lifecycle', async () => { diff --git a/packages/account-core/src/core/billing/subscriptionCommands.ts b/packages/account-core/src/core/billing/subscriptionCommands.ts index 28b79d4e7a3..5e69a21b19c 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.ts @@ -6,11 +6,10 @@ * stay in the lifecycle. `previewSubscribe` sits beside them without a * lifecycle: it only quotes a change. * - * Eligibility is decided from the server's own status fields, never from a - * client-side notion of the plan, and it only ever picks the route — it never - * refuses (`../../../docs/billing-command-eligibility.md`). Server codes are - * matched against the closed set named here; a code outside it reaches the - * caller only as the transport's coded failure. + * No command decides for the server whether a transition is allowed + * (`../../../docs/billing-command-eligibility.md`). Server codes are matched + * against the closed set named here; a code outside it reaches the caller only + * as the transport's coded failure. */ import { zCancelSubscriptionResponse2, @@ -40,7 +39,7 @@ import type { } from './operationState.js' import { validateActionUrl } from './operationState.js' import { readValidatedBillingResponse } from './sharedRead.js' -import type { BillingStatusData, BillingStatusReader } from './status.js' +import type { BillingStatusReader } from './status.js' export const SUBSCRIBE_ROUTE = '/billing/subscribe' export const RESUBSCRIBE_ROUTE = '/billing/subscription/resubscribe' @@ -196,17 +195,6 @@ function coded(code: SubscriptionCommandCode): SubscriptionCommandFailure { return { status: 'error', code } } -type Eligibility = 'free' | 'active' | 'canceled' - -function eligibilityOf(status: BillingStatusData): Eligibility { - const paid = - status.is_active && - status.subscription_tier !== undefined && - status.subscription_tier !== 'FREE' - if (!paid) return 'free' - return status.subscription_status === 'canceled' ? 'canceled' : 'active' -} - /** * A server code the caller's request already satisfies is a success, but * only from a 4xx: a 5xx echoing the code is an upstream failure that @@ -402,18 +390,7 @@ export function createBillingCommands( return coded('INVALID_REQUEST') } - const status = await statusReader.read() - if (status.status === 'error') return status - switch (eligibilityOf(status.value.status)) { - case 'canceled': - return resubscribe() - // A plan change is a subscribe against a live subscription, and only the - // server can price one. Refusing it here on the client would deny every - // upgrade, downgrade and duration change the host already allows. - case 'active': - case 'free': - return settle('subscription', () => issueSubscribe(request)) - } + return settle('subscription', () => issueSubscribe(request)) } async function previewSubscribe( diff --git a/packages/account/docs/billing-command-eligibility.md b/packages/account/docs/billing-command-eligibility.md index 3a29c90ec67..a1fd688eeb1 100644 --- a/packages/account/docs/billing-command-eligibility.md +++ b/packages/account/docs/billing-command-eligibility.md @@ -1,31 +1,24 @@ # Billing command eligibility -`createBillingCommands` reads `GET /billing/status` before it issues a -subscription command, and uses it to pick a route. It never uses it to refuse -one: pricing a change, rejecting a duplicate and confirming a reactivation are -all server decisions, and a client that second-guesses them denies transitions -the server would have allowed. - -`eligibilityOf` collapses the status into three cases: - -| Eligibility | Status fields | -| ----------- | ---------------------------------------------------------- | -| `free` | `is_active` false, or `subscription_tier` absent or `FREE` | -| `canceled` | paid, and `subscription_status === 'canceled'` | -| `active` | paid, and any other `subscription_status` | +No subscription command reads the subscription's state to decide whether it +may run. Pricing a change, reactivating a scheduled cancel, rejecting a +duplicate and demanding a confirmation are all server decisions, and a client +that second-guesses them denies transitions the server would have allowed. ## Routes -| Command | `free` | `active` | `canceled` | -| ------------- | ------------------------- | ------------------------- | ---------------------- | -| `subscribe` | `POST /billing/subscribe` | `POST /billing/subscribe` | `resubscribe()` | -| `resubscribe` | `POST .../resubscribe` | `POST .../resubscribe` | `POST .../resubscribe` | -| `cancel` | `POST .../cancel` | `POST .../cancel` | `POST .../cancel` | +| Command | Route | +| ------------- | ------------------------- | +| `subscribe` | `POST /billing/subscribe` | +| `resubscribe` | `POST .../resubscribe` | +| `cancel` | `POST .../cancel` | -`subscribe` on `active` is a plan change: an upgrade, a downgrade, or a -duration change, priced and prorated by the server. `subscribe` on `canceled` -is a reactivation, which the backend exposes as its own route rather than as a -subscribe. +The status read decides nothing for `subscribe`: whatever state the +subscription is in, the request goes to the subscribe route carrying the +`plan_slug` that was asked for, and the server prices the change, reactivates a +scheduled cancel, or refuses. Routing a scheduled cancel to `resubscribe()` +would drop that plan and resume the old one instead; `resubscribe` stays the +explicit "resume subscription" action, which carries no plan of its own. ## Already-held answers @@ -41,15 +34,16 @@ assumed to hold. | `cancel` | `ALREADY_CANCELED` | | `subscribe` | none documented on the route | -The subscribe route documents no already-held code, so `subscribe` reaches one -only through the `canceled` route's `resubscribe()`. A repeat subscribe against -a live subscription surfaces whatever the server answers, exactly as the host's -own `POST /billing/subscribe` call does. +The subscribe route documents no already-held code, so `subscribe` never +settles without an operation. A repeat subscribe against a live subscription +surfaces whatever the server answers, exactly as the host's own +`POST /billing/subscribe` call does. ## Codes the command maps itself - `REACTIVATION_CONFIRMATION_REQUIRED` — the server wants the host to - re-preview and resend with `confirm_reactivation`. + re-preview and resend with `confirm_reactivation`. It exists for exactly the + subscribe-on-a-scheduled-cancel case. - `NO_ACTIVE_SUBSCRIPTION` — resubscribe or cancel with nothing to act on. Every other server code reaches the caller as the transport's coded failure, diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 78b191dda0e..6e118c372a3 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -466,9 +466,9 @@ describe('useBillingSdkStore subscription commands', () => { await expect( store.openPaymentPortal('https://app.example/') ).resolves.toEqual({ status: 'unavailable' }) - await expect( - store.subscribe({ plan_slug: 'pro-yearly' }) - ).resolves.toEqual({ status: 'unavailable' }) + await expect(store.subscribe({ plan_slug: 'pro-yearly' })).resolves.toEqual( + { status: 'unavailable' } + ) await expect( store.previewSubscribe({ planSlug: 'pro-yearly' }) ).resolves.toEqual({ status: 'unavailable' }) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index 6d617217756..2f5779221e1 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -293,7 +293,8 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { function cancelSubscription(): Promise { return runSubscriptionCommand( - async () => projectSubscriptionResult(await sdk.commands.cancelSubscription()), + async () => + projectSubscriptionResult(await sdk.commands.cancelSubscription()), refreshAfterCancel ) } diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts index bc8dc3d51bd..3d6d076d27f 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -130,22 +130,21 @@ export function projectSubscriptionResult( * the response's `needs_payment_method` or `pending_payment`, both of which * the lifecycle drove to a conclusion first. * - * `billing_op_id` is empty when the server answered that the requested state - * already held: nothing was issued, so there is no operation to attribute the - * success to. Both callers read the id only to report telemetry, and both - * treat an absent response as a failure — which this is not. + * An outcome carries no operation only when the server answered that the + * requested state already held, which subscribe never reaches: the route + * documents no already-held code. */ export function projectSubscribeResult( result: SubscriptionCommandResult ): SubscriptionRailOutcome { if (result.status === 'error') return projectFailure(result) const { phase, operation } = result.value - if (phase !== 'succeeded') { + if (phase !== 'succeeded' || operation === undefined) { return { status: 'error', error: new Error(`phase: ${phase}`) } } return { status: 'ok', - value: { billing_op_id: operation?.id ?? '', status: 'subscribed' } + value: { billing_op_id: operation.id, status: 'subscribed' } } } diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index 3157503ae79..175c4b55bc7 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -381,20 +381,6 @@ describe('subscribe on the billing SDK rail', () => { expect(workspaceApi.subscribe).not.toHaveBeenCalled() }) - it('reports an already-held plan as a settled subscribe', async () => { - flagState.billingSdkSubscriptionEnabled = true - vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue({ - status: 'ok', - value: { phase: 'succeeded' } - }) - - await expect(setupBilling().subscribe('pro-monthly')).resolves.toEqual({ - billing_op_id: '', - status: 'subscribed' - }) - expect(workspaceApi.subscribe).not.toHaveBeenCalled() - }) - it('falls back to the workspace client once when the route is missing', async () => { flagState.billingSdkSubscriptionEnabled = true vi.mocked(harness.sdk.commands.subscribe).mockResolvedValue(ROUTE_MISSING) From 1b48bedee3fd882c359223a5050dff73450bc195 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 16 Sep 2026 17:30:31 -0400 Subject: [PATCH 05/15] test(account-ui): expect the quote's cents as numbers (FE-2216) This branch reads the preview route's money as numbers instead of the bigints the generated schema coerces to, and updated billing-web's previewOf fixture to match. usePreviewSubscribe's test answers over the real transport, so it observes the real parse, and its assertion still expected 1500n. --- .../account-ui/src/billing/usePreviewSubscribe.test.ts | 2 +- .../workspace/billing/sdk/billingSdkTestUtils.ts | 10 ++-------- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/packages/account-ui/src/billing/usePreviewSubscribe.test.ts b/packages/account-ui/src/billing/usePreviewSubscribe.test.ts index 83a570d871f..9e28f8373cc 100644 --- a/packages/account-ui/src/billing/usePreviewSubscribe.test.ts +++ b/packages/account-ui/src/billing/usePreviewSubscribe.test.ts @@ -54,7 +54,7 @@ describe('usePreviewSubscribe', () => { await quoting expect(preview.preview.value).toMatchObject({ - cost_today_cents: 1500n, + cost_today_cents: 1500, new_plan: { slug: 'pro_monthly' } }) expect(preview.loading.value).toBe(false) diff --git a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts index 41d1854edaf..9131d5ebdfd 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -61,15 +61,9 @@ export function pendingTopup( /** A subscribe the lifecycle is still driving, for the store's own effects. */ export function pendingSubscription( - overrides: Partial = {} + overrides: PendingOverrides = {} ): PendingBillingOperation { - return { - ...IDENTITY, - kind: 'subscription', - phase: 'pending', - customerActionSeen: false, - ...overrides - } + return pendingTopup({ kind: 'subscription', ...overrides }) } export function failedTopup( From 0bd7cce2ba945b9068329a615b7527b7a37e213e Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 00:47:10 -0400 Subject: [PATCH 06/15] docs(account-core): put the command-eligibility record where its pointer resolves (FE-2216) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The record landed in packages/account/docs/, a directory the account-core rename removed, while its only pointer — subscriptionCommands.ts:10's `../../../docs/billing-command-eligibility.md` — resolves to packages/account-core/docs/. Move the file to the path the pointer already names, so the module's one reference to why client-side eligibility was dropped leads somewhere and a cleanup of the stray directory cannot take the record with it. --- .../{account => account-core}/docs/billing-command-eligibility.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename packages/{account => account-core}/docs/billing-command-eligibility.md (100%) diff --git a/packages/account/docs/billing-command-eligibility.md b/packages/account-core/docs/billing-command-eligibility.md similarity index 100% rename from packages/account/docs/billing-command-eligibility.md rename to packages/account-core/docs/billing-command-eligibility.md From afe0fc9e9f92b4fe71245c46805eca0d826dbb02 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 01:54:45 -0400 Subject: [PATCH 07/15] fix(billing): show a declined plan change as a sentence, not a phase (FE-2216) projectSubscribeResult returned `new Error(`phase: ${phase}`)` for anything that settled short of succeeded, and showSubscribeError puts error.message straight into the toast detail (useSubscriptionCheckout.ts:1134-1140), so a declined card on a plan change read "phase: failed" to the customer. Cancel and resubscribe already went through projectUnsuccessfulSettle; subscribe is the one command the earlier fix missed. Routed through the same projection, so a decline carries the reason declineDetail localizes and every other terminal phase the generic sentence, with the phase still on WorkspaceApiError.code. Tests: projectSubscribeResult gains the succeeded row plus a failed/timed_out table in subscriptionOperationView.test.ts, and the rail suite's never-settled case now pins the localized sentence instead of 'phase: timed_out'. All three fail without the source change. --- .../sdk/subscriptionOperationView.test.ts | 45 +++++++++++++++++++ .../billing/sdk/subscriptionOperationView.ts | 2 +- ...eWorkspaceBilling.subscriptionRail.test.ts | 7 ++- 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts index bc8b29c3805..f5aa854e1d7 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts @@ -10,6 +10,7 @@ import { } from './billingSdkTestUtils' import { projectPaymentPortalResult, + projectSubscribeResult, projectSubscriptionResult } from './subscriptionOperationView' @@ -108,6 +109,50 @@ describe('projectSubscriptionResult', () => { }) }) +describe('projectSubscribeResult', () => { + it('hands back the operation the checkout reports as subscribed', () => { + expect( + projectSubscribeResult({ + status: 'ok', + value: { + phase: 'succeeded', + operation: settledOperation('succeeded', 'subscription') + } + }) + ).toEqual({ + status: 'ok', + value: { billing_op_id: 'op-1', status: 'subscribed' } + }) + }) + + it.for([ + { + phase: 'failed', + operation: failedOperation('subscription'), + detail: + 'Your bank declined this payment. Try another payment method or contact your bank.' + }, + { + phase: 'timed_out', + operation: settledOperation('timed_out', 'subscription'), + detail: "We couldn't update your subscription. Please try again." + } + ] as const)( + 'reports a $phase subscribe as a sentence for the customer', + ({ phase, operation, detail }) => { + const outcome = projectSubscribeResult({ + status: 'ok', + value: { phase, operation } + }) + + expect(outcome).toMatchObject({ status: 'error' }) + expect( + outcome.status === 'error' ? outcome.error : undefined + ).toMatchObject({ message: detail, code: phase }) + } + ) +}) + describe('projectPaymentPortalResult', () => { it('hands back the portal URL the host opens', () => { expect( diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts index 3d6d076d27f..2f508578632 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -140,7 +140,7 @@ export function projectSubscribeResult( if (result.status === 'error') return projectFailure(result) const { phase, operation } = result.value if (phase !== 'succeeded' || operation === undefined) { - return { status: 'error', error: new Error(`phase: ${phase}`) } + return projectUnsuccessfulSettle(result.value) } return { status: 'ok', diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index 175c4b55bc7..d6e30903de3 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -431,8 +431,11 @@ describe('subscribe on the billing SDK rail', () => { } }) - await expect(setupBilling().subscribe('pro-monthly')).rejects.toThrow( - 'phase: timed_out' + await expect(setupBilling().subscribe('pro-monthly')).rejects.toMatchObject( + { + message: "We couldn't update your subscription. Please try again.", + code: 'timed_out' + } ) expect(workspaceApi.subscribe).not.toHaveBeenCalled() }) From 0fba2ddbc63b4edac425522919608fe29db6f276 Mon Sep 17 00:00:00 2001 From: Dante Date: Thu, 17 Sep 2026 03:55:56 -0400 Subject: [PATCH 08/15] FE-2218 feat(billing): mint billing-web entries from the shared contract when the hosted destination says billing_web (#17860) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stacked on #17856 (base branch `jaewon/fe-2216-plan-change`) → #17853 → Rollout layer C (`hosted_billing_destination`, `stripe` | `billing_web`, PostHog at 100% `stripe`) decides where a hosted billing action lands. The plan says the host reads the flag, hands it to the SDK (#17783) and, when it says `billing_web`, mints a `/v1/` entry with `return_to` from `@comfyorg/billing-contract`, the one definition of that route surface (#17795); when it says `stripe`, the backend's URL is opened unchanged. Today the host only opens the bare billing-web origin from the user popover (#17716) with no intent and no `return_to`, and "Billing & invoices" in the settings panel always goes to the Stripe portal. This is the last un-opened code item before the Phase 7 host proof. - `src/platform/workspace/billing/hostedBillingRoutes.ts`: `hostedBillingRoute(destination, intent)` returns `{ kind: 'billing_web', url }` built by `buildBillingEntryUrl({ billingOrigin, intent, product: 'comfyui', returnTo: 'comfyui_workspace' })`, or `{ kind: 'provider' }` meaning "use the server's URL". The environment is derived, not hardcoded: the cloud base URL's hostname through the existing `resolveDeployEnv` map (`prod-v2 | stg-v2 | test-v2` → `production | staging | test`), which also classifies a local dev session by the backend it talks to. Fails closed to the provider on: no configured origin, an unknown backend family, a return target with no destination in that family, or an entry the contract refuses. A path-prefixed `VITE_BILLING_WEB_URL` keeps its prefix under the minted route. - Consumers: the popover's "Plans and pricing" mints the `pricing` intent (billing-web routes it to the subscription view; the in-app dialog stays the `stripe` behaviour and the popup-blocked fallback); `useWorkspaceBilling.manageSubscription()` mints `payment-methods` **before** either rail is consulted, so on `billing_web` no portal URL is requested on the SDK rail or the legacy one, and `openPortalWindow` + `refreshOnPortalReturn` still run so the return re-reads status, balance and capabilities. - Also fixed on the way: the popover treated a falsy `window.open(…, "noopener,noreferrer")` result as a blocked popup and showed the in-app pricing dialog as a fallback. Per the HTML spec `noopener` always returns `null`, so on `billing_web` the tab and the dialog opened together — a latent defect inherited from #17370 on `main`, caught by this PR's evidence run. The fallback is gone; the E2E `window.open` stub now returns `null` for `noopener` like a browser does, and a popover case covers both destinations. - Left on the provider on purpose: `useSubscriptionCheckout.recoverOutstandingPayment` and the `payment_method_url` steps inside an operation are mid-checkout provider steps, not hosted management; `invoices` and `result` are not served by billing-web yet (`ComingSoonView`), so nothing mints them; the legacy `/customers` rail's `accessBillingPortal` is being retired by the personal-billing flip and is not touched. - `@comfyorg/billing-contract` becomes a root `workspace:*` dependency. The CI cloud build for E2E (`.github/actions/build-cloud-frontend`, used only by `ci-tests-e2e.yaml` and `pr-update-playwright-expectations.yaml`, never by a deploy) gets `VITE_BILLING_WEB_URL=https://billing-web.example`, a reserved origin the spec stubs, reachable only when the server flag says `billing_web`. - No frontend-derived server state: the destination is the flag as-is; the host chooses only the URL shape. | AS-IS — `hosted_billing_destination: stripe` | TO-BE — `hosted_billing_destination: billing_web` | | --- | --- | | **1. User popover, "Plans and pricing" hovered**

Same menu item, unchanged by the flag. | **1. User popover, "Plans and pricing" hovered**

Same menu item, unchanged by the flag. | | **2. After clicking "Plans and pricing"**

In-app "Choose a Plan" dialog, no tab opened. | **2. After clicking "Plans and pricing"**

`billing-web.example/v1/pricing?product=comfyui&return_to=comfyui_workspace` tab opens and nothing else: `window.open` returns `null` under `noopener` as the spec requires, and no in-app dialog is left behind. | | **3. Settings ▸ Workspace ▸ Plan & Credits, before clicking "Billing & invoices"**

Identical panel; the destination is only read on click. | **3. Settings ▸ Workspace ▸ Plan & Credits, before clicking "Billing & invoices"**

Identical panel; the destination is only read on click. | | **4. After clicking "Billing & invoices"**

`POST /api/billing/payment-portal` recorded, and the URL it returned (`https://billing.example/portal`) opened. | **4. After clicking "Billing & invoices"**

No request to `/api/billing/payment-portal` on either rail; `billing-web.example/v1/payment-methods?product=comfyui&return_to=comfyui_workspace` minted and opened. | | **5. Return trip — refocusing the app tab after the hosted tab opened**

`/api/billing/status`, `/balance` and `/capabilities` re-read. | **5. Return trip — refocusing the app tab after the hosted tab opened**

Same three reads; `openPortalWindow` + `refreshOnPortalReturn` still run on the minted route. | - AS-IS (`stripe`, today's default): popover → in-app pricing dialog; settings → Stripe portal via `POST /billing/payment-portal`. - TO-BE (`billing_web`): popover → `/v1/pricing?product=comfyui&return_to=comfyui_workspace`; settings → `/v1/payment-methods?…`, no portal request on either rail; the app re-reads billing state on return. | Gate | Result | | --- | --- | | `vitest run src/platform/workspace src/composables/billing src/composables/useFeatureFlags src/config` | 91 files, 1890 tests (19 new route cases: intent × destination × env × prefix × each fail-closed branch; 3 new adapter cases; 3 popover cases re-pointed) | | `packages/billing-contract` vitest | 3 files, 62 tests | | `pnpm typecheck`, `typecheck:browser`, `lint`, `format`, `knip` | exit 0 | | `fallow audit --changed-since origin/jaewon/fe-2216-plan-change` | no issues in 10 changed files | | `PLAYWRIGHT_TEST_URL=http://localhost:5431 pnpm exec playwright test --project=cloud browser_tests/tests/dialogs/hostedBillingDestination.spec.ts --reporter=list`, against `VITE_BILLING_WEB_URL=https://billing-web.example pnpm dev:cloud` | `4 passed (4.6s)` — settings on both destinations, plus the two new avatar-menu cases: `opens the in-app pricing table from the avatar menu while the destination is stripe` and `opens the billing-web pricing entry alone from the avatar menu while the destination is billing_web` | Billing SDK track FE-2210 ([implementation plan V2](https://app.notion.com/p/3d86d73d36508152b92cdbdfdfe83ac8)). Hybrid model: top-up in-app, subscription management / invoices / payment methods on the hosted billing app. | Phase | Item | Ticket | Status | | --- | --- | --- | --- | | 1-2 | Session core, transport, readers | FE-2211/2212/2213 | merged | | 3 | Operation lifecycle, commands, eight-state projection | FE-2227/2214/2223 | merged (#17655) | | 4 | `@comfyorg/account-ui` composables + `CheckoutSteps` | FE-2215 | merged (#17662, #17663) | | 5 slice 1 | Top-up through the SDK behind `billing_sdk_topup_enabled` | FE-2216 | merged (#17665) | | rollout C | `hosted_billing_destination` server flag read by the host | FE-2218 | merged (#17716) | | rollout C | `hostedDestination` port on the lifecycle, value on operation state | FE-2210/2218 | #17783 (review) | | 7 prep | Scope-source port + credentialed transport (BFF / cookie hosts) | FE-2218 | merged (#17782) | | 7 prep | `@comfyorg/account` → `@comfyorg/account-core` rename | FE-2218 | #17851 (review) | | 7 prep | `billing-contract` route builder + `return_to` registry | FE-2218 | merged (#17795) | | 3A-3 | Workshop adapter over `createHostedTopupCheckout` | FE-2214 | merged (#17793) | | 8 core | `previewSubscribe` command | FE-2331 | merged (#17797) | | 8 core | Plans + saved payment-methods readers | FE-2331 | merged (#17798) | | 8 ui | account-ui composables (`usePlans`, `usePaymentMethods`, `usePreviewSubscribe`) | FE-2331 | merged (#17798) | | 7 | billing-web own-origin session, sign-in, SDK composition | FE-2218 | merged (#17798) | | 7 | billing-web unit tests in CI (`ci-billing-web-unit.yaml`) | FE-2218 | merged (#17827, #17844) | | 7 | ingest CORS + top-up return hosts for billing.comfy.org and its previews (Comfy-Org/cloud) | FE-2218 | merged (Comfy-Org/cloud#9512) | | 8 ui | billing-web `/v1` entry routing + subscription / payment-method surfaces | FE-2331 | merged (#17798) | | 7 | npm publish (`ingest-types`, `account-core`, `billing-contract`), Platform install, billing-web live top-up | FE-2218 | todo | | 6 | Contract tests per generated schema (package layer) | FE-2217 | | 6 | Live E2E per flow × consumer + evidence table | FE-2217 | todo (needs staging flags) | | 5 slice 2a | Cancel, resubscribe and payment portal through the SDK behind `billing_sdk_subscription_enabled` | FE-2216 | #17853 (review) | | 5 slice 2b | Subscribe and plan change through the SDK, priced by the server | FE-2216 | #17856 (review; parent of this PR) | | 7 / rollout C | Host mints billing-web `/v1/` entries with `return_to` when `hosted_billing_destination` is `billing_web` | FE-2218 | **this PR** | | follow-up | One `needsCustomerAttention` predicate (from the #17665 review) | FE-2216 | merged (#17792) | | follow-up | Opaque `BillingServerCode` (from the #17656 review) | FE-2227 | merged (#17794) | | follow-up | `useCredits` clears on `SUPERSEDED` (from the #17799 review) | FE-2215 | merged (#17824) | | follow-up | credits / status / capabilities readers fence a late failure as `SUPERSEDED` (from the #17798 review) | FE-2331 | merged (#17828) | ```mermaid flowchart LR P3["Phase 3 core lifecycle (merged)"] P4["Phase 4 account-ui (merged)"] P5["Phase 5 slice 1 top-up flag (merged)"] FC["PR 17716 hosted_billing_destination flag (merged)"] HD["PR 17783 hostedDestination port"] SS["PR 17782 scope-source port + credentialed transport"] RN["account-core rename"] RB["billing-contract route builder + return_to"] WS["Workshop adapter"] P8PV["previewSubscribe command"] P8RD["plans + payment-methods readers"] P8["account-ui hosted composables"] BWS["billing-web session + sign-in"] BWV["billing-web /v1 surfaces"] CORS["cloud PR 9512 ingest CORS + return hosts"] PUB["npm publish account-core / billing-contract"] P7["Phase 7 host proof: Platform + billing-web live"] P6C["Phase 6 contract tests"] P6["Phase 6 live evidence"] S2A["PR 17853 slice 2a cancel / resubscribe / portal rail"] S2B["PR 17856 slice 2b subscribe + plan change"] LC["Layer C: host mints billing-web entries"] FU9["customer-attention predicate"] FU11["opaque BillingServerCode"] FU12["useCredits clears on SUPERSEDED"] FU13["reader late-failure fence"] P3 --> HD FC --> HD HD --> RB P3 --> SS SS --> P7 RB --> P7 P3 --> RN RN --> PUB RB --> PUB PUB --> P7 P3 --> P8PV P3 --> P8RD P8PV --> P8 P8RD --> P8 P4 --> P8 P8 --> S2B HD --> S2A S2A --> S2B S2B --> LC RB --> LC HD --> LC LC --> P7 P8 --> BWS BWS --> BWV RB --> BWV BWV --> P7 CORS --> P7 P5 --> P6 P3 --> P6C P5 --> WS P5 --> FU9 P3 --> FU11 P4 --> FU12 P3 --> FU13 style P3 fill:#d4edda,stroke:#155724 style P4 fill:#d4edda,stroke:#155724 style P5 fill:#d4edda,stroke:#155724 style FC fill:#d4edda,stroke:#155724 style SS fill:#d4edda,stroke:#155724 style RB fill:#d4edda,stroke:#155724 style WS fill:#d4edda,stroke:#155724 style FU9 fill:#d4edda,stroke:#155724 style BWV fill:#d4edda,stroke:#155724 style BWS fill:#d4edda,stroke:#155724 style P8 fill:#d4edda,stroke:#155724 style P8RD fill:#d4edda,stroke:#155724 style CORS fill:#d4edda,stroke:#155724 style FU13 fill:#d4edda,stroke:#155724 style FU12 fill:#d4edda,stroke:#155724 style FU11 fill:#d4edda,stroke:#155724 style P8PV fill:#d4edda,stroke:#155724 style LC stroke:#0366d6,stroke-width:4px ``` --- .../actions/build-cloud-frontend/action.yaml | 5 + .../dialogs/hostedBillingDestination.spec.ts | 246 ++++++++++++++++++ package.json | 1 + pnpm-lock.yaml | 3 + src/platform/telemetry/initDatadogRum.ts | 6 +- .../billing/hostedBillingRoutes.test.ts | 112 ++++++++ .../workspace/billing/hostedBillingRoutes.ts | 97 +++++++ .../CurrentUserPopoverWorkspace.test.ts | 43 ++- .../CurrentUserPopoverWorkspace.vue | 12 +- .../composables/useWorkspaceBilling.test.ts | 91 +++++++ .../composables/useWorkspaceBilling.ts | 16 ++ 11 files changed, 598 insertions(+), 34 deletions(-) create mode 100644 browser_tests/tests/dialogs/hostedBillingDestination.spec.ts create mode 100644 src/platform/workspace/billing/hostedBillingRoutes.test.ts create mode 100644 src/platform/workspace/billing/hostedBillingRoutes.ts diff --git a/.github/actions/build-cloud-frontend/action.yaml b/.github/actions/build-cloud-frontend/action.yaml index a13eeb36de6..77b8c2c24bc 100644 --- a/.github/actions/build-cloud-frontend/action.yaml +++ b/.github/actions/build-cloud-frontend/action.yaml @@ -18,6 +18,11 @@ runs: run: pnpm build:cloud env: VITE_USE_LEGACY_DEFAULT_GRAPH: 'true' + # A reserved origin the e2e suite stubs, so the hosted billing + # destination has somewhere to mint to. Reachable only when the server + # flag says billing_web, which no deployment default does. + # browser_tests/tests/dialogs/hostedBillingDestination.spec.ts pins it. + VITE_BILLING_WEB_URL: 'https://billing-web.example' - name: Verify cloud frontend shell: bash diff --git a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts new file mode 100644 index 00000000000..1afb0303a6a --- /dev/null +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -0,0 +1,246 @@ +import { expect } from '@playwright/test' +import type { Page, Request } from '@playwright/test' + +import type { RemoteConfig } from '@/platform/remoteConfig/types' +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' + +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { createWorkspaceBillingCapabilities } from '@e2e/fixtures/data/billingCapabilities' +import { mockSystemStats } from '@e2e/fixtures/data/systemStats' +import { CloudAuthHelper } from '@e2e/fixtures/helpers/CloudAuthHelper' +import { FeatureFlagHelper } from '@e2e/fixtures/helpers/FeatureFlagHelper' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { + mockWorkspaceTokenMint, + workspace +} from '@e2e/fixtures/utils/workspaceMocks' + +/** + * Hosted billing destination — FE-2218, Layer C of the billing rollout. + * + * `hosted_billing_destination` decides where Billing & invoices and Plans and + * pricing land, and nothing else does: on `stripe` the app opens the URL + * `/billing/payment-portal` handed back and shows the in-app pricing table, on + * `billing_web` it mints the contract's `/v1/payment-methods` and `/v1/pricing` + * entries and never asks the server for a portal link. + * + * Drives a raw `page` so the cloud app boots against fully mocked endpoints, + * the same pattern as creditsTile.spec.ts. + * + * The hosted origin is baked in at build time. `.github/actions/build-cloud-frontend` + * supplies the value below; a locally served build needs the same + * `VITE_BILLING_WEB_URL`, or the hosted case falls back to the provider page. + */ +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' + +const BILLING_WEB_ORIGIN = 'https://billing-web.example' +const PROVIDER_PORTAL_URL = 'https://billing.example/portal' + +const ACTIVE_BILLING_STATUS: BillingStatusResponse = { + is_active: true, + max_seats: 1, + occupied_seats: 1, + team_credit_stop: null, + scheduled_change: null, + subscription_tier: 'PRO', + subscription_duration: 'MONTHLY', + plan_slug: 'pro-monthly', + billing_status: 'paid', + renewal_date: '2099-02-20T12:00:00Z', + has_funds: true +} + +/** Every request the app made for a provider portal URL, in order. */ +async function mockCloudBoot(page: Page): Promise { + const portalRequests: Request[] = [] + + await page.route('**/api/features', (r) => + r.fulfill( + jsonRoute({ billing_control_enabled: true } satisfies RemoteConfig) + ) + ) + await page.route('**/api/system_stats', (r) => + r.fulfill(jsonRoute(mockSystemStats)) + ) + await page.route('**/api/users', (r) => + r.fulfill( + jsonRoute({ + storage: 'server', + migrated: true, + users: { 'test-user-e2e': 'E2E Test User' } + }) + ) + ) + // TutorialCompleted suppresses the new-user template browser, whose modal + // overlay would otherwise intercept the Settings click. + await page.route('**/api/settings', (r) => + r.fulfill(jsonRoute({ 'Comfy.TutorialCompleted': true })) + ) + await page.route('**/api/userdata**', (r) => r.fulfill(jsonRoute([]))) + await page.route('**/api/extensions', (r) => r.fulfill(jsonRoute([]))) + await page.route('**/api/object_info', (r) => r.fulfill(jsonRoute({}))) + await page.route('**/api/global_subgraphs', (r) => r.fulfill(jsonRoute({}))) + await page.route('**/api/i18n', (r) => r.fulfill(jsonRoute({}))) + await page.route('**/api/auth/session', (r) => + r.fulfill(jsonRoute({ token: 'mock-workspace-token' })) + ) + await page.route('**/releases**', (r) => r.fulfill(jsonRoute([]))) + await mockWorkspaceTokenMint(page, workspace('personal', 'owner')) + await page.route('**/api/workspaces', (r) => + r.fulfill(jsonRoute({ workspaces: [workspace('personal', 'owner')] })) + ) + + await page.route('**/api/billing/status', (r) => + r.fulfill(jsonRoute(ACTIVE_BILLING_STATUS)) + ) + await page.route('**/api/billing/balance', (r) => + r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) + ) + await page.route('**/customers/balance', (r) => + r.fulfill(jsonRoute({ amount_micros: 6000, currency: 'usd' })) + ) + await page.route('**/api/billing/plans', (r) => + r.fulfill(jsonRoute({ plans: [] })) + ) + await page.route('**/api/billing/capabilities', (r) => { + if (r.request().method() !== 'GET') return r.fallback() + return r.fulfill( + jsonRoute( + createWorkspaceBillingCapabilities(workspace('personal', 'owner')) + ) + ) + }) + await page.route('**/api/billing/payment-portal', (r) => { + portalRequests.push(r.request()) + return r.fulfill(jsonRoute({ url: PROVIDER_PORTAL_URL })) + }) + + return portalRequests +} + +async function bootApp(page: Page) { + await new CloudAuthHelper(page).mockAuth() + await page.addInitScript(() => { + localStorage.setItem('Comfy.userId', 'test-user-e2e') + // Records the destination instead of opening a tab the test would have to + // dismiss. The handle follows the spec: a `noopener` open always yields + // null, while a plain one returns a window and keeps the app's + // portal-return refresh armed. + window.open = (url, _target, features) => { + document.documentElement.dataset.openedUrl = String(url) + return (features ?? '').includes('noopener') ? null : window + } + }) + await page.goto(APP_URL) + await page.waitForFunction(() => !!window.app?.extensionManager, null, { + timeout: 45_000 + }) +} + +/** Settings ▸ Workspace ▸ Plan & Credits, where Billing & invoices lives. */ +async function openPlanAndCredits(page: Page) { + await page + .getByRole('button', { name: /^Settings/ }) + .first() + .click() + const dialog = page.getByTestId('settings-dialog') + await expect(dialog).toBeVisible() + await dialog + .locator('nav') + .getByRole('button', { name: 'Plan & Credits' }) + .click() + + return dialog.getByRole('main') +} + +function openedUrl(page: Page) { + return page.locator('html').getAttribute('data-opened-url') +} + +/** The avatar menu's Plans and pricing entry. */ +async function clickPlansAndPricing(page: Page) { + await page.getByRole('button', { name: 'Current user' }).click() + await page.getByTestId('plans-pricing-menu-item').click() +} + +const pricingHeading = (page: Page) => + page.getByRole('heading', { name: 'Choose a Plan' }) + +/** + * The in-app pricing dialog's frame. Pushed synchronously by the click + * handler, unlike its lazily imported contents, so its absence right after + * the handler ran is a settled answer rather than a race. + */ +const pricingDialog = (page: Page) => + page.locator('[data-dialog-key="subscription-required"]') + +test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { + test('opens the provider portal while the destination is stripe', async ({ + page + }) => { + test.setTimeout(60_000) + const portalRequests = await mockCloudBoot(page) + await bootApp(page) + + const content = await openPlanAndCredits(page) + await content.getByRole('button', { name: 'Billing & invoices' }).click() + + await expect.poll(() => openedUrl(page)).toBe(PROVIDER_PORTAL_URL) + expect(portalRequests).toHaveLength(1) + }) + + test('mints the billing-web payment-methods entry while the destination is billing_web', async ({ + page + }) => { + test.setTimeout(60_000) + const portalRequests = await mockCloudBoot(page) + await bootApp(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + hosted_billing_destination: 'billing_web' + }) + + const content = await openPlanAndCredits(page) + await content.getByRole('button', { name: 'Billing & invoices' }).click() + + await expect + .poll(() => openedUrl(page)) + .toBe( + `${BILLING_WEB_ORIGIN}/v1/payment-methods?product=comfyui&return_to=comfyui_workspace` + ) + expect(portalRequests).toHaveLength(0) + }) + + test('opens the in-app pricing table from the avatar menu while the destination is stripe', async ({ + page + }) => { + test.setTimeout(60_000) + await mockCloudBoot(page) + await bootApp(page) + + await clickPlansAndPricing(page) + + await expect(pricingHeading(page)).toBeVisible() + expect(await openedUrl(page)).toBeNull() + }) + + test('opens the billing-web pricing entry alone from the avatar menu while the destination is billing_web', async ({ + page + }) => { + test.setTimeout(60_000) + await mockCloudBoot(page) + await bootApp(page) + await new FeatureFlagHelper(page).setServerFlagsPersistent({ + hosted_billing_destination: 'billing_web' + }) + + await clickPlansAndPricing(page) + + await expect + .poll(() => openedUrl(page)) + .toBe( + `${BILLING_WEB_ORIGIN}/v1/pricing?product=comfyui&return_to=comfyui_workspace` + ) + await expect(pricingDialog(page)).toHaveCount(0) + await expect(pricingHeading(page)).toBeHidden() + }) +}) diff --git a/package.json b/package.json index 80599969d9b..c0297b0d51f 100644 --- a/package.json +++ b/package.json @@ -96,6 +96,7 @@ "@atlaskit/pragmatic-drag-and-drop": "^1.3.1", "@comfyorg/account-core": "workspace:*", "@comfyorg/account-ui": "workspace:*", + "@comfyorg/billing-contract": "workspace:*", "@comfyorg/comfy-multi-player": "0.2.1", "@comfyorg/comfyui-desktop-bridge-types": "catalog:", "@comfyorg/comfyui-electron-types": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 277fc3d39af..bcd6ff897e0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -503,6 +503,9 @@ importers: '@comfyorg/account-ui': specifier: workspace:* version: link:packages/account-ui + '@comfyorg/billing-contract': + specifier: workspace:* + version: link:packages/billing-contract '@comfyorg/comfy-multi-player': specifier: 0.2.1 version: 0.2.1 diff --git a/src/platform/telemetry/initDatadogRum.ts b/src/platform/telemetry/initDatadogRum.ts index 48f077aa1f7..19b2fabec1e 100644 --- a/src/platform/telemetry/initDatadogRum.ts +++ b/src/platform/telemetry/initDatadogRum.ts @@ -4,7 +4,9 @@ import { datadogRum } from '@datadog/browser-rum' import { rumBeforeSend } from './datadogRumBeforeSend' import { trackUserManualRefresh } from './manualRefreshTracker' -const DATADOG_ENV_BY_HOSTNAME = new Map([ +export type DeployEnv = 'prod-v2' | 'stg-v2' | 'test-v2' + +const DATADOG_ENV_BY_HOSTNAME = new Map([ ['cloud.comfy.org', 'prod-v2'], ['stagingcloud.comfy.org', 'stg-v2'], ['testcloud.comfy.org', 'test-v2'] @@ -63,7 +65,7 @@ async function initializeDatadogRum(env: string): Promise { */ export function resolveDeployEnv( hostname = window.location.hostname -): string | undefined { +): DeployEnv | undefined { return ( DATADOG_ENV_BY_HOSTNAME.get(hostname) ?? (hostname.endsWith('.testenvs.comfy.org') ? 'test-v2' : undefined) diff --git a/src/platform/workspace/billing/hostedBillingRoutes.test.ts b/src/platform/workspace/billing/hostedBillingRoutes.test.ts new file mode 100644 index 00000000000..301405cf600 --- /dev/null +++ b/src/platform/workspace/billing/hostedBillingRoutes.test.ts @@ -0,0 +1,112 @@ +import type { + BillingEnvironment, + BillingIntent +} from '@comfyorg/billing-contract' + +import { hostedBillingRoute } from './hostedBillingRoutes' + +const cloudBaseUrl = vi.hoisted(() => ({ + value: 'https://testcloud.comfy.org' +})) + +vi.mock(import('@/config/comfyApi'), () => ({ + getComfyCloudBaseUrl: () => cloudBaseUrl.value +})) + +const BILLING_WEB = new URL('https://billing.comfy.org') + +function entryUrl( + intent: BillingIntent, + environment: BillingEnvironment = 'production', + base: URL = BILLING_WEB +): string | undefined { + const route = hostedBillingRoute('billing_web', intent, base, environment) + return route.kind === 'billing_web' ? route.url.href : undefined +} + +describe('hostedBillingRoute', () => { + beforeEach(() => { + cloudBaseUrl.value = 'https://testcloud.comfy.org' + }) + + it.for([ + ['pricing', 'https://billing.comfy.org/v1/pricing'], + ['subscription', 'https://billing.comfy.org/v1/subscription'], + ['payment-methods', 'https://billing.comfy.org/v1/payment-methods'], + ['checkout', 'https://billing.comfy.org/v1/checkout'] + ] as const)('mints %s at its contract route', ([intent, path]) => { + expect(entryUrl(intent)).toBe( + `${path}?product=comfyui&return_to=comfyui_workspace` + ) + }) + + it.for(['production', 'staging', 'test'] as const)( + 'mints the same workspace return in %s', + (environment) => { + expect(entryUrl('payment-methods', environment)).toContain( + 'return_to=comfyui_workspace' + ) + } + ) + + it.for([ + ['https://billing.comfy.org/billing/', '/billing/v1/pricing'], + ['https://billing.comfy.org/app', '/app/v1/pricing'], + ['https://billing.comfy.org/', '/v1/pricing'] + ] as const)('serves %s beneath its own path prefix', ([base, path]) => { + expect(entryUrl('pricing', 'production', new URL(base))).toBe( + `https://billing.comfy.org${path}?product=comfyui&return_to=comfyui_workspace` + ) + }) + + it.for(['pricing', 'subscription', 'payment-methods'] as const)( + 'leaves %s on the provider while the server says stripe', + (intent) => { + expect( + hostedBillingRoute('stripe', intent, BILLING_WEB, 'production') + ).toEqual({ kind: 'provider' }) + } + ) + + it('stays on the provider when no billing-web origin is configured', () => { + expect( + hostedBillingRoute('billing_web', 'pricing', null, 'production') + ).toEqual({ kind: 'provider' }) + }) + + it('stays on the provider when the contract refuses the origin', () => { + expect( + hostedBillingRoute( + 'billing_web', + 'pricing', + new URL('http://billing.example.com'), + 'production' + ) + ).toEqual({ kind: 'provider' }) + }) + + it.for([ + 'https://cloud.comfy.org', + 'https://stagingcloud.comfy.org', + 'https://testcloud.comfy.org' + ] as const)('mints an entry for the %s backend', (baseUrl) => { + cloudBaseUrl.value = baseUrl + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + + expect(hostedBillingRoute('billing_web', 'pricing')).toEqual({ + kind: 'billing_web', + url: new URL( + 'https://billing.comfy.org/v1/pricing?product=comfyui&return_to=comfyui_workspace' + ) + }) + }) + + it('stays on the provider for a backend outside the known families', () => { + cloudBaseUrl.value = 'https://cloud.example.com' + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + + expect(hostedBillingRoute('billing_web', 'pricing')).toEqual({ + kind: 'provider' + }) + }) +}) diff --git a/src/platform/workspace/billing/hostedBillingRoutes.ts b/src/platform/workspace/billing/hostedBillingRoutes.ts new file mode 100644 index 00000000000..55f83bb0314 --- /dev/null +++ b/src/platform/workspace/billing/hostedBillingRoutes.ts @@ -0,0 +1,97 @@ +/** + * Layer C of the billing rollout: which origin a hosted billing action opens. + * + * The server decides, through `hosted_billing_destination`. `stripe` means the + * URL the backend already handed back — `action_url`, `payment_method_url`, a + * portal link — is opened unchanged, so the host never composes a provider + * URL of its own. `billing_web` means the host mints a `/v1/` entry + * from `@comfyorg/billing-contract`, the one definition of that route surface. + * + * Every hosted surface reads the same flag, so they flip together and stay + * independent of Layer A: whether an action reached here over the SDK rail or + * the legacy client says nothing about where it should land. + * + * Anything unresolved fails closed to the provider — no configured billing-web + * origin, an environment whose return target has no destination, an entry the + * contract refuses to build. A customer on the provider page is served; one on + * an origin nobody hosts, or with no way back, is stranded. + */ +import type { + BillingEnvironment, + BillingIntent, + ReturnTarget +} from '@comfyorg/billing-contract' +import { + buildBillingEntryUrl, + resolveReturnTarget +} from '@comfyorg/billing-contract' + +import type { HostedBillingDestination } from '@/config/billingWeb' +import { getBillingWebUrl } from '@/config/billingWeb' +import { getComfyCloudBaseUrl } from '@/config/comfyApi' +import type { DeployEnv } from '@/platform/telemetry/initDatadogRum' +import { resolveDeployEnv } from '@/platform/telemetry/initDatadogRum' + +export type HostedBillingRoute = + | { readonly kind: 'billing_web'; readonly url: URL } + | { readonly kind: 'provider' } + +const PROVIDER: HostedBillingRoute = { kind: 'provider' } + +const PRODUCT = 'comfyui' +const RETURN_TO: ReturnTarget = 'comfyui_workspace' + +const BILLING_ENVIRONMENT_BY_DEPLOY_ENV: Readonly< + Record +> = { + 'prod-v2': 'production', + 'stg-v2': 'staging', + 'test-v2': 'test' +} + +/** + * The family the session was minted against, not the label on this build: a + * developer running the frontend locally still talks to a deployed backend, + * so the cloud base URL classifies the trip and `window.location` cannot. + */ +function hostBillingEnvironment( + cloudBaseUrl = getComfyCloudBaseUrl() +): BillingEnvironment | undefined { + const deployEnv = resolveDeployEnv(new URL(cloudBaseUrl).hostname) + return deployEnv === undefined + ? undefined + : BILLING_ENVIRONMENT_BY_DEPLOY_ENV[deployEnv] +} + +/** + * Re-bases a contract route under the configured billing-web path, which the + * builder drops because an entry URL is only ever routing input. A prefixed + * deployment (`https://host/billing/`) serves `/v1/` beneath its own + * prefix, so the origin alone would point at nothing. + */ +function underBase(base: URL, entry: URL): URL { + const prefix = base.pathname.replace(/\/$/, '') + return new URL(`${prefix}${entry.pathname}${entry.search}`, base.origin) +} + +export function hostedBillingRoute( + destination: HostedBillingDestination, + intent: BillingIntent, + billingWebBase: URL | null = getBillingWebUrl(), + environment: BillingEnvironment | undefined = hostBillingEnvironment() +): HostedBillingRoute { + if (destination !== 'billing_web' || !billingWebBase) return PROVIDER + if (!environment || !resolveReturnTarget(RETURN_TO, environment)) { + return PROVIDER + } + + const entry = buildBillingEntryUrl({ + billingOrigin: billingWebBase, + intent, + product: PRODUCT, + returnTo: RETURN_TO + }) + return entry.status === 'ok' + ? { kind: 'billing_web', url: underBase(billingWebBase, entry.url) } + : PROVIDER +} diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index 4376f0dc8e1..ed63de7cdd6 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -35,7 +35,7 @@ const state = vi.hoisted(() => { canReactivatePlan: false, canOpenPricingSurface: false, shouldUseWorkspaceBilling: true, - hostedBillingWebEnabled: false, + hostedBillingDestination: 'stripe', billingWebUrl: initialBillingWebUrl(), showCreateWorkspaceDialog: vi.fn(), showTopUpCreditsDialog: vi.fn(), @@ -132,8 +132,8 @@ vi.mock(import('@/platform/telemetry')) vi.mock(import('@/composables/useFeatureFlags'), () => ({ useFeatureFlags: () => ({ flags: { - get hostedBillingWebEnabled() { - return state.hostedBillingWebEnabled + get hostedBillingDestination() { + return state.hostedBillingDestination } } }) @@ -143,6 +143,11 @@ vi.mock(import('@/config/billingWeb'), () => ({ getBillingWebUrl: () => state.billingWebUrl })) +// Pins the billing family the hosted route derives; an unmapped one fails closed to the provider. +vi.mock(import('@/config/comfyApi'), () => ({ + getComfyCloudBaseUrl: () => 'https://testcloud.comfy.org' +})) + const WorkspaceSwitcherPopoverStub = defineComponent({ emits: ['select', 'create'], template: ` @@ -210,7 +215,7 @@ describe('CurrentUserPopoverWorkspace', () => { state.canOpenPricingSurface = false state.canReactivate = false state.shouldUseWorkspaceBilling = true - state.hostedBillingWebEnabled = false + state.hostedBillingDestination = 'stripe' state.billingWebUrl = new URL('http://localhost:5174') }) @@ -320,6 +325,7 @@ describe('CurrentUserPopoverWorkspace', () => { it('keeps Plans & pricing in-app when hosted billing is disabled', async () => { const user = userEvent.setup() + const open = vi.spyOn(window, 'open').mockReturnValue(null) state.canOpenPricingSurface = true renderComponent('team') @@ -328,45 +334,32 @@ describe('CurrentUserPopoverWorkspace', () => { expect(state.showPricingTable).toHaveBeenCalledWith({ reason: 'avatar_menu_plans' }) + expect(open).not.toHaveBeenCalled() }) - it('opens hosted billing when its feature flag is enabled', async () => { + it('opens hosted billing alone when its feature flag is enabled', async () => { const user = userEvent.setup() - const open = vi.spyOn(window, 'open').mockReturnValue(window) + const open = vi.spyOn(window, 'open').mockReturnValue(null) state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' renderComponent('team') await user.click(screen.getByTestId('plans-pricing-menu-item')) + expect(open).toHaveBeenCalledOnce() expect(open).toHaveBeenCalledWith( - 'http://localhost:5174/', + 'http://localhost:5174/v1/pricing?product=comfyui&return_to=comfyui_workspace', '_blank', 'noopener,noreferrer' ) expect(state.showPricingTable).not.toHaveBeenCalled() }) - it('keeps Plans & pricing in-app when the hosted tab is blocked', async () => { - const user = userEvent.setup() - const open = vi.spyOn(window, 'open').mockReturnValue(null) - state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true - renderComponent('team') - - await user.click(screen.getByTestId('plans-pricing-menu-item')) - - expect(open).toHaveBeenCalledOnce() - expect(state.showPricingTable).toHaveBeenCalledWith({ - reason: 'avatar_menu_plans' - }) - }) - it('keeps Plans & pricing in-app when the hosted URL is unavailable', async () => { const user = userEvent.setup() const open = vi.spyOn(window, 'open').mockImplementation(() => null) state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' state.billingWebUrl = null renderComponent('team') @@ -623,7 +616,7 @@ describe('CurrentUserPopoverWorkspace', () => { state.canManageSubscriptionLifecycle = true state.canReactivatePlan = true state.canOpenPricingSurface = true - state.hostedBillingWebEnabled = true + state.hostedBillingDestination = 'billing_web' renderComponent('team') expect(screen.getByTestId('add-credits-button')).toBeInTheDocument() diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index fc243434fc9..859d23b3bc5 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -267,11 +267,11 @@ import { useCurrentUser } from '@/composables/auth/useCurrentUser' import { useExternalLink } from '@/composables/useExternalLink' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useBillingContext } from '@/composables/billing/useBillingContext' -import { getBillingWebUrl } from '@/config/billingWeb' import SubscribeButton from '@/platform/cloud/subscription/components/SubscribeButton.vue' import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' +import { hostedBillingRoute } from '@/platform/workspace/billing/hostedBillingRoutes' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -393,12 +393,10 @@ const handleOpenWorkspaceSettings = () => { } const handleOpenPlansAndPricing = () => { - const billingWebUrl = getBillingWebUrl() - const hostedTab = - flags.hostedBillingWebEnabled && billingWebUrl - ? window.open(billingWebUrl.href, '_blank', 'noopener,noreferrer') - : null - if (!hostedTab) { + const route = hostedBillingRoute(flags.hostedBillingDestination, 'pricing') + if (route.kind === 'billing_web') { + window.open(route.url.href, '_blank', 'noopener,noreferrer') + } else { subscriptionDialog.showPricingTable({ reason: 'avatar_menu_plans' }) } emit('close') diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 64abb06bb4e..2e207772b81 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -85,8 +85,25 @@ vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError: mockReportError })) +const mockRail = vi.hoisted(() => ({ + enabled: false, + openPaymentPortal: vi.fn() +})) + +vi.mock( + import('@/platform/workspace/composables/useSubscriptionRail'), + () => ({ + useSubscriptionRail: () => (mockRail.enabled ? mockRail : null) + }) +) + vi.mock(import('@/platform/telemetry')) +// Pins the billing family the hosted route derives; an unmapped one fails closed to the provider. +vi.mock(import('@/config/comfyApi'), () => ({ + getComfyCloudBaseUrl: () => 'https://testcloud.comfy.org' +})) + let scope: ReturnType | undefined function setupBilling() { @@ -843,6 +860,8 @@ describe('useWorkspaceBilling', () => { }) afterEach(() => { + mockRail.enabled = false + localStorage.clear() Object.defineProperty(window, 'location', { configurable: true, writable: true, @@ -887,6 +906,78 @@ describe('useWorkspaceBilling', () => { expect(openSpy).not.toHaveBeenCalled() }) + // Layer C is independent of Layer A: the destination decides the URL, so + // neither rail is asked for a portal link the customer will not open. + it.for([ + ['the legacy client', false], + ['the SDK rail', true] + ] as const)( + 'opens the hosted payment-methods route on %s', + async ([, railEnabled]) => { + const openSpy = vi.fn(() => window) + vi.stubGlobal('open', openSpy) + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + localStorage.setItem('ff:hosted_billing_destination', '"billing_web"') + mockRail.enabled = railEnabled + + const billing = setupBilling() + await billing.manageSubscription() + + expect(openSpy).toHaveBeenCalledWith( + 'https://billing.comfy.org/v1/payment-methods?product=comfyui&return_to=comfyui_workspace', + '_blank' + ) + expect(mockWorkspaceApi.getPaymentPortalUrl).not.toHaveBeenCalled() + expect(mockRail.openPaymentPortal).not.toHaveBeenCalled() + + mockWorkspaceApi.getBillingStatus.mockClear() + document.dispatchEvent(new Event('visibilitychange')) + expect(mockWorkspaceApi.getBillingStatus).toHaveBeenCalledTimes(1) + } + ) + + it('clears a failure from the previous attempt when the hosted route opens', async () => { + vi.stubGlobal( + 'open', + vi.fn(() => window) + ) + localStorage.setItem('ff:hosted_billing_destination', '"billing_web"') + mockWorkspaceApi.getPaymentPortalUrl.mockRejectedValue( + new Error('portal down') + ) + + const billing = setupBilling() + await expect(billing.manageSubscription()).rejects.toThrow('portal down') + expect(billing.error.value).toBe('portal down') + + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + await billing.manageSubscription() + + expect(billing.error.value).toBeNull() + }) + + it('opens the portal URL the SDK rail returns while the server says stripe', async () => { + const openSpy = vi.fn(() => window) + vi.stubGlobal('open', openSpy) + mockRail.enabled = true + mockRail.openPaymentPortal.mockResolvedValue({ + status: 'ok', + value: 'https://billing.example/sdk-portal' + }) + + const billing = setupBilling() + await billing.manageSubscription() + + expect(mockRail.openPaymentPortal).toHaveBeenCalledWith( + 'https://app.example/settings' + ) + expect(openSpy).toHaveBeenCalledWith( + 'https://billing.example/sdk-portal', + '_blank' + ) + expect(mockWorkspaceApi.getPaymentPortalUrl).not.toHaveBeenCalled() + }) + it('records error when API call fails', async () => { mockWorkspaceApi.getPaymentPortalUrl.mockRejectedValue( new Error('portal down') diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 461b29ea0a9..e870df5af1a 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -32,6 +32,7 @@ import { WorkspaceApiError, workspaceApi } from '@/platform/workspace/api/workspaceApi' +import { hostedBillingRoute } from '@/platform/workspace/billing/hostedBillingRoutes' import { useBillingSdkStore } from '@/platform/workspace/billing/sdk/billingSdkStore' import type { SubscriptionRailOutcome } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' @@ -533,11 +534,26 @@ export function useWorkspaceBilling(): BillingState & BillingActions { } function openPortalWindow(url: string): void { + // The handle arms the return refresh, so adding `noopener` here (which + // nulls it) silently stops billing state from re-reading on return. const portalWindow = window.open(url, '_blank') if (portalWindow) refreshOnPortalReturn() } + // Layer C before Layer A: where the customer lands is the server's call, so + // the rail the host would otherwise take never gets asked for a portal URL + // it would not open. async function manageSubscription(): Promise { + const hosted = hostedBillingRoute( + flags.hostedBillingDestination, + 'payment-methods' + ) + if (hosted.kind === 'billing_web') { + error.value = null + openPortalWindow(hosted.url.href) + return + } + const rail = useSubscriptionRail() if (rail) { const url = await onSubscriptionRail(() => From d987ce93fabf9ccb21df02942ffa2c08b034c7fa Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 04:21:46 -0400 Subject: [PATCH 09/15] FE-2216 fix(billing): keep the subscription conversion event on the SDK rail On the rail every subscribe projects to `subscribed`, so the checkout returns before the poller that used to emit `trackMonthlySubscriptionSucceeded` and the success toast. Legacy drew that line by whether the server could activate the plan on the spot: a `subscribed` response started no poller and counted nothing, while `needs_payment_method` and `pending_payment` were watched to a conclusion and then counted and announced. The subscribe command now carries the status it issued under, so the rail's settled response says whether the server took a payment and the checkout emits exactly the same set. --- .../core/billing/subscriptionCommands.test.ts | 52 +++++++++++++++++- .../src/core/billing/subscriptionCommands.ts | 48 ++++++++++++++-- .../billing/sdk/billingSdkStore.test.ts | 6 +- .../sdk/subscriptionOperationView.test.ts | 33 +++++++---- .../billing/sdk/subscriptionOperationView.ts | 31 +++++++++-- .../composables/useDowngradeToPersonal.ts | 10 ++-- .../useSubscriptionCheckout.test.ts | 55 +++++++++++++++++++ .../composables/useSubscriptionCheckout.ts | 34 +++++++++--- ...eWorkspaceBilling.subscriptionRail.test.ts | 3 +- .../composables/useWorkspaceBilling.ts | 10 ++-- 10 files changed, 240 insertions(+), 42 deletions(-) diff --git a/packages/account-core/src/core/billing/subscriptionCommands.test.ts b/packages/account-core/src/core/billing/subscriptionCommands.test.ts index cdfc0d4682a..b21ad989d67 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.test.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import type { SessionClient, SessionSnapshot } from '../session.js' import type { AccountCredential } from '../sessionContracts.js' @@ -898,6 +898,56 @@ describe('createBillingCommands', () => { }) }) + it.for([ + ['subscribed', subscribed], + ['pending_payment', pendingPayment], + [ + 'needs_payment_method', + http(200, { + billing_op_id: 'op-1', + status: 'needs_payment_method', + payment_method_url: 'https://checkout.example/pay' + }) + ] + ] as const)( + 'settles a %s subscribe under the status the server issued it with', + async ([issuedStatus, response]) => { + const h = harness({ + status: FREE, + script: { [POST_SUBSCRIBE]: [response], [GET_OP]: settledOk } + }) + + const result = h.commands.subscribe(PLAN) + await flush() + await vi.advanceTimersByTimeAsync(OPERATION_POLL_TIMING.parkedMs) + + await expect(result).resolves.toMatchObject({ + status: 'ok', + value: { phase: 'succeeded', issuedStatus } + }) + } + ) + + it('leaves a cancel without an issued subscribe status', async () => { + const h = harness({ + status: PRO_ACTIVE, + script: { + [POST_CANCEL]: [ + http(200, { + billing_op_id: 'op-1', + cancel_at: '2026-10-01T00:00:00.000Z' + }) + ], + [GET_OP]: settledOk + } + }) + + const result = await h.commands.cancelSubscription() + + assert(result.status === 'ok') + expect(result.value.issuedStatus).toBeUndefined() + }) + it('reports a hosted payment step without a page as MISSING_PAYMENT_METHOD_URL', async () => { const h = harness({ status: FREE, diff --git a/packages/account-core/src/core/billing/subscriptionCommands.ts b/packages/account-core/src/core/billing/subscriptionCommands.ts index 5e69a21b19c..1ea34d792b5 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.ts @@ -78,10 +78,21 @@ export type SubscriptionCommandFailure = | BillingFailure | { readonly status: 'error'; readonly code: SubscriptionCommandCode } +/** What the subscribe route answered before the lifecycle drove the operation on. */ +type SubscribeIssuedStatus = z.infer['status'] + export interface SubscriptionCommandOutcome { readonly phase: TerminalBillingOperation['phase'] /** Absent when the requested state already held and nothing was issued. */ readonly operation?: TerminalBillingOperation + /** + * The `status` the subscribe response carried, before the lifecycle settled + * the operation: `subscribed` is a plan the server activated on the spot, + * the other two are payment steps it could not complete without the + * customer. Absent for every other command, and for a subscribe that + * adopted an operation the server was already settling. + */ + readonly issuedStatus?: SubscribeIssuedStatus } export type SubscriptionCommandResult = @@ -180,8 +191,14 @@ export interface BillingCommands { }) => Promise } +interface IssuedOutcome { + readonly status: 'ok' + readonly value: IssuedBillingOperation + readonly issuedStatus?: SubscribeIssuedStatus +} + type IssueOutcome = - | { readonly status: 'ok'; readonly value: IssuedBillingOperation } + | IssuedOutcome /** The server refused because the requested state already holds. */ | { readonly status: 'already_held' } | SubscriptionCommandFailure @@ -282,11 +299,17 @@ export function createBillingCommands( issue: () => Promise ): Promise { // The lifecycle carries only the shared codes; the command's own verdict - // waits here for `begin` to return. + // and what it read off the issuing response wait here for `begin` to + // return. Both stay unset when `begin` adopted an operation the server was + // already settling instead of issuing this one. const verdict: { value?: Exclude } = {} + const issued: { value?: IssuedOutcome } = {} const began = await lifecycle.begin(kind, async () => { const outcome = await issue() - if (outcome.status === 'ok') return outcome + if (outcome.status === 'ok') { + issued.value = outcome + return outcome + } verdict.value = outcome return { status: 'error', code: 'REQUEST_FAILED' } }) @@ -303,7 +326,15 @@ export function createBillingCommands( return { status: 'error', code: 'SUPERSEDED' } } if (operation.phase === 'succeeded') await refreshAfterSuccess() - return { status: 'ok', value: { phase: operation.phase, operation } } + const issuedStatus = issued.value?.issuedStatus + return { + status: 'ok', + value: { + phase: operation.phase, + operation, + ...(issuedStatus === undefined ? {} : { issuedStatus }) + } + } } async function issueSubscribe(input: SubscribeInput): Promise { @@ -324,14 +355,19 @@ export function createBillingCommands( } const { billing_op_id, status, payment_method_url } = response.value.data if (status !== 'needs_payment_method') { - return { status: 'ok', value: { operationId: billing_op_id } } + return { + status: 'ok', + value: { operationId: billing_op_id }, + issuedStatus: status + } } if (payment_method_url === undefined) { return coded('MISSING_PAYMENT_METHOD_URL') } return { status: 'ok', - value: { operationId: billing_op_id, actionUrl: payment_method_url } + value: { operationId: billing_op_id, actionUrl: payment_method_url }, + issuedStatus: status } } diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 6e118c372a3..f802e3d649c 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -488,7 +488,11 @@ describe('useBillingSdkStore subscription commands', () => { useBillingSdkStore().subscribe({ plan_slug: 'pro-yearly' }) ).resolves.toEqual({ status: 'ok', - value: { billing_op_id: 'op-1', status: 'subscribed' } + value: { + billing_op_id: 'op-1', + status: 'subscribed', + requiredPayment: true + } }) expect(harness.sdk.commands.subscribe).toHaveBeenCalledWith({ plan_slug: 'pro-yearly' diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts index f5aa854e1d7..1f9a416851e 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts @@ -110,20 +110,33 @@ describe('projectSubscriptionResult', () => { }) describe('projectSubscribeResult', () => { - it('hands back the operation the checkout reports as subscribed', () => { - expect( - projectSubscribeResult({ + it.for([ + { issuedStatus: 'subscribed', requiredPayment: false }, + { issuedStatus: 'pending_payment', requiredPayment: true }, + { issuedStatus: 'needs_payment_method', requiredPayment: true }, + { issuedStatus: undefined, requiredPayment: true } + ] as const)( + 'reports a subscribe issued as $issuedStatus as subscribed, requiredPayment $requiredPayment', + ({ issuedStatus, requiredPayment }) => { + expect( + projectSubscribeResult({ + status: 'ok', + value: { + phase: 'succeeded', + operation: settledOperation('succeeded', 'subscription'), + ...(issuedStatus === undefined ? {} : { issuedStatus }) + } + }) + ).toEqual({ status: 'ok', value: { - phase: 'succeeded', - operation: settledOperation('succeeded', 'subscription') + billing_op_id: 'op-1', + status: 'subscribed', + requiredPayment } }) - ).toEqual({ - status: 'ok', - value: { billing_op_id: 'op-1', status: 'subscribed' } - }) - }) + } + ) it.for([ { diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts index 2f508578632..60c8aeedcdf 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -26,6 +26,18 @@ import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { declineDetail } from './topupOperationView' +/** + * A subscribe response as the checkout reads it. `requiredPayment` is set only + * by the SDK rail, where `status` is always the settled `subscribed`: it says + * whether the server had to take a payment from the customer to get there. + * The legacy path leaves it unset — there a `subscribed` response is a plan + * that was already active, and the poller it never started is what drew the + * same line. + */ +export interface SettledSubscribeResponse extends SubscribeResponse { + readonly requiredPayment?: boolean +} + export type SubscriptionRailOutcome = | { readonly status: 'ok'; readonly value: T } | { readonly status: 'error'; readonly error: Error } @@ -41,7 +53,7 @@ export type SubscriptionRailOutcome = export interface SubscriptionRail { subscribe: ( input: SubscribeInput - ) => Promise> + ) => Promise> previewSubscribe: ( input: PreviewSubscribeInput ) => Promise> @@ -128,7 +140,12 @@ export function projectSubscriptionResult( * The SDK waits for the operation, so by the time this projects there is * nothing left to poll: the status is always the settled `subscribed`, never * the response's `needs_payment_method` or `pending_payment`, both of which - * the lifecycle drove to a conclusion first. + * the lifecycle drove to a conclusion first. `issuedStatus` is what the + * server answered before that, so `requiredPayment` keeps the line the legacy + * poller drew: it watched — and so counted and announced — exactly the + * subscribes the server could not activate on the spot. An adopted operation + * carries no issued status and is one the server was still settling, which is + * the same side of that line. * * An outcome carries no operation only when the server answered that the * requested state already held, which subscribe never reaches: the route @@ -136,15 +153,19 @@ export function projectSubscriptionResult( */ export function projectSubscribeResult( result: SubscriptionCommandResult -): SubscriptionRailOutcome { +): SubscriptionRailOutcome { if (result.status === 'error') return projectFailure(result) - const { phase, operation } = result.value + const { phase, operation, issuedStatus } = result.value if (phase !== 'succeeded' || operation === undefined) { return projectUnsuccessfulSettle(result.value) } return { status: 'ok', - value: { billing_op_id: operation.id, status: 'subscribed' } + value: { + billing_op_id: operation.id, + status: 'subscribed', + requiredPayment: issuedStatus !== 'subscribed' + } } } diff --git a/src/platform/workspace/composables/useDowngradeToPersonal.ts b/src/platform/workspace/composables/useDowngradeToPersonal.ts index fdbd278ea77..8d17be0d706 100644 --- a/src/platform/workspace/composables/useDowngradeToPersonal.ts +++ b/src/platform/workspace/composables/useDowngradeToPersonal.ts @@ -12,10 +12,8 @@ import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { BillingFailure } from '@/platform/telemetry/types' import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' -import type { - PreviewSubscribeResponse, - SubscribeResponse -} from '@/platform/workspace/api/workspaceApi' +import type { PreviewSubscribeResponse } from '@/platform/workspace/api/workspaceApi' +import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' @@ -23,7 +21,7 @@ import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspace export interface DowngradeToPersonalResult { preview: PreviewSubscribeResponse - response: SubscribeResponse + response: SettledSubscribeResponse } export interface DowngradePreview { @@ -285,7 +283,7 @@ export function useDowngradeToPersonal() { cycle: targetCycle, checkout_type: 'change' }) - let response: SubscribeResponse | void + let response: SettledSubscribeResponse | void try { response = await subscribe(planSlug, { returnUrl: `${getComfyPlatformBaseUrl()}/payment/success`, diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index 043933fef97..04baa3dd503 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -422,6 +422,9 @@ const i18n = createI18n({ } } }, + billingOperation: { + subscriptionSuccess: 'Subscription updated' + }, toastMessages: { failedToAccessBillingPortal: 'Billing portal unavailable', invalidBillingPortalUrl: 'Invalid billing portal URL' @@ -3999,6 +4002,58 @@ describe('useSubscriptionCheckout', () => { ).not.toHaveBeenCalled() }) + it('counts the conversion and announces a subscribe the server charged for', async () => { + const checkout = await setupWithApprovedPreview() + checkout.selectedTierKey.value = 'standard' + checkout.selectedBillingCycle.value = 'yearly' + mockSubscribe.mockResolvedValueOnce({ + status: 'subscribed', + billing_op_id: 'op-3', + requiredPayment: true + }) + mockFetchStatus.mockResolvedValueOnce(undefined) + mockFetchBalance.mockResolvedValueOnce(undefined) + + await checkout.handleConfirmTransition() + + expect( + useTelemetry()?.trackMonthlySubscriptionSucceeded + ).toHaveBeenCalledExactlyOnceWith({ + tier: 'standard', + cycle: 'yearly', + checkout_type: 'new', + payment_intent_source: undefined, + billing_op_id: 'op-3' + }) + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'success', + summary: 'Subscription updated' + }) + ) + }) + + it('counts neither for a subscribe the server activated without a payment', async () => { + const checkout = await setupWithApprovedPreview() + checkout.selectedTierKey.value = 'standard' + checkout.selectedBillingCycle.value = 'yearly' + mockSubscribe.mockResolvedValueOnce({ + status: 'subscribed', + billing_op_id: 'op-3', + requiredPayment: false + }) + mockFetchStatus.mockResolvedValueOnce(undefined) + mockFetchBalance.mockResolvedValueOnce(undefined) + + await checkout.handleConfirmTransition() + + expect(checkout.checkoutStep.value).toBe('success') + expect( + useTelemetry()?.trackMonthlySubscriptionSucceeded + ).not.toHaveBeenCalled() + expect(mockToastAdd).not.toHaveBeenCalled() + }) + it('shows error toast on failure', async () => { const checkout = await setupWithApprovedPreview() checkout.selectedTierKey.value = 'standard' diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.ts b/src/platform/workspace/composables/useSubscriptionCheckout.ts index 5d5bb8deb90..aed60f2026e 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.ts @@ -29,10 +29,10 @@ import type { PreviewSubscribeOptions, PreviewSubscribeResponse, SavedPaymentMethod, - SubscribeOptions, - SubscribeResponse + SubscribeOptions } from '@/platform/workspace/api/workspaceApi' import { workspaceApi } from '@/platform/workspace/api/workspaceApi' +import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' @@ -1365,7 +1365,7 @@ export function useSubscriptionCheckout( } async function handleSubscribeResponse( - response: SubscribeResponse | void, + response: SettledSubscribeResponse | void, context: SubscriptionOutcomeContext, shouldTrackSubscriptionSuccess = true, // 0 when the caller holds no lock; a release from a non-holder is a no-op. @@ -1384,11 +1384,11 @@ export function useSubscriptionCheckout( const durationMs = Date.now() - context.attemptStartedAt // PostHog implements both trackBillingEvent and // trackMonthlySubscriptionSucceeded (PostHogTelemetryProvider.ts:405, - // :444), so also calling the legacy event here would double-count this - // success for it. billingOperationStore.ts's own success handler - // already restores trackMonthlySubscriptionSucceeded for the - // providers that need it (Mixpanel, GTM); this call site doesn't need - // a second one. + // :444), so calling the legacy event for a plan the server activated + // on the spot would double-count that success for it. Only a subscribe + // the server charged for reaches the legacy event below, which is the + // set billingOperationStore.ts's success handler counts for the + // providers that need it (Mixpanel, GTM) on the legacy path. telemetry?.trackBillingEvent({ operation: 'subscription_checkout', stage: 'succeeded', @@ -1412,6 +1412,24 @@ export function useSubscriptionCheckout( billing_op_id: response.billing_op_id, duration_ms: durationMs }) + if (response.requiredPayment) { + telemetry?.trackMonthlySubscriptionSucceeded({ + tier: context.tier, + cycle: context.cycle, + checkout_type: context.checkoutType, + payment_intent_source: paymentIntentSource, + billing_op_id: response.billing_op_id + }) + } + } + // The poller announced every subscription operation it settled, whatever + // the caller was tracking; on this rail there is no poller to do it. + if (response.requiredPayment) { + toast.add({ + severity: 'success', + summary: t('billingOperation.subscriptionSuccess'), + life: 5000 + }) } checkoutStep.value = 'success' return diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index d6e30903de3..3d70853931a 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -376,7 +376,8 @@ describe('subscribe on the billing SDK rail', () => { }) expect(response).toEqual({ billing_op_id: 'op-1', - status: 'subscribed' + status: 'subscribed', + requiredPayment: true }) expect(workspaceApi.subscribe).not.toHaveBeenCalled() }) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index e870df5af1a..aab074156d4 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -25,8 +25,7 @@ import type { CreateTopupResponse, PreviewSubscribeOptions, PreviewSubscribeResponse, - SubscribeOptions, - SubscribeResponse + SubscribeOptions } from '@/platform/workspace/api/workspaceApi' import { WorkspaceApiError, @@ -34,7 +33,10 @@ import { } from '@/platform/workspace/api/workspaceApi' import { hostedBillingRoute } from '@/platform/workspace/billing/hostedBillingRoutes' import { useBillingSdkStore } from '@/platform/workspace/billing/sdk/billingSdkStore' -import type { SubscriptionRailOutcome } from '@/platform/workspace/billing/sdk/subscriptionOperationView' +import type { + SettledSubscribeResponse, + SubscriptionRailOutcome +} from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useSubscriptionRail } from '@/platform/workspace/composables/useSubscriptionRail' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' @@ -422,7 +424,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { async function subscribe( planSlug: string, options?: SubscribeOptions - ): Promise { + ): Promise { const rail = useSubscriptionRail() if (rail) { const response = await onSubscriptionRail(() => From 7e82c5bebb0cd7a1565b875cfde51c5e5510f578 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 04:28:54 -0400 Subject: [PATCH 10/15] FE-2216 fix(billing): give a blocked payment popup a way through MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `openedActions` marked an operation opened before the open was known to have worked, so a blocked popup silenced the hosted step for the rest of its life. The open runs off the lifecycle rather than a click, so retrying it per poll would only be blocked again and repeat the warning; instead the rail offers each hosted step once and holds the one the customer still owes on `subscriptionActionUrl`, which the checkout folds into `activeCheckoutActionUrl` — the Complete verification button the legacy poller already fed. --- .../billing/sdk/billingSdkStore.test.ts | 39 ++++++++++++++++++- .../workspace/billing/sdk/billingSdkStore.ts | 24 ++++++++++-- .../billing/sdk/subscriptionOperationView.ts | 6 +++ .../useSubscriptionCheckout.test.ts | 36 ++++++++++++++++- .../composables/useSubscriptionCheckout.ts | 6 ++- 5 files changed, 102 insertions(+), 9 deletions(-) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index f802e3d649c..8f6ff059393 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -514,9 +514,9 @@ describe('useBillingSdkStore subscription commands', () => { expect(mockFetchStatus).not.toHaveBeenCalled() }) - it('opens the hosted payment page once for a subscribe parked on the customer', () => { + it('warns once and keeps a blocked payment page reachable however long it polls', () => { const openPage = vi.spyOn(window, 'open').mockReturnValue(null) - useBillingSdkStore() + const store = useBillingSdkStore() const toasts = useToastStore() harness.publish( @@ -528,6 +528,13 @@ describe('useBillingSdkStore subscription commands', () => { customerActionSeen: true }) ) + harness.publish( + pendingSubscription({ + actionUrl: 'https://pay.example/op-1', + customerActionSeen: true, + authenticationState: 'requires_action' + }) + ) expect(openPage).toHaveBeenCalledExactlyOnceWith( 'https://pay.example/op-1', @@ -536,6 +543,34 @@ describe('useBillingSdkStore subscription commands', () => { expect(toasts.messagesToAdd).toEqual([ expect.objectContaining({ severity: 'warn' }) ]) + expect(store.subscriptionActionUrl).toBe('https://pay.example/op-1') + }) + + it('offers the next hosted page the same subscribe moves to', () => { + const openPage = vi.spyOn(window, 'open').mockReturnValue(null) + const store = useBillingSdkStore() + + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/first' }) + ) + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/second' }) + ) + + expect(openPage).toHaveBeenCalledTimes(2) + expect(store.subscriptionActionUrl).toBe('https://pay.example/second') + }) + + it('offers nothing once the subscribe has settled', () => { + vi.spyOn(window, 'open').mockReturnValue(null) + const store = useBillingSdkStore() + + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/op-1' }) + ) + harness.publish(settledOperation('succeeded', 'subscription')) + + expect(store.subscriptionActionUrl).toBeNull() }) it('drives the in-page challenge a subscribe raises, as it does for a top-up', async () => { diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index 2f5779221e1..a6e9147832f 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -76,7 +76,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { const dismissed = shallowRef>(new Set()) const resumedOperations = new Set() const drivenChallenges = new Set() - const openedActions = new Set() + const offeredActions = new Map() const progressToasts = new Map< string, { kind: ProgressKind; message: ToastMessage } @@ -123,6 +123,15 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { topupViews.value.find(needsCustomerAttention) ) + const subscriptionActionUrl = computed( + () => + operations.value.flatMap((state) => + state.kind === 'subscription' && state.phase === 'pending' + ? (state.actionUrl ?? []) + : [] + )[0] ?? null + ) + // A top-up the dialog issued is reported by the dialog, exactly as before; // the lifecycle's events stand in for the poller's only on an operation // this tab reattached to. A cancel or resubscribe has no such second @@ -194,10 +203,16 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { openHostedAction(state) } + // One offer per hosted step, not per poll: the open runs off the lifecycle + // rather than a click, so a browser that blocked the first one blocks every + // retry and each retry would repeat the warning. A step the customer still + // owes stays on `subscriptionActionUrl` for the checkout to put behind a + // button of their own. function openHostedAction(state: PendingBillingOperation) { - if (state.actionUrl === undefined || openedActions.has(state.id)) return - openedActions.add(state.id) - if (window.open(state.actionUrl, '_blank')) return + const { id, actionUrl } = state + if (actionUrl === undefined || offeredActions.get(id) === actionUrl) return + offeredActions.set(id, actionUrl) + if (window.open(actionUrl, '_blank')) return toastStore.add({ severity: 'warn', summary: t('g.warning'), @@ -358,6 +373,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { return { isAddingCredits, topupActionOperation, + subscriptionActionUrl, createTopup, subscribe, previewSubscribe, diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts index 60c8aeedcdf..e759e4ec192 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -51,6 +51,12 @@ export type SubscriptionRailOutcome = * already reads. */ export interface SubscriptionRail { + /** + * The hosted step a subscribe on this rail is parked on, or null. The rail + * opens it once itself, so this is what the checkout puts behind a button + * when the browser blocked that open. + */ + readonly subscriptionActionUrl: string | null subscribe: ( input: SubscribeInput ) => Promise> diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index 04baa3dd503..c9cd8a297ab 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -205,7 +205,8 @@ const { mockCanReactivatePlan, mockCapabilities, mockSubscription, - mockBillingStatus + mockBillingStatus, + mockSubscriptionRail } = vi.hoisted(() => { return { mockSubscribe: vi.fn(), @@ -246,7 +247,10 @@ const { isCancelled: boolean } | null }, - mockBillingStatus: { value: null as BillingStatus | null } + mockBillingStatus: { value: null as BillingStatus | null }, + mockSubscriptionRail: { + value: null as { subscriptionActionUrl: string | null } | null + } } }) @@ -375,6 +379,11 @@ vi.mock(import('@/platform/workspace/api/workspaceApi'), () => ({ } })) +vi.mock( + import('@/platform/workspace/composables/useSubscriptionRail'), + () => ({ useSubscriptionRail: () => mockSubscriptionRail.value }) +) + vi.mock(import('@/config/comfyApi'), () => ({ getComfyPlatformBaseUrl: () => 'https://platform.comfy.org' })) @@ -539,6 +548,7 @@ describe('useSubscriptionCheckout', () => { } mockCanReactivatePlan.value = true mockSubscription.value = null + mockSubscriptionRail.value = null vi.mocked(useTelemetry()?.trackCheckoutJourneyEvent)?.mockClear() sessionStorage.clear() clearCheckoutJourney() @@ -3093,6 +3103,28 @@ describe('useSubscriptionCheckout', () => { }) }) + describe('hosted payment step on the SDK rail', () => { + it('re-offers the hosted page the rail opened for itself', async () => { + mockSubscriptionRail.value = { + subscriptionActionUrl: 'https://pay.example/op-3' + } + + const checkout = await setupWithApprovedPreview() + + expect(checkout.activeCheckoutActionUrl.value).toBe( + 'https://pay.example/op-3' + ) + }) + + it('offers nothing while the rail is parked on no hosted page', async () => { + mockSubscriptionRail.value = { subscriptionActionUrl: null } + + const checkout = await setupWithApprovedPreview() + + expect(checkout.activeCheckoutActionUrl.value).toBeNull() + }) + }) + describe('handleBackToPricing', () => { it('surfaces a subscription operation recovered from billing status', async () => { Object.assign(useBillingOperationStore(), { diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.ts b/src/platform/workspace/composables/useSubscriptionCheckout.ts index aed60f2026e..ad9590c3643 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.ts @@ -34,6 +34,7 @@ import type { import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { useSubscriptionRail } from '@/platform/workspace/composables/useSubscriptionRail' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -200,7 +201,10 @@ export function useSubscriptionCheckout( : undefined }) const activeCheckoutActionUrl = computed( - () => activeCheckoutOperation.value?.actionUrl ?? null + () => + activeCheckoutOperation.value?.actionUrl ?? + useSubscriptionRail()?.subscriptionActionUrl ?? + null ) // The server says whether the operation is parked; the client no longer // guesses. Only awaiting_payment_method offers this recovery — an operation From cb7d3e13193af07e0952ed6238d8739b07b05d75 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 05:13:56 -0400 Subject: [PATCH 11/15] FE-2216 fix(billing): leave a way through when a hosted tab is blocked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both hosted entry points returned as though the open had worked. "Plans & pricing" branched on the route kind, so a blocked popup left the customer with nothing at all; `manageSubscription` returned before the rail and the workspace client, so "Billing & invoices" opened nothing either. The popover now opens a blank tab, which reports blocking honestly, drops its `opener` before it leaves about:blank, and only then navigates — keeping the security `noopener` was there for without giving up the handle that says whether a tab exists. `openPortalWindow` reports the same thing, so the hosted branch returns only on a real open and otherwise falls through to the rail. --- .../CurrentUserPopoverWorkspace.test.ts | 40 ++++++++++++++++--- .../CurrentUserPopoverWorkspace.vue | 17 ++++++-- .../composables/useWorkspaceBilling.test.ts | 30 ++++++++++++++ .../composables/useWorkspaceBilling.ts | 9 +++-- 4 files changed, 84 insertions(+), 12 deletions(-) diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts index ed63de7cdd6..d97288fe225 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts @@ -201,6 +201,20 @@ function renderComponent( }) } +/** + * A blank tab the handler can disown and navigate. happy-dom's own child + * window exposes `opener` read-only and fetches whatever `location` is set to. + */ +function stubHostedTab(): Window { + const tab: Window = Object.create(window) + Object.defineProperty(tab, 'opener', { value: window, writable: true }) + Object.defineProperty(tab, 'location', { + value: { href: 'about:blank' }, + writable: true + }) + return tab +} + describe('CurrentUserPopoverWorkspace', () => { beforeEach(() => { state.isCloud = true @@ -339,7 +353,8 @@ describe('CurrentUserPopoverWorkspace', () => { it('opens hosted billing alone when its feature flag is enabled', async () => { const user = userEvent.setup() - const open = vi.spyOn(window, 'open').mockReturnValue(null) + const tab = stubHostedTab() + const open = vi.spyOn(window, 'open').mockReturnValue(tab) state.canOpenPricingSurface = true state.hostedBillingDestination = 'billing_web' renderComponent('team') @@ -347,14 +362,29 @@ describe('CurrentUserPopoverWorkspace', () => { await user.click(screen.getByTestId('plans-pricing-menu-item')) expect(open).toHaveBeenCalledOnce() - expect(open).toHaveBeenCalledWith( - 'http://localhost:5174/v1/pricing?product=comfyui&return_to=comfyui_workspace', - '_blank', - 'noopener,noreferrer' + expect(open).toHaveBeenCalledWith('', '_blank') + expect(tab.opener).toBeNull() + expect(tab.location.href).toBe( + 'http://localhost:5174/v1/pricing?product=comfyui&return_to=comfyui_workspace' ) expect(state.showPricingTable).not.toHaveBeenCalled() }) + it('falls back to the in-app pricing table when the hosted tab is blocked', async () => { + const user = userEvent.setup() + const open = vi.spyOn(window, 'open').mockReturnValue(null) + state.canOpenPricingSurface = true + state.hostedBillingDestination = 'billing_web' + renderComponent('team') + + await user.click(screen.getByTestId('plans-pricing-menu-item')) + + expect(open).toHaveBeenCalledOnce() + expect(state.showPricingTable).toHaveBeenCalledWith({ + reason: 'avatar_menu_plans' + }) + }) + it('keeps Plans & pricing in-app when the hosted URL is unavailable', async () => { const user = userEvent.setup() const open = vi.spyOn(window, 'open').mockImplementation(() => null) diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index 859d23b3bc5..6dae24bd068 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -392,11 +392,22 @@ const handleOpenWorkspaceSettings = () => { emit('close') } +/** + * `noopener` returns a null handle even on success, so the blocked tab and the + * opened one are told apart by opening a blank tab and disowning it by hand + * before it leaves `about:blank`. + */ +const openDisownedTab = (url: URL): boolean => { + const tab = window.open('', '_blank') + if (!tab) return false + tab.opener = null + tab.location.href = url.href + return true +} + const handleOpenPlansAndPricing = () => { const route = hostedBillingRoute(flags.hostedBillingDestination, 'pricing') - if (route.kind === 'billing_web') { - window.open(route.url.href, '_blank', 'noopener,noreferrer') - } else { + if (route.kind !== 'billing_web' || !openDisownedTab(route.url)) { subscriptionDialog.showPricingTable({ reason: 'avatar_menu_plans' }) } emit('close') diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 2e207772b81..7ab82fd5a45 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -936,6 +936,36 @@ describe('useWorkspaceBilling', () => { } ) + it.for([ + ['the legacy client', false, 'https://billing.example/portal'], + ['the SDK rail', true, 'https://billing.example/sdk-portal'] + ] as const)( + 'falls through to %s when the hosted tab is blocked', + async ([, railEnabled, fallbackUrl]) => { + const openSpy = vi.fn(() => null) + vi.stubGlobal('open', openSpy) + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + localStorage.setItem('ff:hosted_billing_destination', '"billing_web"') + mockRail.enabled = railEnabled + mockRail.openPaymentPortal.mockResolvedValue({ + status: 'ok', + value: 'https://billing.example/sdk-portal' + }) + mockWorkspaceApi.getPaymentPortalUrl.mockResolvedValue({ + url: 'https://billing.example/portal' + }) + + const billing = setupBilling() + await billing.manageSubscription() + + expect(openSpy).toHaveBeenCalledWith( + 'https://billing.comfy.org/v1/payment-methods?product=comfyui&return_to=comfyui_workspace', + '_blank' + ) + expect(openSpy).toHaveBeenLastCalledWith(fallbackUrl, '_blank') + } + ) + it('clears a failure from the previous attempt when the hosted route opens', async () => { vi.stubGlobal( 'open', diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index aab074156d4..d28d8d1882e 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -535,11 +535,13 @@ export function useWorkspaceBilling(): BillingState & BillingActions { } } - function openPortalWindow(url: string): void { + function openPortalWindow(url: string): boolean { // The handle arms the return refresh, so adding `noopener` here (which // nulls it) silently stops billing state from re-reading on return. const portalWindow = window.open(url, '_blank') - if (portalWindow) refreshOnPortalReturn() + if (!portalWindow) return false + refreshOnPortalReturn() + return true } // Layer C before Layer A: where the customer lands is the server's call, so @@ -552,8 +554,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { ) if (hosted.kind === 'billing_web') { error.value = null - openPortalWindow(hosted.url.href) - return + if (openPortalWindow(hosted.url.href)) return } const rail = useSubscriptionRail() From 89f32349eedc800200b7170a94e872f9d71b4c34 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 05:14:33 -0400 Subject: [PATCH 12/15] FE-2216 fix(billing): refuse billing input the customer would be charged on `hostedBillingRoute` promises that anything unresolved falls back to the provider, but the cloud base URL reached `new URL` unguarded: `resolveBaseUrl` validates a configured value and then returns the build-time default without checking it, so a malformed `VITE_STAGING_CLOUD_BASE_URL` threw out of a default argument rather than routing to the provider. The quote's overridden cent fields replaced the generated int64 with a bare `z.number()`, which took `1500.5` and integers past the safe range straight into price display and charge confirmation. They are whole units of currency that have to survive arithmetic, so the shared `cents` schema requires that. --- .../core/billing/subscriptionCommands.test.ts | 115 +++++++++++++++++- .../src/core/billing/subscriptionCommands.ts | 6 +- .../billing/hostedBillingRoutes.test.ts | 9 ++ .../workspace/billing/hostedBillingRoutes.ts | 17 ++- 4 files changed, 142 insertions(+), 5 deletions(-) diff --git a/packages/account-core/src/core/billing/subscriptionCommands.test.ts b/packages/account-core/src/core/billing/subscriptionCommands.test.ts index b21ad989d67..1ad72cd2fc9 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.test.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.test.ts @@ -1,4 +1,12 @@ -import { assert, beforeEach, describe, expect, it, vi } from 'vitest' +import { + assert, + beforeEach, + describe, + expect, + expectTypeOf, + it, + vi +} from 'vitest' import type { SessionClient, SessionSnapshot } from '../session.js' import type { AccountCredential } from '../sessionContracts.js' @@ -26,6 +34,7 @@ import type { BillingStatusReader, BillingStatusSnapshot } from './status.js' +import type { SubscriptionPreview } from './subscriptionCommands.js' import { CANCEL_SUBSCRIPTION_ROUTE, PAYMENT_PORTAL_ROUTE, @@ -727,6 +736,110 @@ describe('createBillingCommands', () => { }) }) + const QUOTE_CENT_FIELDS = [ + 'amount_due_cents', + 'cost_next_period_cents', + 'cost_today_cents', + 'credits_next_period_cents', + 'credits_today_cents', + 'renewal_amount_cents' + ] as const satisfies readonly (keyof SubscriptionPreview)[] + + const PLAN_CENT_FIELDS = [ + 'credits_cents', + 'price_cents' + ] as const satisfies readonly (keyof SubscriptionPreview['new_plan'])[] + + const SEAT_CENT_FIELDS = [ + 'total_cost_cents', + 'total_credits_cents' + ] as const satisfies readonly (keyof SubscriptionPreview['new_plan']['seat_summary'])[] + + // Compile-time pins: an amount a regen adds fails the package typecheck + // until it reaches a row below. + expectTypeOf<(typeof QUOTE_CENT_FIELDS)[number]>().toEqualTypeOf< + Extract + >() + expectTypeOf<(typeof PLAN_CENT_FIELDS)[number]>().toEqualTypeOf< + Extract + >() + expectTypeOf<(typeof SEAT_CENT_FIELDS)[number]>().toEqualTypeOf< + Extract< + keyof SubscriptionPreview['new_plan']['seat_summary'], + `${string}_cents` + > + >() + + const rejectsQuote = async (patch: object) => { + const h = harness({ + status: FREE, + script: { [POST_PREVIEW]: [http(200, { ...QUOTE_BODY, ...patch })] } + }) + + await expect( + h.commands.previewSubscribe({ planSlug: 'pro-monthly' }) + ).resolves.toEqual({ + status: 'error', + code: 'MALFORMED_RESPONSE', + httpStatus: 200 + }) + } + + const FRACTION_OF_A_CENT = 1500.5 + + it.for(QUOTE_CENT_FIELDS)('refuses a fraction of a cent at %s', (field) => + rejectsQuote({ [field]: FRACTION_OF_A_CENT }) + ) + + it.for(PLAN_CENT_FIELDS)( + 'refuses a fraction of a cent at new_plan.%s', + (field) => + rejectsQuote({ + new_plan: { ...PREVIEW_PLAN, [field]: FRACTION_OF_A_CENT } + }) + ) + + it.for(PLAN_CENT_FIELDS)( + 'refuses a fraction of a cent at current_plan.%s', + (field) => + rejectsQuote({ + current_plan: { ...PREVIEW_PLAN, [field]: FRACTION_OF_A_CENT } + }) + ) + + it.for(SEAT_CENT_FIELDS)( + 'refuses a fraction of a cent at new_plan.seat_summary.%s', + (field) => + rejectsQuote({ + new_plan: { + ...PREVIEW_PLAN, + seat_summary: { + ...PREVIEW_PLAN.seat_summary, + [field]: FRACTION_OF_A_CENT + } + } + }) + ) + + it('refuses a fraction of a cent off a discount', () => + rejectsQuote({ + discounts: [ + { + amount_off_cents: FRACTION_OF_A_CENT, + code: 'LAUNCH', + kind: 'promotion', + name: 'Launch offer' + } + ] + })) + + it.for([ + ['past the safe integers', Number.MAX_SAFE_INTEGER + 2], + ['with no finite value at all', Number.POSITIVE_INFINITY] + ] as const)('refuses an amount %s', ([, cents]) => + rejectsQuote({ cost_today_cents: cents }) + ) + it('forwards the caller signal and timeout, releasing an abandoned read as transient', async () => { const controller = new AbortController() const h = harness({ diff --git a/packages/account-core/src/core/billing/subscriptionCommands.ts b/packages/account-core/src/core/billing/subscriptionCommands.ts index 1ea34d792b5..1192491feb9 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.ts @@ -108,9 +108,11 @@ export type PaymentPortalResult = * add to a price or hand to a currency formatter — and the generated *type* * for the same field is a `number`. Money on this route is bounded to cents * well inside the JavaScript-safe range, so the cents are read as numbers, the - * way `capabilities` reads `revision`. + * way `capabilities` reads `revision` — as whole units of currency that + * survive arithmetic, since these amounts are displayed as prices and + * confirmed as charges. */ -const cents = z.number() +const cents = z.number().int().safe() const PlanInfoSchema = zPreviewPlanInfo.extend({ credits_cents: cents, diff --git a/src/platform/workspace/billing/hostedBillingRoutes.test.ts b/src/platform/workspace/billing/hostedBillingRoutes.test.ts index 301405cf600..56c6779374b 100644 --- a/src/platform/workspace/billing/hostedBillingRoutes.test.ts +++ b/src/platform/workspace/billing/hostedBillingRoutes.test.ts @@ -101,6 +101,15 @@ describe('hostedBillingRoute', () => { }) }) + it('stays on the provider when the cloud base URL will not parse', () => { + cloudBaseUrl.value = 'not-a-url' + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + + expect(hostedBillingRoute('billing_web', 'pricing')).toEqual({ + kind: 'provider' + }) + }) + it('stays on the provider for a backend outside the known families', () => { cloudBaseUrl.value = 'https://cloud.example.com' vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') diff --git a/src/platform/workspace/billing/hostedBillingRoutes.ts b/src/platform/workspace/billing/hostedBillingRoutes.ts index 55f83bb0314..e0d13483eea 100644 --- a/src/platform/workspace/billing/hostedBillingRoutes.ts +++ b/src/platform/workspace/billing/hostedBillingRoutes.ts @@ -49,15 +49,28 @@ const BILLING_ENVIRONMENT_BY_DEPLOY_ENV: Readonly< 'test-v2': 'test' } +function hostnameOf(url: string): string | undefined { + try { + return new URL(url).hostname + } catch { + return undefined + } +} + /** * The family the session was minted against, not the label on this build: a * developer running the frontend locally still talks to a deployed backend, - * so the cloud base URL classifies the trip and `window.location` cannot. + * so the cloud base URL classifies the trip and `window.location` cannot. A + * base URL that will not parse classifies nothing, so it fails closed like any + * other unresolved environment rather than throwing through the caller. */ function hostBillingEnvironment( cloudBaseUrl = getComfyCloudBaseUrl() ): BillingEnvironment | undefined { - const deployEnv = resolveDeployEnv(new URL(cloudBaseUrl).hostname) + const hostname = hostnameOf(cloudBaseUrl) + if (hostname === undefined) return undefined + + const deployEnv = resolveDeployEnv(hostname) return deployEnv === undefined ? undefined : BILLING_ENVIRONMENT_BY_DEPLOY_ENV[deployEnv] From ae559b542a8e788f04438e8f4efaba9a014e2fcd Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 05:15:02 -0400 Subject: [PATCH 13/15] FE-2216 test(billing): quote the plan change on the rail the test names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `?pricing=` deep link quotes as the dialog opens, from the same `onMounted` that assigns `window.app`, so a flag set after the navigation arrived too late and every quote in the spec went over the legacy client. The assertion that covered it read an `Idempotency-Key` neither rail sends on a read, so it could not have said so. `seedServerFlags` installs the flags through a `window.app` accessor, which GraphCanvas assigns just before the URL action loaders run, and re-applies them on each `feature_flags` handshake as the runtime setter does. The quote and the commit are then checked against the transport that issued them — the SDK on `fetch`, the workspace client on axios' XHR — which is what tells the two quotes apart. --- .../fixtures/helpers/FeatureFlagHelper.ts | 37 ++++++++++++++++ .../tests/dialogs/planChangeSdkRail.spec.ts | 44 +++++++++++++++---- 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/browser_tests/fixtures/helpers/FeatureFlagHelper.ts b/browser_tests/fixtures/helpers/FeatureFlagHelper.ts index 5fca2e7a89b..f30d6edc0ca 100644 --- a/browser_tests/fixtures/helpers/FeatureFlagHelper.ts +++ b/browser_tests/fixtures/helpers/FeatureFlagHelper.ts @@ -102,6 +102,43 @@ export class FeatureFlagHelper { }, flags) } + /** + * Seed server feature flags before the app reads them, for a flag a + * boot-time action depends on — a `?pricing=` deep link opens its dialog + * from `onMounted`, so `setServerFlagsPersistent()` lands after the dialog + * has already chosen a rail. + * + * `window.app` is what gates this: it is assigned in `GraphCanvas`'s + * `onMounted` just before the URL action loaders run, so an accessor + * installed here applies the flags in that window and re-applies on every + * later `feature_flags` handshake, as `setServerFlagsPersistent()` does. + * + * Must be called before `page.goto()`; init scripts persist for the page + * lifetime and cannot be removed. + */ + async seedServerFlags(flags: Record): Promise { + await this.page.addInitScript((flagMap: Record) => { + let comfyApp: Window['app'] + Object.defineProperty(window, 'app', { + configurable: true, + get: () => comfyApp, + set: (value: Window['app']) => { + comfyApp = value + const api = value?.api + if (!api) return + const apply = () => { + api.serverFeatureFlags.value = { + ...api.serverFeatureFlags.value, + ...flagMap + } + } + apply() + api.addEventListener('feature_flags', apply) + } + }) + }, flags) + } + /** * Remove server feature flags and keep them removed across websocket * reconnects, pinning the flag-ABSENT state. The real backend may or may diff --git a/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts b/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts index af7aac9f177..427d2481c94 100644 --- a/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/planChangeSdkRail.spec.ts @@ -29,7 +29,8 @@ import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' * `POST /billing/subscribe`, so the recorded requests are what separate them: * only the SDK transport sends an `Idempotency-Key`, and only on the write — * the quote is a read the backend happens to shape as a POST, so it carries - * none on either rail. + * none on either rail. What separates the two quotes is the transport that + * issued them: the SDK runs on `fetch`, the workspace client on axios' XHR. */ const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' @@ -217,6 +218,27 @@ function idempotencyKey(request: Request): string | undefined { return request.headers()['idempotency-key'] } +/** + * Which transport issued a request, and so which rail served it: the SDK's + * runs on `fetch`, the legacy workspace client on axios' XHR adapter. The + * quote carries no idempotency key on either rail, so this is what tells the + * two quotes apart. + */ +function transport(request: Request): string { + return request.resourceType() +} + +/** + * The `?pricing=` deep link quotes the plan as the dialog opens, from the same + * `onMounted` that assigns `window.app`, so the rail has to be chosen before + * the page loads rather than after it. + */ +async function enableSdkRail(page: Page) { + await new FeatureFlagHelper(page).seedServerFlags({ + billing_sdk_subscription_enabled: true + }) +} + async function openCreatorUpgrade(page: Page) { await page.goto(`${APP_URL}/?pricing=creator&cycle=yearly`) await cloudAppExpect( @@ -243,6 +265,8 @@ test.describe('Plan change rail (FE-2216)', { tag: '@cloud' }, () => { expect(idempotencyKey(routes.subscribeRequests[0])).toBeUndefined() expect(routes.previewRequests.length).toBeGreaterThan(0) expect(idempotencyKey(routes.previewRequests[0])).toBeUndefined() + expect(transport(routes.previewRequests[0])).toBe('xhr') + expect(transport(routes.subscribeRequests[0])).toBe('xhr') }) test('issues through the SDK transport while the rail is on', async ({ @@ -250,10 +274,8 @@ test.describe('Plan change rail (FE-2216)', { tag: '@cloud' }, () => { }) => { test.setTimeout(60_000) const routes = await setupPlanChange(page) + await enableSdkRail(page) await openCreatorUpgrade(page) - await new FeatureFlagHelper(page).setServerFlagsPersistent({ - billing_sdk_subscription_enabled: true - }) await confirmButton(page).click() @@ -266,8 +288,12 @@ test.describe('Plan change rail (FE-2216)', { tag: '@cloud' }, () => { plan_slug: 'creator-annual', idempotency_key: idempotencyKey(issued) }) - // The quote is a read; the SDK sends no key for it on either rail. - expect(idempotencyKey(routes.previewRequests.at(-1)!)).toBeUndefined() + expect(transport(issued)).toBe('fetch') + // The quote is a read the SDK sends no key for, so the transport is what + // shows the rail served it. + const quote = routes.previewRequests.at(-1)! + expect(transport(quote)).toBe('fetch') + expect(idempotencyKey(quote)).toBeUndefined() }) test('falls back to the legacy call when the SDK route answers 404', async ({ @@ -275,10 +301,8 @@ test.describe('Plan change rail (FE-2216)', { tag: '@cloud' }, () => { }) => { test.setTimeout(60_000) const routes = await setupPlanChange(page) + await enableSdkRail(page) await openCreatorUpgrade(page) - await new FeatureFlagHelper(page).setServerFlagsPersistent({ - billing_sdk_subscription_enabled: true - }) routes.respondNotFound() await confirmButton(page).click() @@ -288,5 +312,7 @@ test.describe('Plan change rail (FE-2216)', { tag: '@cloud' }, () => { const [sdkAttempt, legacyAttempt] = routes.subscribeRequests expect(idempotencyKey(sdkAttempt)).toBeTruthy() expect(idempotencyKey(legacyAttempt)).toBeUndefined() + expect(transport(sdkAttempt)).toBe('fetch') + expect(transport(legacyAttempt)).toBe('xhr') }) }) From e6669195f510a06877165291777deeeae8a7a7a2 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 05:41:34 -0400 Subject: [PATCH 14/15] fix(account): keep the hosted destination stub off this page (FE-2216) The e2e stub handed back the live `window`, so `openDisownedTab` -- open blank, null the opener, assign `location.href` -- navigated the test page itself to the hosted origin. The recorded destination went with the document and the isolation fixture saw a live billing-web request. The handle is now a stand-in that records where the tab was sent. --- .../dialogs/hostedBillingDestination.spec.ts | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts index 1afb0303a6a..8c6878870c3 100644 --- a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -122,13 +122,37 @@ async function bootApp(page: Page) { await new CloudAuthHelper(page).mockAuth() await page.addInitScript(() => { localStorage.setItem('Comfy.userId', 'test-user-e2e') + const recordDestination = (url: string) => { + document.documentElement.dataset.openedUrl = url + } + // A handle whose navigation is recorded rather than performed. Handing + // back the live `window` would let the disowned-tab open -- blank tab, + // null the opener, then assign `location.href` -- steer this page to the + // hosted origin instead. + const standInTab = new Proxy(window, { + get: (target, property) => + property === 'location' + ? { + get href() { + return document.documentElement.dataset.openedUrl ?? '' + }, + set href(destination: string) { + recordDestination(destination) + } + } + : Reflect.get(target, property), + // The tab is disowned before it navigates, and a stand-in that never + // navigates has nothing to disown, so the write is swallowed rather + // than reaching this page's own `window.opener`. + set: () => true + }) // Records the destination instead of opening a tab the test would have to // dismiss. The handle follows the spec: a `noopener` open always yields // null, while a plain one returns a window and keeps the app's // portal-return refresh armed. window.open = (url, _target, features) => { - document.documentElement.dataset.openedUrl = String(url) - return (features ?? '').includes('noopener') ? null : window + if (url) recordDestination(String(url)) + return (features ?? '').includes('noopener') ? null : standInTab } }) await page.goto(APP_URL) From ca7406cc58b402cacb703fe47f5e15d4c90251e4 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Thu, 17 Sep 2026 05:46:40 -0400 Subject: [PATCH 15/15] FE-2216 fix(billing): keep falling through when the rail's portal tab is blocked The hosted branch learned to fall through on a blocked open, but the rail branch below it still returned unconditionally, so a customer whose browser blocks both gets no portal and never reaches the workspace client. The rail suite stubbed window.open to null throughout, which read as harmless while the handle was ignored and as "every tab is blocked" once it was not; it now opens, and the blocked case is asserted where it belongs. --- ...eWorkspaceBilling.subscriptionRail.test.ts | 3 +- .../composables/useWorkspaceBilling.test.ts | 28 +++++++++++++++++-- .../composables/useWorkspaceBilling.ts | 5 +--- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index 3d70853931a..e907b72bf3b 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -165,7 +165,8 @@ beforeEach(() => { status: 'subscribed' }) vi.spyOn(workspaceApi, 'previewSubscribe').mockResolvedValue(LEGACY_QUOTE) - vi.spyOn(window, 'open').mockReturnValue(null) + // A tab that opens, so these routing tests are not all reading as blocked. + vi.spyOn(window, 'open').mockReturnValue(window) vi.mocked(useBillingOperationStore().startOperation).mockResolvedValue({ status: 'succeeded' } as never) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index 7ab82fd5a45..e42757ed169 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -940,7 +940,7 @@ describe('useWorkspaceBilling', () => { ['the legacy client', false, 'https://billing.example/portal'], ['the SDK rail', true, 'https://billing.example/sdk-portal'] ] as const)( - 'falls through to %s when the hosted tab is blocked', + 'attempts %s when the hosted tab is blocked', async ([, railEnabled, fallbackUrl]) => { const openSpy = vi.fn(() => null) vi.stubGlobal('open', openSpy) @@ -962,10 +962,34 @@ describe('useWorkspaceBilling', () => { 'https://billing.comfy.org/v1/payment-methods?product=comfyui&return_to=comfyui_workspace', '_blank' ) - expect(openSpy).toHaveBeenLastCalledWith(fallbackUrl, '_blank') + expect(openSpy).toHaveBeenCalledWith(fallbackUrl, '_blank') } ) + it('reaches the legacy portal when the hosted tab and the rail are both blocked', async () => { + const openSpy = vi.fn(() => null) + vi.stubGlobal('open', openSpy) + vi.stubEnv('VITE_BILLING_WEB_URL', 'https://billing.comfy.org') + localStorage.setItem('ff:hosted_billing_destination', '"billing_web"') + mockRail.enabled = true + mockRail.openPaymentPortal.mockResolvedValue({ + status: 'ok', + value: 'https://billing.example/sdk-portal' + }) + mockWorkspaceApi.getPaymentPortalUrl.mockResolvedValue({ + url: 'https://billing.example/portal' + }) + + const billing = setupBilling() + await billing.manageSubscription() + + expect(mockWorkspaceApi.getPaymentPortalUrl).toHaveBeenCalledTimes(1) + expect(openSpy).toHaveBeenLastCalledWith( + 'https://billing.example/portal', + '_blank' + ) + }) + it('clears a failure from the previous attempt when the hosted route opens', async () => { vi.stubGlobal( 'open', diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index d28d8d1882e..9910623370c 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -562,10 +562,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { const url = await onSubscriptionRail(() => rail.openPaymentPortal(window.location.href) ) - if (url !== DECLINED) { - openPortalWindow(url) - return - } + if (url !== DECLINED && openPortalWindow(url)) return } isLoading.value = true