diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index 381d2d4e034..8540347ab9b 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -61,6 +61,7 @@ import { useAuthStore } from '@/stores/authStore' import type { UserId } from '@/types/authTypes' import { createWebSessionAdapter } from './webSessionAdapter' +import { WorkspaceApiError } from './workspaceApiError' import { workspaceApiUrl } from './workspaceApiUrl' export type WorkspaceType = 'personal' | 'team' @@ -105,6 +106,8 @@ export interface SubscribeOptions { billingCycle?: SubscribeBillingCycle confirmReactivation?: boolean prorationAt?: string + /** Set when the caller reported this attempt's `billing.operation.started`; never sent to the server. */ + attemptStartedAt?: number } export interface PreviewSubscribeOptions { @@ -149,16 +152,7 @@ interface GetBillingEventsParams { limit?: number } -export class WorkspaceApiError extends Error { - constructor( - message: string, - public readonly status?: number, - public readonly code?: string - ) { - super(message) - this.name = 'WorkspaceApiError' - } -} +export { WorkspaceApiError } const workspaceApiClient = axios.create({ headers: { diff --git a/src/platform/workspace/api/workspaceApiError.ts b/src/platform/workspace/api/workspaceApiError.ts new file mode 100644 index 00000000000..3b3e67bddf2 --- /dev/null +++ b/src/platform/workspace/api/workspaceApiError.ts @@ -0,0 +1,14 @@ +/** + * A leaf module, so a subclass can be declared wherever the class is needed + * without pulling the workspace client and its stores into the import graph. + */ +export class WorkspaceApiError extends Error { + constructor( + message: string, + public readonly status?: number, + public readonly code?: string + ) { + super(message) + this.name = 'WorkspaceApiError' + } +} diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 705b868a427..29c17e80274 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -25,7 +25,12 @@ import { settledOperation, settledTopup } from './billingSdkTestUtils' -import type { HostedBillingDestination } from '@comfyorg/account-core/billing' +import type { + BillingOperationKind, + BillingOperationTelemetryEvent, + HostedBillingDestination +} from '@comfyorg/account-core/billing' +import { BILLING_OPERATION_TELEMETRY_EVENT } from '@comfyorg/account-core/billing' import type { BillingSdk, BillingSdkOptions } from './createBillingSdk' const mockCreateBillingSdk = vi.hoisted(() => @@ -508,7 +513,7 @@ describe('useBillingSdkStore subscription commands', () => { await expect(useBillingSdkStore().cancelSubscription()).resolves.toEqual({ status: 'ok', - value: undefined + value: { operationObserved: true } }) expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() @@ -520,7 +525,7 @@ describe('useBillingSdkStore subscription commands', () => { await expect(useBillingSdkStore().resubscribe()).resolves.toEqual({ status: 'ok', - value: undefined + value: { operationObserved: true } }) expect( useBillingContext().reconcileSubscriptionSuccess @@ -569,7 +574,8 @@ describe('useBillingSdkStore subscription commands', () => { value: { billing_op_id: 'op-1', status: 'subscribed', - requiredPayment: false + requiredPayment: false, + operationObserved: true } }) expect(harness.sdk.commands.subscribe).toHaveBeenCalledWith({ @@ -888,6 +894,160 @@ describe('useBillingSdkStore subscription commands', () => { }) }) +describe('useBillingSdkStore telemetry ownership', () => { + type Store = ReturnType + + const SETTLED = { + status: 'ok', + value: { + phase: 'succeeded', + operation: settledOperation('succeeded', 'subscription') + } + } as const + + const EVENTS = { + started: { name: 'started', resumed: false }, + 'resumed started': { name: 'started', resumed: true }, + terminal: { name: 'succeeded', resumed: false }, + 'resumed terminal': { name: 'succeeded', resumed: true } + } as const + + function lifecycleEvent( + kind: BillingOperationKind, + { name, resumed }: (typeof EVENTS)[keyof typeof EVENTS] + ): BillingOperationTelemetryEvent { + return { + name: BILLING_OPERATION_TELEMETRY_EVENT[name], + billing_op_id: 'op-1', + operation_type: kind, + presentation: 'hosted', + resumed + } + } + + const COMMANDS = { + 'a cancel': { + kind: 'cancel', + stub: (fire: () => void) => + vi + .mocked(harness.sdk.commands.cancelSubscription) + .mockImplementation(async () => { + fire() + return SETTLED + }), + run: (store: Store) => store.cancelSubscription() + }, + 'a subscribe the caller announced': { + kind: 'subscription', + stub: (fire: () => void) => + vi + .mocked(harness.sdk.commands.subscribe) + .mockImplementation(async () => { + fire() + return SETTLED + }), + run: (store: Store) => + store.subscribe({ plan_slug: 'pro-yearly' }, { callerStarted: true }) + }, + 'a subscribe no caller announced': { + kind: 'subscription', + stub: (fire: () => void) => + vi + .mocked(harness.sdk.commands.subscribe) + .mockImplementation(async () => { + fire() + return SETTLED + }), + run: (store: Store) => store.subscribe({ plan_slug: 'pro-yearly' }) + }, + 'a resubscribe': { + kind: 'subscription', + stub: (fire: () => void) => + vi + .mocked(harness.sdk.commands.resubscribe) + .mockImplementation(async () => { + fire() + return SETTLED + }), + run: (store: Store) => store.resubscribe() + } + } as const + + it.for([ + { command: 'a cancel', event: 'started', reports: 0 }, + { command: 'a cancel', event: 'resumed started', reports: 1 }, + { command: 'a cancel', event: 'terminal', reports: 1 }, + { command: 'a cancel', event: 'resumed terminal', reports: 1 }, + { + command: 'a subscribe the caller announced', + event: 'started', + reports: 0 + }, + { + command: 'a subscribe the caller announced', + event: 'resumed started', + reports: 1 + }, + { + command: 'a subscribe the caller announced', + event: 'terminal', + reports: 1 + }, + { + command: 'a subscribe the caller announced', + event: 'resumed terminal', + reports: 1 + }, + { + command: 'a subscribe no caller announced', + event: 'started', + reports: 1 + }, + { + command: 'a subscribe no caller announced', + event: 'resumed started', + reports: 1 + }, + { + command: 'a subscribe no caller announced', + event: 'terminal', + reports: 1 + }, + { + command: 'a subscribe no caller announced', + event: 'resumed terminal', + reports: 1 + }, + { command: 'a resubscribe', event: 'started', reports: 1 }, + { command: 'a resubscribe', event: 'resumed started', reports: 1 }, + { command: 'a resubscribe', event: 'terminal', reports: 1 }, + { command: 'a resubscribe', event: 'resumed terminal', reports: 1 } + ] as const)( + 'reports $reports event(s) for a lifecycle $event inside $command', + async ({ command, event, reports }) => { + const { kind, stub, run } = COMMANDS[command] + const store = useBillingSdkStore() + stub(() => options.onTelemetry(lifecycleEvent(kind, EVENTS[event]))) + + await run(store) + + expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledTimes(reports) + } + ) + + it('reports a started that arrives once the announced command has settled', async () => { + const store = useBillingSdkStore() + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( + SETTLED + ) + await store.cancelSubscription() + + options.onTelemetry(lifecycleEvent('cancel', EVENTS.started)) + + expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledOnce() + }) +}) + describe('useBillingSdkStore operation projections', () => { const otherWorkspace = { userId: 'uid-1', diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index 0eb083cff26..014a06d9561 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -6,6 +6,7 @@ * dialog performs for the operations it issues itself. */ import type { + BillingOperationKind, BillingOperationState, BillingEventsReadOptions, BillingOperationTelemetryEvent, @@ -41,8 +42,7 @@ import type { BillingStatusResponse, CreateTopupResponse, PreviewSubscribeResponse, - SavedPaymentMethod, - SubscribeResponse + SavedPaymentMethod } from '@/platform/workspace/api/workspaceApi' import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl' import { needsCustomerAttention } from '@/platform/workspace/billing/customerAttention' @@ -59,7 +59,11 @@ import { projectBillingStatus } from './billingStatusView' import { createBillingSdk } from './createBillingSdk' import type { BillingOperationRecordView } from './operationRecordView' import { projectOperationRecord } from './operationRecordView' -import type { SubscriptionRailOutcome } from './subscriptionOperationView' +import type { + SettledCommand, + SettledSubscribeResponse, + SubscriptionRailOutcome +} from './subscriptionOperationView' import { projectPaymentPortalResult, projectPreviewSubscribeResult, @@ -107,6 +111,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { const operations = shallowRef([]) const dismissed = shallowRef>(new Set()) const resumedOperations = new Set() + const callerStarted = new Set() const drivenChallenges = new Set() const offeredActions = new Map>() const progressToasts = new Map< @@ -206,20 +211,36 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { // A top-up the dialog issued is reported by the dialog, exactly as before; // the lifecycle's events stand in for the poller's only on an operation - // this tab reattached to. A cancel or resubscribe has no such second - // reporter on this rail — the poller owned both ends of it on the legacy - // one — so the lifecycle's events are the only ones it emits. + // this tab reattached to. A cancel or subscribe the caller announced with + // its own `started` keeps that one event: the lifecycle's `started` is + // dropped inside the caller's command window, and its terminal is always + // forwarded, since only the lifecycle holds the operation's id, category + // and timing. A command no caller announced — a resubscribe, a checkout + // that reports nothing — is reported at both ends by the lifecycle. function reportTelemetry(event: BillingOperationTelemetryEvent) { if (event.operation_type === 'topup' && !event.resumed) return - if ( - event.resumed && - event.name === BILLING_OPERATION_TELEMETRY_EVENT.started - ) { - resumedOperations.add(event.billing_op_id) + const started = event.name === BILLING_OPERATION_TELEMETRY_EVENT.started + if (started && event.resumed) resumedOperations.add(event.billing_op_id) + if (started && !event.resumed && callerStarted.has(event.operation_type)) { + return } useTelemetry()?.trackBillingEvent(toBillingTelemetryEvent(event)) } + // Sound because the lifecycle runs one command per kind at a time and + // emits both of an issued operation's events before the command resolves. + async function withCallerStart( + kind: BillingOperationKind, + run: () => Promise + ): Promise { + callerStarted.add(kind) + try { + return await run() + } finally { + callerStarted.delete(kind) + } + } + function onTopupChanged(state: BillingOperationState) { if (state.phase === 'pending') { syncProgressToast(state, 'topup') @@ -429,15 +450,19 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { ]) } - function cancelSubscription(): Promise { - return runSubscriptionCommand( - async () => - projectSubscriptionResult(await sdk.commands.cancelSubscription()), - refreshAfterCancel + function cancelSubscription(): Promise< + SubscriptionRailOutcome + > { + return withCallerStart('cancel', () => + runSubscriptionCommand( + async () => + projectSubscriptionResult(await sdk.commands.cancelSubscription()), + refreshAfterCancel + ) ) } - function resubscribe(): Promise { + function resubscribe(): Promise> { return runSubscriptionCommand( async () => projectSubscriptionResult(await sdk.commands.resubscribe()), refreshAfterSubscriptionChange @@ -445,12 +470,15 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { } function subscribe( - input: SubscribeInput - ): Promise> { - return runSubscriptionCommand( - async () => projectSubscribeResult(await sdk.commands.subscribe(input)), - refreshAfterSubscriptionChange - ) + input: SubscribeInput, + { callerStarted: announced = false }: { callerStarted?: boolean } = {} + ): Promise> { + const run = () => + runSubscriptionCommand( + async () => projectSubscribeResult(await sdk.commands.subscribe(input)), + refreshAfterSubscriptionChange + ) + return announced ? withCallerStart('subscription', run) : run() } // A quote changes nothing, so it refreshes nothing; it shares the route diff --git a/src/platform/workspace/billing/sdk/billingSdkTelemetryOwnership.test.ts b/src/platform/workspace/billing/sdk/billingSdkTelemetryOwnership.test.ts new file mode 100644 index 00000000000..800be8ed024 --- /dev/null +++ b/src/platform/workspace/billing/sdk/billingSdkTelemetryOwnership.test.ts @@ -0,0 +1,539 @@ +import { + BILLING_STATUS_ROUTE, + CANCEL_SUBSCRIPTION_ROUTE, + CAPABILITIES_ROUTE, + CREDITS_ROUTE, + PAYMENT_METHODS_ROUTE, + PREVIEW_SUBSCRIBE_ROUTE, + RESUBSCRIBE_ROUTE, + SUBSCRIBE_ROUTE, + TOPUP_ROUTE, + operationRoute +} from '@comfyorg/account-core/billing' +import type { + AccountCredential, + SessionSnapshot +} from '@comfyorg/account-core/session' +import userEvent from '@testing-library/user-event' +import { render, screen } from '@testing-library/vue' +import { fromPartial } from '@total-typescript/shoehorn' +import type { User } from 'firebase/auth' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' +import { computed, effectScope } from 'vue' + +import type { SubscriptionInfo } from '@/composables/billing/types' +import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { i18n } from '@/i18n' +import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' +import { useTelemetry } from '@/platform/telemetry' +import type { + Plan, + WorkspaceWithRole +} from '@/platform/workspace/api/workspaceApi' +import TopUpCreditsDialogContentWorkspace from '@/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue' +import { useDowngradeToPersonal } from '@/platform/workspace/composables/useDowngradeToPersonal' +import { useSubscriptionCheckout } from '@/platform/workspace/composables/useSubscriptionCheckout' +import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' +import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { useDialogStore } from '@/stores/dialogStore' +import { + stubAccountIdentityPort, + stubFirebaseAuthHarness +} from '@/utils/__tests__/stubAccountIdentityPort' + +vi.mock(import('@/platform/telemetry')) +vi.mock(import('@/composables/useFeatureFlags')) +vi.mock(import('@/composables/billing/useBillingContext')) +vi.mock(import('@/platform/workspace/composables/useBillingCapabilities')) +vi.mock(import('@/platform/workspace/composables/useWorkspaceUI')) +vi.mock(import('@/platform/settings/composables/useSettingsDialog')) +vi.mock(import('firebase/auth')) +vi.mock( + import('@/platform/cloud/subscription/composables/useBillingPlans'), + () => ({ + useBillingPlans: () => ({ + plans: { value: [] }, + currentPlanSlug: { value: null }, + error: { value: null }, + fetchPlans: vi.fn() + }) + }) +) +vi.mock( + import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports + () => ({ + useToast: () => ({ add: vi.fn(), remove: vi.fn(), removeGroup: vi.fn() }) + }) +) + +const CREDENTIAL: AccountCredential = { + token: 'workspace-jwt', + expiresAt: Date.now() + 60 * 60 * 1000, + uid: 'uid-1', + workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, + role: 'owner', + permissions: ['workspace:read'] +} + +const SNAPSHOT: SessionSnapshot = { + phase: 'authenticated', + user: fromPartial({ uid: 'uid-1' }), + session: CREDENTIAL +} + +const PERSONAL_WORKSPACE: WorkspaceWithRole = { + id: 'ws-1', + name: 'Personal', + type: 'personal', + role: 'owner', + created_at: '2026-01-01T00:00:00Z', + joined_at: '2026-01-01T00:00:00Z' +} + +const STANDARD_YEARLY: Plan = { + slug: 'standard-yearly', + tier: 'STANDARD', + duration: 'ANNUAL', + price_cents: 1600, + credits_cents: 4200, + max_seats: 1, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: 1600, + total_credits_cents: 4200 + } +} + +const ACTIVE_SUBSCRIPTION: SubscriptionInfo = { + isActive: true, + tier: 'PRO', + duration: 'MONTHLY', + planSlug: 'pro-monthly', + scheduledChange: null, + renewalDate: null, + endDate: null, + isCancelled: false, + hasFunds: true, + agentHasFunds: true +} + +const DOWNGRADE_PREVIEW = { + allowed: true, + transition_type: 'downgrade', + effective_at: '2026-10-01T00:00:00.000Z', + is_immediate: true, + cost_today_cents: 0, + cost_next_period_cents: 1600, + credits_today_cents: 0, + credits_next_period_cents: 4200, + new_plan: { + slug: 'standard-yearly', + tier: 'STANDARD', + duration: 'ANNUAL', + price_cents: 1600, + credits_cents: 4200, + seat_summary: { + seat_count: 1, + total_cost_cents: 1600, + total_credits_cents: 4200 + } + } +} + +const STATUS = { + billing_rail: 'stripe', + has_funds: true, + is_active: true, + max_seats: 1, + occupied_seats: 1, + scheduled_change: null, + team_credit_stop: null +} + +const CAPABILITIES = { + capabilities: { + can_cancel: true, + can_change_seats: false, + can_downgrade_to_personal: false, + can_invite_members: false, + can_reactivate: true, + can_subscribe_self_serve: true, + can_top_up: true + }, + expires_at: new Date(Date.now() + 10 * 60 * 1000).toISOString(), + resolved_for: { user_id: 'uid-1', workspace_id: 'ws-1' }, + revision: 1, + rollout_defaults_applied: { + can_downgrade_to_personal: false, + can_subscribe_self_serve: false, + can_top_up: false + } +} + +const PAYMENT_METHODS = [ + { brand: 'visa', id: 'pm_1', is_default: true, last4: '4242', type: 'card' } +] + +interface ServerAnswer { + readonly status: number + readonly body: unknown +} + +type ServerRoute = readonly ['GET' | 'POST', string, ServerAnswer] + +function issuedThenSettled( + route: string, + issued: Record, + settled: Record +): readonly ServerRoute[] { + return [ + [ + 'POST', + route, + { status: 200, body: { billing_op_id: 'op-1', ...issued } } + ], + [ + 'GET', + operationRoute('op-1'), + { + status: 200, + body: { id: 'op-1', started_at: '2026-09-14T00:00:00.000Z', ...settled } + } + ] + ] +} + +function rejected(route: string): readonly ServerRoute[] { + return [ + [ + 'POST', + route, + { + status: 402, + body: { code: 'OUTSTANDING_INVOICE', message: 'Settle the invoice' } + } + ] + ] +} + +function alreadyHeld(route: string, code: string): readonly ServerRoute[] { + return [ + ['POST', route, { status: 409, body: { code, message: 'Already there' } }] + ] +} + +function previewed(routes: readonly ServerRoute[]): readonly ServerRoute[] { + return [ + ...routes, + ['POST', PREVIEW_SUBSCRIBE_ROUTE, { status: 200, body: DOWNGRADE_PREVIEW }] + ] +} + +function fakeServer() { + const answers = new Map() + const unanswered: string[] = [] + const fetchImpl: typeof fetch = async (input, init) => { + const { pathname } = new URL(String(input)) + const route = pathname.slice(pathname.indexOf('/billing/')) + const key = `${init?.method ?? 'GET'} ${route}` + const answer = answers.get(key) + if (!answer) { + unanswered.push(key) + return new Response('', { status: 500 }) + } + return new Response(JSON.stringify(answer.body), { status: answer.status }) + } + return { + fetchImpl, + unanswered, + script(routes: readonly ServerRoute[]) { + for (const [method, route, answer] of routes) { + answers.set(`${method} ${route}`, answer) + } + } + } +} + +let server: ReturnType + +beforeEach(() => { + stubAccountIdentityPort() + stubFirebaseAuthHarness() + server = fakeServer() + server.script([ + ['GET', BILLING_STATUS_ROUTE, { status: 200, body: STATUS }], + [ + 'GET', + CREDITS_ROUTE, + { status: 200, body: { amount_micros: 1_000_000, currency: 'USD' } } + ], + ['GET', CAPABILITIES_ROUTE, { status: 200, body: CAPABILITIES }], + ['GET', PAYMENT_METHODS_ROUTE, { status: 200, body: PAYMENT_METHODS }] + ]) + vi.stubGlobal('fetch', server.fetchImpl) + const session = useWorkspaceAuthStore().getUnifiedSessionClient() + vi.spyOn(session, 'getSnapshot').mockReturnValue(SNAPSHOT) + vi.spyOn(session, 'ensureFresh').mockResolvedValue({ + status: 'ok', + session: CREDENTIAL + }) + vi.spyOn(session, 'remint').mockResolvedValue({ + status: 'ok', + session: CREDENTIAL + }) + vi.mocked(useFeatureFlags().flags).billingSdkSubscriptionRailEnabled = true + vi.mocked(useFeatureFlags().flags).billingSdkTopupRailEnabled = true + vi.mocked(useBillingContext).mockReturnValue(useBillingContext()) + Object.assign(useTeamWorkspaceStore(), { + activeWorkspace: PERSONAL_WORKSPACE, + activeWorkspaceId: PERSONAL_WORKSPACE.id + }) +}) + +function workspaceBilling() { + const scope = effectScope() + const billing = scope.run(() => useWorkspaceBilling()) + assert.exists(billing) + return billing +} + +function driveWorkspaceBilling(action: 'cancelSubscription' | 'resubscribe') { + return async () => { + await workspaceBilling() + [action]() + .catch(() => undefined) + } +} + +async function driveCheckoutSubscribe() { + Object.assign(useBillingContext(), { + subscribe: workspaceBilling().subscribe, + plans: computed(() => [STANDARD_YEARLY]) + }) + let checkout: ReturnType | undefined + render( + { + setup() { + checkout = useSubscriptionCheckout(() => {}) + return () => null + } + }, + { global: { plugins: [i18n] } } + ) + assert.exists(checkout) + checkout.selectedTierKey.value = 'standard' + await checkout.handleConfirmTransition() +} + +async function driveLegacyStripeCheckoutSubscribe() { + useTeamWorkspaceStore().setWorkspaceBillingRail('ws-1', 'legacy_stripe') + await driveCheckoutSubscribe() +} + +async function driveDowngrade() { + const billing = workspaceBilling() + Object.assign(useBillingContext(), { + subscribe: billing.subscribe, + previewSubscribe: billing.previewSubscribe, + subscription: computed(() => ACTIVE_SUBSCRIPTION) + }) + const { permissions } = useWorkspaceUI() + useWorkspaceUI().permissions = computed(() => ({ + ...permissions.value, + canDowngradeToPersonal: true + })) + await useDowngradeToPersonal() + .downgradeToPersonal('standard-yearly') + .catch(() => undefined) +} + +async function driveTopupDialog() { + vi.mocked(useDialogStore().closeDialog).mockImplementation(() => {}) + render(TopUpCreditsDialogContentWorkspace, { + global: { + plugins: [i18n], + stubs: { + FormattedNumberStepper: { + name: 'FormattedNumberStepper', + props: ['modelValue'], + template: '
' + } + } + } + }) + const user = userEvent.setup() + await user.click(screen.getByRole('button', { name: 'Add credits' })) + const pay = await screen.findByRole('button', { name: /^Pay / }) + await vi.waitFor(() => expect(pay).toBeEnabled()) + await user.click(pay) + await vi.waitFor(() => + expect(useSettingsDialog().show).toHaveBeenCalledOnce() + ) +} + +function operationEvents() { + const telemetry = useTelemetry() + assert.exists(telemetry) + return vi.mocked(telemetry.trackBillingEvent).mock.calls.flatMap(([event]) => + event.operation === 'operation' + ? [ + { + stage: event.stage, + ...(event.billing_op_id === undefined + ? {} + : { billing_op_id: event.billing_op_id }), + ...('failure_category' in event + ? { failure_category: event.failure_category } + : {}) + } + ] + : [] + ) +} + +const STARTED = { stage: 'started' } as const +const SUCCEEDED = { stage: 'succeeded', billing_op_id: 'op-1' } as const +const DECLINED = { + stage: 'failed', + billing_op_id: 'op-1', + failure_category: 'provider_decline' +} as const +const REFUSED = { stage: 'failed', failure_category: 'api_rejected' } as const + +describe('billing operation telemetry ownership on the SDK rail', () => { + it.for([ + { + name: 'cancel succeeds', + routes: issuedThenSettled( + CANCEL_SUBSCRIPTION_ROUTE, + { status: 'pending' }, + { status: 'succeeded' } + ), + drive: driveWorkspaceBilling('cancelSubscription'), + expected: [STARTED, SUCCEEDED] + }, + { + name: 'cancel settles failed after issue', + routes: issuedThenSettled( + CANCEL_SUBSCRIPTION_ROUTE, + { status: 'pending' }, + { status: 'failed', decline_reason: 'generic' } + ), + drive: driveWorkspaceBilling('cancelSubscription'), + expected: [ + STARTED, + { + stage: 'failed', + billing_op_id: 'op-1', + failure_category: 'api_rejected' + } + ] + }, + { + name: 'cancel is rejected before any operation exists', + routes: rejected(CANCEL_SUBSCRIPTION_ROUTE), + drive: driveWorkspaceBilling('cancelSubscription'), + expected: [STARTED, REFUSED] + }, + { + name: 'cancel finds the subscription already cancelled', + routes: alreadyHeld(CANCEL_SUBSCRIPTION_ROUTE, 'ALREADY_CANCELED'), + drive: driveWorkspaceBilling('cancelSubscription'), + expected: [STARTED, { stage: 'succeeded' }] + }, + { + name: 'subscribe succeeds', + routes: issuedThenSettled( + SUBSCRIBE_ROUTE, + { status: 'pending_payment' }, + { status: 'succeeded' } + ), + drive: driveCheckoutSubscribe, + expected: [STARTED, SUCCEEDED] + }, + { + name: 'subscribe settles declined', + routes: issuedThenSettled( + SUBSCRIBE_ROUTE, + { status: 'pending_payment' }, + { status: 'failed', decline_reason: 'card_declined', retryable: true } + ), + drive: driveCheckoutSubscribe, + expected: [STARTED, DECLINED] + }, + { + name: 'subscribe is rejected before any operation exists', + routes: rejected(SUBSCRIBE_ROUTE), + drive: driveCheckoutSubscribe, + expected: [STARTED, REFUSED] + }, + { + name: 'a checkout that reports no started subscribes', + routes: issuedThenSettled( + SUBSCRIBE_ROUTE, + { status: 'pending_payment' }, + { status: 'succeeded' } + ), + drive: driveLegacyStripeCheckoutSubscribe, + expected: [STARTED, SUCCEEDED] + }, + { + name: 'downgrade to personal succeeds', + routes: previewed( + issuedThenSettled( + SUBSCRIBE_ROUTE, + { status: 'pending_payment' }, + { status: 'succeeded' } + ) + ), + drive: driveDowngrade, + expected: [STARTED, SUCCEEDED] + }, + { + name: 'downgrade to personal settles declined', + routes: previewed( + issuedThenSettled( + SUBSCRIBE_ROUTE, + { status: 'pending_payment' }, + { status: 'failed', decline_reason: 'card_declined', retryable: true } + ) + ), + drive: driveDowngrade, + expected: [STARTED, DECLINED] + }, + { + name: 'resubscribe succeeds', + routes: issuedThenSettled( + RESUBSCRIBE_ROUTE, + { status: 'pending' }, + { status: 'succeeded' } + ), + drive: driveWorkspaceBilling('resubscribe'), + expected: [STARTED, SUCCEEDED] + }, + { + name: 'top-up succeeds', + routes: issuedThenSettled( + TOPUP_ROUTE, + { amount_cents: 5000, status: 'pending', topup_id: 'topup-1' }, + { status: 'succeeded' } + ), + drive: driveTopupDialog, + expected: [STARTED, SUCCEEDED] + } + ] as const)( + 'reports one started and one terminal operation event when $name', + async ({ routes, drive, expected }) => { + server.script(routes) + + await drive() + + expect(server.unanswered).toEqual([]) + expect(operationEvents()).toEqual(expected) + } + ) +}) diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts index d9d22ffa1af..88228cfa265 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.test.ts @@ -9,13 +9,14 @@ import { settledOperation } from './billingSdkTestUtils' import { + SettledOperationError, projectPaymentPortalResult, projectSubscribeResult, projectSubscriptionResult } from './subscriptionOperationView' describe('projectSubscriptionResult', () => { - it('reports a settled command as done', () => { + it('reports a settled command as done, with its operation observed', () => { const result: SubscriptionCommandResult = { status: 'ok', value: { phase: 'succeeded', operation: settledOperation('succeeded') } @@ -23,14 +24,14 @@ describe('projectSubscriptionResult', () => { expect(projectSubscriptionResult(result)).toEqual({ status: 'ok', - value: undefined + value: { operationObserved: true } }) }) - it('reports a request the server refused as already satisfied', () => { + it('reports a request the server refused as already satisfied, with no operation observed', () => { expect( projectSubscriptionResult({ status: 'ok', value: { phase: 'succeeded' } }) - ).toEqual({ status: 'ok', value: undefined }) + ).toEqual({ status: 'ok', value: { operationObserved: false } }) }) it.for([ @@ -81,7 +82,7 @@ describe('projectSubscriptionResult', () => { detail: "We couldn't update your subscription. Please try again." } ] as const)( - 'reports a $phase operation as a sentence for the customer', + 'reports a $phase operation as a settled failure with a sentence for the customer', ({ phase, operation, detail }) => { const outcome = projectSubscriptionResult({ status: 'ok', @@ -89,9 +90,13 @@ describe('projectSubscriptionResult', () => { }) expect(outcome).toMatchObject({ status: 'error' }) - expect( - outcome.status === 'error' ? outcome.error : undefined - ).toMatchObject({ message: detail, code: phase }) + const error = outcome.status === 'error' ? outcome.error : undefined + expect(error).toBeInstanceOf(SettledOperationError) + expect(error).toMatchObject({ + message: detail, + code: phase, + billingOpId: 'op-1' + }) } ) @@ -158,14 +163,18 @@ describe('projectSubscriptionResult', () => { 'A payment you started earlier is still going through. It has to finish before you can choose a different plan.' } ] - ] as const)('surfaces %o as a workspace error', ([failure, expected]) => { - const outcome = projectSubscriptionResult(failure) + ] as const)( + 'surfaces %o as a workspace error the caller still owns', + ([failure, expected]) => { + const outcome = projectSubscriptionResult(failure) - expect(outcome.status).toBe('error') - const error = outcome.status === 'error' ? outcome.error : undefined - expect(error).toBeInstanceOf(WorkspaceApiError) - expect(error).toMatchObject(expected) - }) + expect(outcome.status).toBe('error') + const error = outcome.status === 'error' ? outcome.error : undefined + expect(error).toBeInstanceOf(WorkspaceApiError) + expect(error).not.toBeInstanceOf(SettledOperationError) + expect(error).toMatchObject(expected) + } + ) }) describe('projectSubscribeResult', () => { @@ -191,7 +200,8 @@ describe('projectSubscribeResult', () => { value: { billing_op_id: 'op-1', status: 'subscribed', - requiredPayment + requiredPayment, + operationObserved: true } }) } @@ -210,7 +220,7 @@ describe('projectSubscribeResult', () => { detail: "We couldn't update your subscription. Please try again." } ] as const)( - 'reports a $phase subscribe as a sentence for the customer', + 'reports a $phase subscribe as a settled failure with a sentence for the customer', ({ phase, operation, detail }) => { const outcome = projectSubscribeResult({ status: 'ok', @@ -218,9 +228,13 @@ describe('projectSubscribeResult', () => { }) expect(outcome).toMatchObject({ status: 'error' }) - expect( - outcome.status === 'error' ? outcome.error : undefined - ).toMatchObject({ message: detail, code: phase }) + const error = outcome.status === 'error' ? outcome.error : undefined + expect(error).toBeInstanceOf(SettledOperationError) + expect(error).toMatchObject({ + message: detail, + code: phase, + billingOpId: 'op-1' + }) } ) }) diff --git a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts index 008cd2d0843..8e6ce9a22b3 100644 --- a/src/platform/workspace/billing/sdk/subscriptionOperationView.ts +++ b/src/platform/workspace/billing/sdk/subscriptionOperationView.ts @@ -22,22 +22,41 @@ import type { PreviewSubscribeResponse, SubscribeResponse } from '@/platform/workspace/api/workspaceApi' -import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' +import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApiError' import { declineDetail } from './topupOperationView' +/** False only when the server said the state already held: no operation was issued, so the lifecycle reported nothing. */ +export interface SettledCommand { + readonly operationObserved: boolean +} + /** * 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. + * same line. `operationObserved` is set on the same rail, for the same reason + * as on `SettledCommand`. */ -export interface SettledSubscribeResponse extends SubscribeResponse { +export interface SettledSubscribeResponse + extends SubscribeResponse, Partial { readonly requiredPayment?: boolean } +/** The lifecycle drove the operation to a failed terminal and reported it; a refused attempt stays a plain `WorkspaceApiError` for the caller to report. */ +export class SettledOperationError extends WorkspaceApiError { + constructor( + message: string, + phase: string, + readonly billingOpId: string | undefined + ) { + super(message, undefined, phase) + this.name = 'SettledOperationError' + } +} + import type { BillingOperationRecordView } from './operationRecordView' export type SubscriptionRailOutcome = @@ -67,14 +86,16 @@ export interface SubscriptionRail { readonly subscriptionActionOperation: BillingOperationRecordView | undefined /** One operation by id, unscoped: the caller compares the workspace itself. */ getOperation: (opId: string) => BillingOperationRecordView | undefined + /** `callerStarted`: the caller reported `started`, so the rail reports only the terminal. */ subscribe: ( - input: SubscribeInput + input: SubscribeInput, + options?: { readonly callerStarted?: boolean } ) => Promise> previewSubscribe: ( input: PreviewSubscribeInput ) => Promise> - cancelSubscription: () => Promise - resubscribe: () => Promise + cancelSubscription: () => Promise> + resubscribe: () => Promise> openPaymentPortal: ( returnUrl: string ) => Promise> @@ -82,7 +103,15 @@ export interface SubscriptionRail { const UNAVAILABLE = { status: 'unavailable' } as const -const SETTLED: SubscriptionRailOutcome = { status: 'ok', value: undefined } +const OBSERVED: SubscriptionRailOutcome = { + status: 'ok', + value: { operationObserved: true } +} + +const ALREADY_HELD: SubscriptionRailOutcome = { + status: 'ok', + value: { operationObserved: false } +} /** * The failure as the adapter's own error. `serverCode` lands where the @@ -134,27 +163,28 @@ function projectUnsuccessfulSettle( const { operation, phase } = outcome return { status: 'error', - error: new WorkspaceApiError( + error: new SettledOperationError( operation?.phase === 'failed' ? declineDetail(operation.declineReason) : t('billingOperation.subscriptionFailedDetail'), - undefined, - phase + phase, + operation?.id ) } } /** * A command that settled anywhere but `succeeded` failed for the customer, - * exactly as a poller operation that ends in any other status does. + * exactly as a poller operation that ends in any other status does. A success + * with no operation is the server saying the state already held. */ export function projectSubscriptionResult( result: SubscriptionCommandResult -): SubscriptionRailOutcome { +): SubscriptionRailOutcome { if (result.status === 'error') return projectFailure(result) - return result.value.phase === 'succeeded' - ? SETTLED - : projectUnsuccessfulSettle(result.value) + const { phase, operation } = result.value + if (phase !== 'succeeded') return projectUnsuccessfulSettle(result.value) + return operation === undefined ? ALREADY_HELD : OBSERVED } /** @@ -186,7 +216,8 @@ export function projectSubscribeResult( value: { billing_op_id: operation.id, status: 'subscribed', - requiredPayment: issuedStatus !== 'subscribed' + requiredPayment: issuedStatus !== 'subscribed', + operationObserved: true } } } diff --git a/src/platform/workspace/composables/useDowngradeToPersonal.test.ts b/src/platform/workspace/composables/useDowngradeToPersonal.test.ts index 22d3097e2b1..be15d8bed1e 100644 --- a/src/platform/workspace/composables/useDowngradeToPersonal.test.ts +++ b/src/platform/workspace/composables/useDowngradeToPersonal.test.ts @@ -312,7 +312,8 @@ describe('useDowngradeToPersonal', () => { { returnUrl: 'https://platform.test/payment/success', cancelUrl: 'https://platform.test/payment/failed', - confirmReactivation: false + confirmReactivation: false, + attemptStartedAt: expect.any(Number) } ) }) @@ -351,7 +352,8 @@ describe('useDowngradeToPersonal', () => { { returnUrl: 'https://platform.test/payment/success', cancelUrl: 'https://platform.test/payment/failed', - confirmReactivation: true + confirmReactivation: true, + attemptStartedAt: expect.any(Number) } ) }) @@ -467,7 +469,8 @@ describe('useDowngradeToPersonal', () => { { returnUrl: 'https://platform.test/payment/success', cancelUrl: 'https://platform.test/payment/failed', - confirmReactivation: false + confirmReactivation: false, + attemptStartedAt: expect.any(Number) } ) }) @@ -493,7 +496,8 @@ describe('useDowngradeToPersonal', () => { { returnUrl: 'https://platform.test/payment/success', cancelUrl: 'https://platform.test/payment/failed', - confirmReactivation: false + confirmReactivation: false, + attemptStartedAt: expect.any(Number) } ) }) diff --git a/src/platform/workspace/composables/useDowngradeToPersonal.ts b/src/platform/workspace/composables/useDowngradeToPersonal.ts index 8d17be0d706..3c39e91cf0b 100644 --- a/src/platform/workspace/composables/useDowngradeToPersonal.ts +++ b/src/platform/workspace/composables/useDowngradeToPersonal.ts @@ -14,6 +14,7 @@ import type { BillingFailure } from '@/platform/telemetry/types' import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' import type { PreviewSubscribeResponse } from '@/platform/workspace/api/workspaceApi' import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView' +import { SettledOperationError } 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' @@ -165,7 +166,7 @@ export function useDowngradeToPersonal() { member_removal_failures: 0 }) - function trackSucceeded() { + function trackSucceeded(operationObserved: boolean) { const now = Date.now() telemetry?.trackBillingEvent({ operation: 'downgrade_to_personal', @@ -186,6 +187,7 @@ export function useDowngradeToPersonal() { checkout_type: 'change', duration_ms: now - checkoutStartedAt }) + if (operationObserved) return telemetry?.trackBillingEvent({ operation: 'operation', stage: 'succeeded', @@ -289,7 +291,8 @@ export function useDowngradeToPersonal() { returnUrl: `${getComfyPlatformBaseUrl()}/payment/success`, cancelUrl: `${getComfyPlatformBaseUrl()}/payment/failed`, confirmReactivation, - ...(preview.proration_at && { prorationAt: preview.proration_at }) + ...(preview.proration_at && { prorationAt: preview.proration_at }), + attemptStartedAt: checkoutStartedAt }) } catch (error) { if ( @@ -371,7 +374,7 @@ export function useDowngradeToPersonal() { return null } - trackSucceeded() + trackSucceeded(response.operationObserved === true) return { preview, response } } catch (error) { const failure = telemetryFailure ?? { @@ -399,17 +402,19 @@ export function useDowngradeToPersonal() { ...failure, duration_ms: now - checkoutStartedAt }) - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'failed', - outcome: 'failure', - operation_type: 'subscription', - tier: targetTier, - cycle: targetCycle, - checkout_type: 'change', - ...failure, - duration_ms: now - checkoutStartedAt - }) + if (!(error instanceof SettledOperationError)) { + telemetry?.trackBillingEvent({ + operation: 'operation', + stage: 'failed', + outcome: 'failure', + operation_type: 'subscription', + tier: targetTier, + cycle: targetCycle, + checkout_type: 'change', + ...failure, + duration_ms: now - checkoutStartedAt + }) + } } throw error } diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index aa8d2856f8b..1070c3ab0b3 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -3011,7 +3011,8 @@ describe('useSubscriptionCheckout', () => { billingCycle: 'monthly', returnUrl: 'https://app.test/subscribe', cancelUrl: 'https://platform.comfy.org/payment/failed', - confirmReactivation: false + confirmReactivation: false, + attemptStartedAt: expect.any(Number) }) expect(checkout.checkoutStep.value).toBe('success') expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith( @@ -4328,7 +4329,8 @@ describe('useSubscriptionCheckout', () => { expect(mockSubscribe).toHaveBeenCalledWith('standard-yearly', { returnUrl: 'https://app.test/subscribe', cancelUrl: 'https://platform.comfy.org/payment/failed', - confirmReactivation: false + confirmReactivation: false, + attemptStartedAt: expect.any(Number) }) expect(checkout.checkoutStep.value).toBe('success') expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.ts b/src/platform/workspace/composables/useSubscriptionCheckout.ts index 1e285002ea4..fcb3ab3e6ab 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.ts @@ -35,6 +35,7 @@ import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { openHostedBillingTab } from '@/platform/workspace/billing/openHostedBillingTab' import { registerRefreshOnReturn } from '@/platform/workspace/billing/refreshOnReturn' import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView' +import { SettledOperationError } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { readOnRail } from '@/platform/workspace/composables/readOnRail' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useBillingReadRail } from '@/platform/workspace/composables/useBillingReadRail' @@ -1187,7 +1188,8 @@ export function useSubscriptionCheckout( confirmReactivation, prorationAt: previewData.value?.is_immediate ? previewData.value.proration_at - : undefined + : undefined, + attemptStartedAt }) if (response) { @@ -1481,6 +1483,7 @@ export function useSubscriptionCheckout( ...(errorCode && { error_code: errorCode }), duration_ms: Date.now() - context.attemptStartedAt }) + if (error instanceof SettledOperationError) return telemetry?.trackBillingEvent({ operation: 'operation', stage: 'failed', @@ -1532,18 +1535,20 @@ export function useSubscriptionCheckout( billing_op_id: response.billing_op_id, duration_ms: durationMs }) - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'succeeded', - outcome: 'success', - operation_type: 'subscription', - tier: context.tier, - cycle: context.cycle, - checkout_type: context.checkoutType, - payment_intent_source: paymentIntentSource, - billing_op_id: response.billing_op_id, - duration_ms: durationMs - }) + if (!response.operationObserved) { + telemetry?.trackBillingEvent({ + operation: 'operation', + stage: 'succeeded', + outcome: 'success', + operation_type: 'subscription', + tier: context.tier, + cycle: context.cycle, + checkout_type: context.checkoutType, + payment_intent_source: paymentIntentSource, + billing_op_id: response.billing_op_id, + duration_ms: durationMs + }) + } if (response.requiredPayment) { telemetry?.trackMonthlySubscriptionSucceeded({ tier: context.tier, @@ -1767,7 +1772,8 @@ export function useSubscriptionCheckout( confirmReactivation, prorationAt: previewData.value?.is_immediate ? previewData.value.proration_at - : undefined + : undefined, + attemptStartedAt }) if (response) { diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index 4832ca50afc..ebdd5c6c749 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -269,7 +269,7 @@ describe('cancel telemetry on the billing SDK rail', () => { return vi.mocked(trackBillingEvent).mock.calls.map(([event]) => event.stage) } - it('reports a rail cancel that settles as one started and one succeeded', async () => { + it('reports one started and leaves the terminal to the lifecycle when a rail cancel settles an operation', async () => { flagState.billingSdkSubscriptionEnabled = true vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( SETTLED @@ -277,6 +277,18 @@ describe('cancel telemetry on the billing SDK rail', () => { await setupBilling().cancelSubscription() + expect(stages()).toEqual(['started']) + }) + + it('reports one started and one succeeded when the server says the cancel already held', async () => { + flagState.billingSdkSubscriptionEnabled = true + vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue({ + status: 'ok', + value: { phase: 'succeeded' } + }) + + await setupBilling().cancelSubscription() + expect(stages()).toEqual(['started', 'succeeded']) }) @@ -389,7 +401,8 @@ describe('subscribe on the billing SDK rail', () => { expect(response).toEqual({ billing_op_id: 'op-1', status: 'subscribed', - requiredPayment: false + requiredPayment: false, + operationObserved: true }) expect(workspaceApi.subscribe).not.toHaveBeenCalled() }) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 64214a754b0..a04c46c0393 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -37,6 +37,7 @@ import type { SettledSubscribeResponse, SubscriptionRailOutcome } from '@/platform/workspace/billing/sdk/subscriptionOperationView' +import { SettledOperationError } from '@/platform/workspace/billing/sdk/subscriptionOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { readOnRail } from '@/platform/workspace/composables/readOnRail' import type { BillingReadRail } from '@/platform/workspace/composables/useBillingReadRail' @@ -461,7 +462,9 @@ export function useWorkspaceBilling(): WorkspaceBilling { const rail = useSubscriptionRail() if (rail) { const response = await onSubscriptionRail(() => - rail.subscribe(subscribeInputFrom(planSlug, options)) + rail.subscribe(subscribeInputFrom(planSlug, options), { + callerStarted: options?.attemptStartedAt !== undefined + }) ) // The SDK waited for the operation, so the refresh the legacy path fires // and forgets has already run on the rail. @@ -645,11 +648,11 @@ export function useWorkspaceBilling(): WorkspaceBilling { const settled = await onSubscriptionRail(() => rail.cancelSubscription() ).catch((err: unknown) => { - trackCancelFailed(err) + if (!(err instanceof SettledOperationError)) trackCancelFailed(err) throw err }) if (settled !== DECLINED) { - trackCancelSucceeded() + if (!settled.operationObserved) trackCancelSucceeded() return } }