From fcb75458ae00b7f92be4388b4b01bb2cda5f8ee9 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 08:04:54 -0400 Subject: [PATCH 1/5] test: prove the SDK operation mapper drops billing_op_id, presentation, resumed and decline_reason --- .../telemetry/billingTelemetryEvent.test.ts | 57 ++++++- .../billing/sdk/billingSdkStore.test.ts | 7 + .../billing/sdk/billingSdkTelemetry.test.ts | 161 ++++++++++++------ 3 files changed, 174 insertions(+), 51 deletions(-) diff --git a/src/platform/telemetry/billingTelemetryEvent.test.ts b/src/platform/telemetry/billingTelemetryEvent.test.ts index c554e1a1afe..b907f9fe7ba 100644 --- a/src/platform/telemetry/billingTelemetryEvent.test.ts +++ b/src/platform/telemetry/billingTelemetryEvent.test.ts @@ -1,6 +1,7 @@ -import { describe, expectTypeOf, it } from 'vitest' +import { describe, expect, expectTypeOf, it } from 'vitest' import type { BillingTelemetryEvent } from './types' +import { getBillingTelemetryEventPayload } from './types' type LateSuccessEvent = Extract< BillingTelemetryEvent, @@ -15,3 +16,57 @@ describe('BillingTelemetryEvent', () => { >() }) }) + +describe('getBillingTelemetryEventPayload', () => { + it("keeps the SDK rail's presentation, resumption and decline reason", () => { + const sdkFailure = { + operation: 'operation', + stage: 'failed', + outcome: 'failure', + operation_type: 'topup', + billing_op_id: 'op-declined', + presentation: 'embedded', + resumed: false, + failure_category: 'provider_decline', + decline_reason: 'card_declined', + duration_ms: 2300 + } as const + + expect(getBillingTelemetryEventPayload(sdkFailure)).toStrictEqual({ + operation: 'operation', + stage: 'failed', + outcome: 'failure', + operation_type: 'topup', + billing_op_id: 'op-declined', + presentation: 'embedded', + resumed: false, + failure_category: 'provider_decline', + decline_reason: 'card_declined', + duration_ms: 2300 + }) + }) + + it("leaves the poller's operation event, which has none of them, unchanged", () => { + expect( + getBillingTelemetryEventPayload({ + operation: 'operation', + stage: 'failed', + outcome: 'failure', + operation_type: 'subscription', + billing_op_id: 'op-polled', + tier: 'pro', + failure_category: 'provider_decline', + duration_ms: 4200 + }) + ).toStrictEqual({ + operation: 'operation', + stage: 'failed', + outcome: 'failure', + operation_type: 'subscription', + billing_op_id: 'op-polled', + tier: 'pro', + failure_category: 'provider_decline', + duration_ms: 4200 + }) + }) +}) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 705b868a427..27b7c17d9a9 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -293,6 +293,9 @@ describe('useBillingSdkStore', () => { expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'operation', operation_type: 'topup', + billing_op_id: 'op-1', + presentation: 'hosted', + resumed: true, stage: 'started', outcome: 'pending' }) @@ -300,6 +303,8 @@ describe('useBillingSdkStore', () => { operation: 'operation', operation_type: 'topup', billing_op_id: 'op-1', + presentation: 'hosted', + resumed: true, duration_ms: 1200, stage: 'succeeded', outcome: 'success' @@ -447,6 +452,8 @@ describe('useBillingSdkStore', () => { operation: 'operation', operation_type: 'cancel', billing_op_id: 'op-cancel', + presentation: 'hosted', + resumed: false, duration_ms: 900, stage: 'succeeded', outcome: 'success' diff --git a/src/platform/workspace/billing/sdk/billingSdkTelemetry.test.ts b/src/platform/workspace/billing/sdk/billingSdkTelemetry.test.ts index c476509c68e..aadb6e22e56 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTelemetry.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTelemetry.test.ts @@ -1,65 +1,126 @@ +import type { BillingOperationTelemetryEvent } from '@comfyorg/account-core/billing' import { describe, expect, it } from 'vitest' import { toBillingTelemetryEvent } from './billingSdkTelemetry' describe('toBillingTelemetryEvent', () => { - it('reports a start without a duration or an id, as the poller does', () => { - expect( - toBillingTelemetryEvent({ + it.for<{ + name: string + event: BillingOperationTelemetryEvent + expected: Record + }>([ + { + name: 'a start, paired to its terminal by operation id', + event: { name: 'billing.operation.started', - billing_op_id: 'op-1', + billing_op_id: 'op-start', operation_type: 'topup', presentation: 'hosted', resumed: true - }) - ).toEqual({ - operation: 'operation', - operation_type: 'topup', - stage: 'started', - outcome: 'pending' - }) - }) - - it.for([ - [ - 'billing.operation.succeeded', - undefined, - { stage: 'succeeded', outcome: 'success' } - ], - [ - 'billing.operation.failed', - 'reconciliation_needed', - { + }, + expected: { + operation: 'operation', + stage: 'started', + outcome: 'pending', + operation_type: 'topup', + billing_op_id: 'op-start', + presentation: 'hosted', + resumed: true + } + }, + { + name: 'a success with its duration', + event: { + name: 'billing.operation.succeeded', + billing_op_id: 'op-success', + operation_type: 'subscription', + presentation: 'embedded', + resumed: false, + duration_ms: 1500 + }, + expected: { + operation: 'operation', + stage: 'succeeded', + outcome: 'success', + operation_type: 'subscription', + billing_op_id: 'op-success', + presentation: 'embedded', + resumed: false, + duration_ms: 1500 + } + }, + { + name: 'a declined failure with its decline reason', + event: { + name: 'billing.operation.failed', + billing_op_id: 'op-declined', + operation_type: 'topup', + presentation: 'embedded', + resumed: true, + failure_category: 'provider_decline', + decline_reason: 'insufficient_funds', + duration_ms: 2300 + }, + expected: { + operation: 'operation', + stage: 'failed', + outcome: 'failure', + operation_type: 'topup', + billing_op_id: 'op-declined', + presentation: 'embedded', + resumed: true, + failure_category: 'provider_decline', + decline_reason: 'insufficient_funds', + duration_ms: 2300 + } + }, + { + name: 'a failure the provider never declined, without a decline reason', + event: { + name: 'billing.operation.failed', + billing_op_id: 'op-reconcile', + operation_type: 'cancel', + presentation: 'hosted', + resumed: false, + failure_category: 'reconciliation_needed', + duration_ms: 900 + }, + expected: { + operation: 'operation', stage: 'failed', outcome: 'failure', - failure_category: 'reconciliation_needed' + operation_type: 'cancel', + billing_op_id: 'op-reconcile', + presentation: 'hosted', + resumed: false, + failure_category: 'reconciliation_needed', + duration_ms: 900 } - ], - [ - 'billing.operation.timeout', - 'poll_timeout', - { stage: 'timeout', outcome: 'failure', failure_category: 'poll_timeout' } - ] - ] as const)( - 'maps %s onto the terminal payload with its category and duration', - ([name, category, expected]) => { - expect( - toBillingTelemetryEvent({ - name, - billing_op_id: 'op-1', - operation_type: 'topup', - presentation: 'embedded', - resumed: false, - ...(category === undefined ? {} : { failure_category: category }), - duration_ms: 1500 - }) - ).toEqual({ + }, + { + name: 'a timeout as a poll timeout', + event: { + name: 'billing.operation.timeout', + billing_op_id: 'op-timeout', + operation_type: 'subscription', + presentation: 'hosted', + resumed: true, + failure_category: 'poll_timeout', + duration_ms: 600_000 + }, + expected: { operation: 'operation', - operation_type: 'topup', - billing_op_id: 'op-1', - duration_ms: 1500, - ...expected - }) + stage: 'timeout', + outcome: 'failure', + operation_type: 'subscription', + billing_op_id: 'op-timeout', + presentation: 'hosted', + resumed: true, + failure_category: 'poll_timeout', + duration_ms: 600_000 + } } - ) + ])('maps $name', ({ event, expected }) => { + expect(toBillingTelemetryEvent(event)).toEqual(expected) + }) }) From fb4e3041f4ef92ed7d3a1806ca2177f39c60a779 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 08:08:16 -0400 Subject: [PATCH 2/5] fix: keep billing_op_id, presentation, resumed and decline_reason on the mapped SDK operation event --- src/platform/telemetry/types.ts | 18 ++++++++++++- .../billing/sdk/billingSdkTelemetry.ts | 25 +++++++++---------- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/src/platform/telemetry/types.ts b/src/platform/telemetry/types.ts index 5b48a6ec6e4..f3b792bdd49 100644 --- a/src/platform/telemetry/types.ts +++ b/src/platform/telemetry/types.ts @@ -16,6 +16,10 @@ import { AUTH_TELEMETRY_EVENT, SESSION_TELEMETRY_EVENT } from '@comfyorg/account-core/telemetry' +import type { + BillingDeclineReason, + BillingPresentation +} from '@comfyorg/account-core/billing' import type { AgentRunMode, CreateTopupResponse, @@ -1364,6 +1368,10 @@ type BillingOperationBillingEvent = { /** Absent when the initiating call itself failed, before the backend returned one to poll. */ billing_op_id?: string operation_type: 'subscription' | 'topup' | 'cancel' + /** Set by the billing SDK rail, as is `resumed`; the poller never sets either. */ + presentation?: BillingPresentation + /** True when this tab reattached to an operation it did not issue. */ + resumed?: boolean tier?: SubscriptionCheckoutTier cycle?: BillingCycle checkout_type?: SubscriptionCheckoutType @@ -1376,7 +1384,12 @@ type BillingOperationBillingEvent = { * true duration. */ duration_ms?: number -} & (BillingStarted | BillingSucceeded | BillingFailed | BillingTimedOut) +} & ( + | BillingStarted + | BillingSucceeded + | (BillingFailed & { decline_reason?: BillingDeclineReason }) + | BillingTimedOut +) type ResubscribeBillingEvent = { operation: 'resubscribe' @@ -1467,10 +1480,13 @@ const BILLING_PAYLOAD_FIELD_HANDLING = { checkout_attempt_id: 'optional', checkout_type: 'optional', cycle: 'optional', + decline_reason: 'optional', duration_ms: 'optional', error_code: 'optional', payment_intent_source: 'optional', + presentation: 'optional', recovery_outcome: 'optional', + resumed: 'optional', target_tier: 'optional', tier: 'optional' } as const satisfies Record diff --git a/src/platform/workspace/billing/sdk/billingSdkTelemetry.ts b/src/platform/workspace/billing/sdk/billingSdkTelemetry.ts index ded84a31b19..85f6eebcd29 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTelemetry.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTelemetry.ts @@ -4,16 +4,19 @@ import { BILLING_OPERATION_TELEMETRY_EVENT } from '@comfyorg/account-core/billin import type { BillingTelemetryEvent } from '@/platform/telemetry/types' /** - * The lifecycle's event onto the `billing.operation.*` payload the poller - * emits today, so a dashboard cannot tell which rail observed the operation. + * The lifecycle's event onto the poller's `billing.operation.*` stages, so + * both rails count in one funnel; only this rail sets `presentation` and + * `resumed`. */ export function toBillingTelemetryEvent( event: BillingOperationTelemetryEvent ): BillingTelemetryEvent { - const terminal = { + const shared = { operation: 'operation', operation_type: event.operation_type, billing_op_id: event.billing_op_id, + presentation: event.presentation, + resumed: event.resumed, ...(event.duration_ms === undefined ? {} : { duration_ms: event.duration_ms }) @@ -21,27 +24,23 @@ export function toBillingTelemetryEvent( switch (event.name) { case BILLING_OPERATION_TELEMETRY_EVENT.started: - return { - operation: 'operation', - operation_type: event.operation_type, - stage: 'started', - outcome: 'pending' - } + return { ...shared, stage: 'started', outcome: 'pending' } case BILLING_OPERATION_TELEMETRY_EVENT.succeeded: - return { ...terminal, stage: 'succeeded', outcome: 'success' } + return { ...shared, stage: 'succeeded', outcome: 'success' } case BILLING_OPERATION_TELEMETRY_EVENT.timeout: return { - ...terminal, + ...shared, stage: 'timeout', outcome: 'failure', failure_category: 'poll_timeout' } case BILLING_OPERATION_TELEMETRY_EVENT.failed: return { - ...terminal, + ...shared, stage: 'failed', outcome: 'failure', - failure_category: event.failure_category ?? 'provider_decline' + failure_category: event.failure_category ?? 'provider_decline', + decline_reason: event.decline_reason } } } From e872839f4c621af7d277ca290ebdcf0790948b92 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 08:25:13 -0400 Subject: [PATCH 3/5] test: prove the SDK top-up dialog drops the timeout, operation id and decline reason --- ...TopUpCreditsDialogContentWorkspace.test.ts | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index 2e731b24744..d2ac1d03b07 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -1,3 +1,13 @@ +import type { TopupResult } from '@comfyorg/account-core/billing' + +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import type { BillingTelemetryEvent } from '@/platform/telemetry/types' +import { + failedTopup, + fakeBillingSdk, + settledTopup +} from '@/platform/workspace/billing/sdk/billingSdkTestUtils' +import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingSdk' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { @@ -65,6 +75,13 @@ vi.mock(import('@/platform/settings/composables/useSettingsDialog')) vi.mock(import('@/platform/telemetry')) +vi.mock(import('@/composables/useFeatureFlags')) + +const mockCreateBillingSdk = vi.hoisted(() => vi.fn<() => BillingSdk>()) +vi.mock(import('@/platform/workspace/billing/sdk/createBillingSdk'), () => ({ + createBillingSdk: mockCreateBillingSdk +})) + vi.mock(import('firebase/auth'), { spy: true }) const mockClearPendingTopup = vi.hoisted(() => vi.fn()) vi.mock(import('@/composables/billing/usePendingTopup'), () => ({ @@ -142,6 +159,27 @@ function setHasSavedPaymentMethod(value: boolean | null) { mockHasSavedPaymentMethod.ref.value = value } +const SPARSE_BILLING_FIELDS: ReadonlySet = new Set([ + 'stage', + 'operation_type', + 'billing_op_id', + 'failure_category', + 'decline_reason' +]) + +function billingEvents(operation: BillingTelemetryEvent['operation']) { + return vi + .mocked(useTelemetry()!.trackBillingEvent) + .mock.calls.filter(([event]) => event.operation === operation) + .map(([event]) => + Object.fromEntries( + Object.entries(event).filter(([field]) => + SPARSE_BILLING_FIELDS.has(field) + ) + ) + ) +} + async function clickAddCredits() { const user = userEvent.setup() await user.click(screen.getByRole('button', { name: 'Add credits' })) @@ -1127,4 +1165,136 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(mockToastAdd).not.toHaveBeenCalled() expect(useDialogStore().closeDialog).not.toHaveBeenCalled() }) + + describe('on the billing SDK rail', () => { + it.for<{ + outcome: string + result: TopupResult + operationTerminal: Record + topupTerminal: Record + }>([ + { + outcome: 'a settled purchase', + result: { + status: 'ok', + operation: settledTopup('succeeded'), + creditsReconciled: true + }, + operationTerminal: { stage: 'succeeded', billing_op_id: 'op-1' }, + topupTerminal: { stage: 'succeeded', billing_op_id: 'op-1' } + }, + { + outcome: 'a purchase this tab stopped watching', + result: { status: 'unsettled', operation: settledTopup('timed_out') }, + operationTerminal: { + stage: 'timeout', + billing_op_id: 'op-1', + failure_category: 'poll_timeout' + }, + topupTerminal: { + stage: 'failed', + billing_op_id: 'op-1', + failure_category: 'poll_timeout' + } + }, + { + outcome: 'a decline', + result: { + status: 'declined', + operation: failedTopup('insufficient_funds') + }, + operationTerminal: { + stage: 'failed', + billing_op_id: 'op-1', + failure_category: 'provider_decline', + decline_reason: 'insufficient_funds' + }, + topupTerminal: { + stage: 'failed', + billing_op_id: 'op-1', + failure_category: 'provider_decline' + } + }, + { + outcome: 'a purchase support must reconcile', + result: { + status: 'unsettled', + operation: settledTopup('reconciliation_needed') + }, + operationTerminal: { + stage: 'failed', + billing_op_id: 'op-1', + failure_category: 'reconciliation_needed' + }, + topupTerminal: { + stage: 'failed', + billing_op_id: 'op-1', + failure_category: 'reconciliation_needed' + } + }, + { + outcome: 'a refusal that carries no HTTP status', + result: { + status: 'error', + code: 'NO_PAYMENT_METHOD', + recoveryAction: 'replace_payment_method' + }, + operationTerminal: { + stage: 'failed', + failure_category: 'api_rejected' + }, + topupTerminal: { stage: 'failed', failure_category: 'api_rejected' } + }, + { + outcome: 'a purchase the scope moved out from under', + result: { status: 'error', code: 'SUPERSEDED' }, + operationTerminal: { + stage: 'failed', + failure_category: 'stale_operation' + }, + topupTerminal: { stage: 'failed', failure_category: 'stale_operation' } + }, + { + outcome: 'an amount the request contract refused', + result: { status: 'error', code: 'INVALID_AMOUNT' }, + operationTerminal: { stage: 'failed', failure_category: 'validation' }, + topupTerminal: { stage: 'failed', failure_category: 'validation' } + }, + { + outcome: 'a request that never reached the server', + result: { status: 'error', code: 'REQUEST_FAILED' }, + operationTerminal: { stage: 'failed', failure_category: 'network' }, + topupTerminal: { stage: 'failed', failure_category: 'network' } + } + ])( + 'reports $outcome as one terminal carrying what the SDK settled', + async ({ result, operationTerminal, topupTerminal }) => { + const harness = fakeBillingSdk() + mockCreateBillingSdk.mockReturnValue(harness.sdk) + vi.mocked(harness.sdk.topup.createTopupCheckout).mockResolvedValue( + result + ) + vi.mocked(useFeatureFlags().flags).billingSdkTopupRailEnabled = true + vi.spyOn(console, 'error').mockImplementation(() => {}) + + renderDialog() + await clickAddCredits() + await userEvent.click( + screen.getByRole('button', { name: 'Pay $50.00' }) + ) + + await waitFor(() => + expect(billingEvents('operation')).toEqual([ + { stage: 'started', operation_type: 'topup' }, + { operation_type: 'topup', ...operationTerminal } + ]) + ) + expect(billingEvents('topup')).toEqual([ + { stage: 'intent' }, + { stage: 'started' }, + topupTerminal + ]) + } + ) + }) }) From 1b8a24f25ebd718688f9c8ba7c97d69916d2a0af Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 08:33:53 -0400 Subject: [PATCH 4/5] fix: report the timeout, operation id and decline reason from the SDK top-up dialog --- src/platform/telemetry/types.ts | 13 +- .../telemetry/utils/billingFailureCategory.ts | 4 +- src/platform/workspace/api/workspaceApi.ts | 5 +- .../billing/sdk/topupOperationView.test.ts | 4 +- .../billing/sdk/topupOperationView.ts | 88 +++++++++-- .../TopUpCreditsDialogContentWorkspace.vue | 139 ++++++++++-------- 6 files changed, 167 insertions(+), 86 deletions(-) diff --git a/src/platform/telemetry/types.ts b/src/platform/telemetry/types.ts index f3b792bdd49..830a6e43e48 100644 --- a/src/platform/telemetry/types.ts +++ b/src/platform/telemetry/types.ts @@ -1340,6 +1340,12 @@ type BillingTimedOut = { failure_category: 'poll_timeout' } +/** The stage one attempt at a billing operation settled on. */ +export type BillingOperationTerminal = + | BillingSucceeded + | (BillingFailed & { decline_reason?: BillingDeclineReason }) + | BillingTimedOut + type SubscriptionCheckoutBillingEvent = { operation: 'subscription_checkout' billing_op_id?: string @@ -1384,12 +1390,7 @@ type BillingOperationBillingEvent = { * true duration. */ duration_ms?: number -} & ( - | BillingStarted - | BillingSucceeded - | (BillingFailed & { decline_reason?: BillingDeclineReason }) - | BillingTimedOut -) +} & (BillingStarted | BillingOperationTerminal) type ResubscribeBillingEvent = { operation: 'resubscribe' diff --git a/src/platform/telemetry/utils/billingFailureCategory.ts b/src/platform/telemetry/utils/billingFailureCategory.ts index 7d973d1b9e5..c8f50a42012 100644 --- a/src/platform/telemetry/utils/billingFailureCategory.ts +++ b/src/platform/telemetry/utils/billingFailureCategory.ts @@ -4,7 +4,8 @@ import { AuthStoreError } from '@/stores/authStore' import type { BillingFailure } from '../types' /** - * A `WorkspaceApiError`/`AuthStoreError` with no `status` never reached the + * A `WorkspaceApiError` that names its category keeps it. Otherwise a + * `WorkspaceApiError`/`AuthStoreError` with no `status` never reached the * backend (`network`); a `TypeError` naming fetch/network/load is what `fetch` * throws for connectivity failures. */ @@ -12,6 +13,7 @@ export function categorizeBillingApiError( err: unknown ): BillingFailure['failure_category'] { if (err instanceof WorkspaceApiError) { + if (err.failureCategory) return err.failureCategory return err.status === undefined ? 'network' : 'api_rejected' } if (err instanceof AuthStoreError) { diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index 381d2d4e034..3b0ca23d01b 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -46,6 +46,7 @@ import { webSessionSend } from '@/platform/auth/session/webSessionFetch' import { useTelemetry } from '@/platform/telemetry' +import type { BillingFailure } from '@/platform/telemetry/types' import { attachUnifiedRemintInterceptor } from '@/platform/auth/unified/remintRetry' import { churnkeyAuthResponseSchema } from '@/platform/cloud/churnkey/churnkeyAuthSchema' import { @@ -153,7 +154,9 @@ export class WorkspaceApiError extends Error { constructor( message: string, public readonly status?: number, - public readonly code?: string + public readonly code?: string, + /** For a failure `status` cannot classify, such as a billing SDK refusal. */ + public readonly failureCategory?: BillingFailure['failure_category'] ) { super(message) this.name = 'WorkspaceApiError' diff --git a/src/platform/workspace/billing/sdk/topupOperationView.test.ts b/src/platform/workspace/billing/sdk/topupOperationView.test.ts index 8bf7ff24413..40bc237e5f6 100644 --- a/src/platform/workspace/billing/sdk/topupOperationView.test.ts +++ b/src/platform/workspace/billing/sdk/topupOperationView.test.ts @@ -89,13 +89,13 @@ describe('projectTopupResult', () => { ).toMatchObject({ billing_op_id: 'op-1', status: 'failed' }) }) - it('reports nothing for a purchase this tab stopped observing', () => { + it('reports a purchase this tab stopped observing as still pending', () => { expect( projectTopupResult( { status: 'unsettled', operation: settledTopup('timed_out') }, 1000 ) - ).toBeUndefined() + ).toMatchObject({ billing_op_id: 'op-1', status: 'pending' }) }) it('throws the API error whose code the dialog already handles', () => { diff --git a/src/platform/workspace/billing/sdk/topupOperationView.ts b/src/platform/workspace/billing/sdk/topupOperationView.ts index 3ac45920304..f4af702f226 100644 --- a/src/platform/workspace/billing/sdk/topupOperationView.ts +++ b/src/platform/workspace/billing/sdk/topupOperationView.ts @@ -1,8 +1,8 @@ /** * Projections from the SDK's operation state and top-up result onto the two * shapes the top-up dialog already reads: the poller's operation record and - * the `CreateTopupResponse` the legacy call returned. The dialog is untouched; - * these give it the same inputs from the other rail. + * the `CreateTopupResponse` the legacy call returned, plus the terminal the + * SDK observed where those shapes cannot hold it. */ import type { BillingDeclineReason, @@ -16,6 +16,10 @@ import { } from '@comfyorg/account-core/billing' import { t } from '@/i18n' +import type { + BillingFailure, + BillingOperationTerminal +} from '@/platform/telemetry/types' import type { BillingAuthenticationState, BillingOperationPhase, @@ -72,36 +76,98 @@ export function projectTopupOperation( } } +/** + * A purchase the SDK settled without crediting, as the response the dialog + * handles, carrying the terminal its status cannot: the decline reason, or + * that this tab stopped watching, or that support must reconcile it. + */ +export class UncreditedTopupResponse implements CreateTopupResponse { + readonly topup_id = '' + + constructor( + readonly billing_op_id: string, + readonly status: 'failed' | 'pending', + readonly amount_cents: number, + readonly terminal: BillingOperationTerminal + ) {} +} + +/** + * Most SDK refusals carry no HTTP status, which a status-less API error + * would otherwise report as a network failure, so each names its category. + */ function topupFailureError(failure: TopupFailure): WorkspaceApiError { const serverCode = 'serverCode' in failure ? failure.serverCode : undefined return new WorkspaceApiError( t('credits.topUp.unknownError'), 'httpStatus' in failure ? failure.httpStatus : undefined, - serverCode === undefined ? failure.code : unwrapServerCode(serverCode) + serverCode === undefined ? failure.code : unwrapServerCode(serverCode), + topupFailureCategory(failure) ) } +function topupFailureCategory( + failure: TopupFailure +): BillingFailure['failure_category'] { + switch (failure.code) { + case 'REQUEST_FAILED': + return failure.httpStatus === undefined ? 'network' : 'api_rejected' + case 'SUPERSEDED': + return 'stale_operation' + case 'INVALID_AMOUNT': + return 'validation' + default: + return 'api_rejected' + } +} + /** - * A settled result as the response the dialog handles today. `unsettled` has - * no counterpart: the dialog reads an undefined response as "nothing to - * report" and the operation stays visible through `projectTopupOperation`. - * `topup_id` is not surfaced by the SDK and nothing reads it. + * A settled result as the response the dialog handles today. `unsettled` is + * the pending response: the server may still settle it, and the operation + * stays visible through `projectTopupOperation`. `topup_id` is not surfaced + * by the SDK and nothing reads it. */ export function projectTopupResult( result: TopupResult, amountCents: number -): CreateTopupResponse | undefined { +): CreateTopupResponse { switch (result.status) { case 'ok': - case 'declined': return { billing_op_id: result.operation.id, topup_id: '', - status: result.status === 'ok' ? 'completed' : 'failed', + status: 'completed', amount_cents: amountCents } + case 'declined': + return new UncreditedTopupResponse( + result.operation.id, + 'failed', + amountCents, + { + stage: 'failed', + outcome: 'failure', + failure_category: 'provider_decline', + decline_reason: result.operation.declineReason + } + ) case 'unsettled': - return undefined + return new UncreditedTopupResponse( + result.operation.id, + 'pending', + amountCents, + result.operation.phase === 'timed_out' + ? { + stage: 'timeout', + outcome: 'failure', + failure_category: 'poll_timeout' + } + : { + stage: 'failed', + outcome: 'failure', + failure_category: 'reconciliation_needed' + } + ) case 'error': throw topupFailureError(result) } diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue index 396e0608f46..546682dae4c 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue @@ -303,14 +303,17 @@ import { useTelemetry } from '@/platform/telemetry' import { usePendingTopup } from '@/composables/billing/usePendingTopup' import { isCloud } from '@/platform/distribution/types' import type { + BillingOperationTerminal, CheckoutJourneyPhaseEvent, PaymentIntentSource } from '@/platform/telemetry/types' import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' import { reportError } from '@/platform/telemetry/reportError' +import type { CreateTopupResponse } from '@/platform/workspace/api/workspaceApi' import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { isBlockedOnCustomerPhase } from '@/platform/workspace/billing/customerAttention' +import { UncreditedTopupResponse } from '@/platform/workspace/billing/sdk/topupOperationView' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { useHasSavedPaymentMethod } from '@/platform/workspace/composables/useHasSavedPaymentMethod' import { useTopupOperation } from '@/platform/workspace/composables/useTopupOperation' @@ -620,21 +623,10 @@ async function handleBuy() { const response = await topup(amountCents) if (!response) { if (isCurrentAttempt()) paymentSubmitted.value = false - telemetry?.trackBillingEvent({ - operation: 'topup', + reportTerminal(attemptStartedAt, { stage: 'failed', outcome: 'failure', - payment_intent_source: source, - failure_category: 'unknown', - duration_ms: Date.now() - attemptStartedAt - }) - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'failed', - outcome: 'failure', - operation_type: 'topup', - failure_category: 'unknown', - duration_ms: Date.now() - attemptStartedAt + failure_category: 'unknown' }) return } @@ -657,28 +649,20 @@ async function handleBuy() { } } + const terminal = + response instanceof UncreditedTopupResponse + ? response.terminal + : RESPONSE_TERMINALS[response.status] + if (terminal) { + reportTerminal(attemptStartedAt, terminal, response.billing_op_id) + } + if (response.status === 'completed') { if ( getActiveCheckoutJourney()?.billing_op_id === response.billing_op_id ) { clearCheckoutJourney() } - telemetry?.trackBillingEvent({ - operation: 'topup', - stage: 'succeeded', - outcome: 'success', - billing_op_id: response.billing_op_id, - payment_intent_source: source, - duration_ms: Date.now() - attemptStartedAt - }) - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'succeeded', - outcome: 'success', - operation_type: 'topup', - billing_op_id: response.billing_op_id, - duration_ms: Date.now() - attemptStartedAt - }) toast.add({ severity: 'success', summary: t('credits.topUp.purchaseSuccess'), @@ -705,26 +689,7 @@ async function handleBuy() { ) }) } else { - // Synchronous 'failed' here means the charge was declined, not rejected pre-attempt. if (isCurrentAttempt()) paymentSubmitted.value = false - telemetry?.trackBillingEvent({ - operation: 'topup', - stage: 'failed', - outcome: 'failure', - billing_op_id: response.billing_op_id, - payment_intent_source: source, - failure_category: 'provider_decline', - duration_ms: Date.now() - attemptStartedAt - }) - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'failed', - outcome: 'failure', - operation_type: 'topup', - billing_op_id: response.billing_op_id, - failure_category: 'provider_decline', - duration_ms: Date.now() - attemptStartedAt - }) toast.add({ severity: 'error', summary: t('credits.topUp.purchaseError'), @@ -747,30 +712,74 @@ function reportPurchaseError( if (currentAttempt) paymentSubmitted.value = false console.error('Purchase failed', ...(error === undefined ? [] : [error])) - telemetry?.trackBillingEvent({ - operation: 'topup', + reportTerminal( + attemptStartedAt, + { + stage: 'failed', + outcome: 'failure', + failure_category: + error === undefined ? 'unknown' : categorizeBillingApiError(error) + }, + billingOpId + ) + toast.add({ + severity: 'error', + summary: t('credits.topUp.purchaseError'), + detail: purchaseErrorDetail(error) + }) +} + +/** + * The terminal a response's status implies. A synchronous `failed` is a + * declined charge, not a pre-attempt rejection; a `pending` one is the + * poller's to report once it settles. + */ +const RESPONSE_TERMINALS: Record< + CreateTopupResponse['status'], + BillingOperationTerminal | undefined +> = { + completed: { stage: 'succeeded', outcome: 'success' }, + failed: { stage: 'failed', outcome: 'failure', + failure_category: 'provider_decline' + }, + pending: undefined +} + +function reportTerminal( + attemptStartedAt: number, + terminal: BillingOperationTerminal, + billingOpId?: string +) { + const attempt = { ...(billingOpId ? { billing_op_id: billingOpId } : {}), - payment_intent_source: source, - failure_category: - error === undefined ? 'unknown' : categorizeBillingApiError(error), duration_ms: Date.now() - attemptStartedAt - }) + } + // No timeout stage on the top-up funnel; the poller reports it as failed too. + telemetry?.trackBillingEvent( + terminal.stage === 'succeeded' + ? { + operation: 'topup', + stage: 'succeeded', + outcome: 'success', + payment_intent_source: source, + ...attempt + } + : { + operation: 'topup', + stage: 'failed', + outcome: 'failure', + payment_intent_source: source, + failure_category: terminal.failure_category, + ...attempt + } + ) telemetry?.trackBillingEvent({ operation: 'operation', - stage: 'failed', - outcome: 'failure', operation_type: 'topup', - ...(billingOpId ? { billing_op_id: billingOpId } : {}), - failure_category: - error === undefined ? 'unknown' : categorizeBillingApiError(error), - duration_ms: Date.now() - attemptStartedAt - }) - toast.add({ - severity: 'error', - summary: t('credits.topUp.purchaseError'), - detail: purchaseErrorDetail(error) + ...terminal, + ...attempt }) } From b4020297c1ec143220a2953d514b25807ecc8820 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 08:47:48 -0400 Subject: [PATCH 5/5] fix: keep the top-up dialog's buy handler under the complexity gate --- .../TopUpCreditsDialogContentWorkspace.vue | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue index 546682dae4c..f7b9a38a004 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue @@ -649,13 +649,7 @@ async function handleBuy() { } } - const terminal = - response instanceof UncreditedTopupResponse - ? response.terminal - : RESPONSE_TERMINALS[response.status] - if (terminal) { - reportTerminal(attemptStartedAt, terminal, response.billing_op_id) - } + reportResponseTerminal(response, attemptStartedAt) if (response.status === 'completed') { if ( @@ -747,6 +741,19 @@ const RESPONSE_TERMINALS: Record< pending: undefined } +function reportResponseTerminal( + response: CreateTopupResponse, + attemptStartedAt: number +) { + const terminal = + response instanceof UncreditedTopupResponse + ? response.terminal + : RESPONSE_TERMINALS[response.status] + if (terminal) { + reportTerminal(attemptStartedAt, terminal, response.billing_op_id) + } +} + function reportTerminal( attemptStartedAt: number, terminal: BillingOperationTerminal,