From 509df0611127072d8adc8b88fbdd6a77af41a6c7 Mon Sep 17 00:00:00 2001 From: Dante Date: Tue, 29 Sep 2026 17:32:14 +0000 Subject: [PATCH] FE-3057 feat(billing): show the payment progress in the app while billing-web takes the payment (#19129) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Linear: FE-3057 ## Why With the embedded checkout the app shows "Processing payment — setting up your workspace…" while the payment settles, then "Subscription updated successfully". With the billing-web handoff those toasts appear only in the billing-web tab; the app tab shows nothing until the return refresh re-reads the plan. The owner expects the app to keep showing the payment progress as it did before, with only the checkout screen moved. ## Root cause The app already turns any operation the server reports pending into those toasts: every billing status read calls `resumePendingOperation` (`useWorkspaceBilling.ts`), which hands the operation to the SDK store (`recover()`) or the legacy poller, and both settle with the success / failure toasts. Nothing reads the status while billing-web is paying, so the app never sees the operation billing-web started. ## How - `openHostedBillingTab`: when it opens a `checkout` or `subscription` tab, it re-reads the billing status every 4s for up to 15 minutes. The next open or `disarmHostedBillingReturnRefresh` stops it. Other intents (payment methods, invoices) start no payment and are not watched. - No new toast and no client-side inference: the server's own `pending_billing_op_id` drives the existing resume path. - Relies on #19120 so an operation the app resumes this way never auto-opens a payment page. - CI: red https://github.com/Comfy-Org/ComfyUI_frontend/actions/runs/36357332886 (the two new tests fail), green on fca3937498. ## AS IS / TO BE **AS IS** — the app tab shows nothing while billing-web takes the payment; it only re-reads the plan on return (see the billing-web upgrade recording in #19101: https://github.com/user-attachments/assets/7bb0e7d7-9b89-42e9-8521-330996622f7d). **TO BE** — local build of the stack top + #19120 + #19123 + this PR against testcloud, Stripe test mode, workspace `parity-bw-0927`, Team 295.4K → 527.5K reactivating upgrade paid on billing-web with the 3DS card: mid-payment the app tab shows "Verify your payment to finish setting up your workspace"; after 3DS completes and Close closes the billing tab, the app tab shows "Subscription updated successfully" and the plan is active. https://github.com/user-attachments/assets/8501d67c-9724-4974-9d8c-2a867b633e53 ## Plan position M2 (billing-web checkout in a new tab). Stacked on #19123 (FE-3054, return refresh on every return), off `main`. ```mermaid graph LR R[#19123 FE-3054 refresh on every return] --> W[FE-3057 app shows payment progress]:::me X[#19120 FE-3051 no auto-open on resume] -.relies on.-> W classDef me fill:#f9d71c,stroke:#333,color:#000 ``` --- .../billing/__mocks__/useBillingContext.ts | 3 +- src/composables/billing/types.ts | 2 + .../billing/useBillingContext.test.ts | 23 ++++ src/composables/billing/useBillingContext.ts | 21 +++- .../billing/openHostedBillingTab.test.ts | 116 +++++++++++++++++- .../workspace/billing/openHostedBillingTab.ts | 63 +++++++++- .../workspace/billing/refreshOnReturn.test.ts | 14 +-- .../billing/sdk/billingSdkStore.test.ts | 25 ++++ .../workspace/billing/sdk/billingSdkStore.ts | 6 +- .../composables/useWorkspaceBilling.test.ts | 63 ++++++++++ .../composables/useWorkspaceBilling.ts | 39 ++++-- src/storybook/mocks/useBillingContext.ts | 1 + 12 files changed, 347 insertions(+), 29 deletions(-) diff --git a/src/composables/billing/__mocks__/useBillingContext.ts b/src/composables/billing/__mocks__/useBillingContext.ts index 43732800d82..9778d9e0057 100644 --- a/src/composables/billing/__mocks__/useBillingContext.ts +++ b/src/composables/billing/__mocks__/useBillingContext.ts @@ -41,7 +41,8 @@ function createBillingContextMock(): BillingContext { fetchPlans: vi.fn(async () => {}), requireActiveSubscription: vi.fn(async () => {}), showSubscriptionDialog: vi.fn(), - reconcileSubscriptionSuccess: vi.fn(async () => {}) + reconcileSubscriptionSuccess: vi.fn(async () => {}), + readCheckoutOperation: vi.fn(async () => false) } } diff --git a/src/composables/billing/types.ts b/src/composables/billing/types.ts index 84719722b10..6beb096ae7a 100644 --- a/src/composables/billing/types.ts +++ b/src/composables/billing/types.ts @@ -122,6 +122,8 @@ export interface BillingState { export interface BillingContext extends BillingState, BillingActions { type: ComputedRef reconcileSubscriptionSuccess: () => Promise + /** Reads the checkout rail's status; true once its pending operation is adopted. */ + readCheckoutOperation: () => Promise /** * True when the active team workspace is still on a pre-credit-slider * (legacy) per-member tier plan, which keeps the old team pricing table. diff --git a/src/composables/billing/useBillingContext.test.ts b/src/composables/billing/useBillingContext.test.ts index eb5be1e0d1b..e91d77f6adc 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -519,6 +519,29 @@ describe('useBillingContext', () => { expect(vi.mocked(useAuthStore().fetchBalance)).not.toHaveBeenCalled() }) + it.for([ + { pending: 'op-1', found: true }, + { pending: undefined, found: false } + ])( + 'finds an operation the server reports after the first read (pending: $pending)', + async ({ pending, found }) => { + const context = useBillingContext() + await vi.waitFor(() => + expect(workspaceApi.getBillingStatus).toHaveBeenCalled() + ) + vi.clearAllMocks() + mockBillingStatus.value = { + ...DEFAULT_BILLING_STATUS, + pending_billing_op_id: pending + } + + await expect(context.readCheckoutOperation()).resolves.toBe(found) + + expect(workspaceApi.getBillingStatus).toHaveBeenCalledOnce() + expect(workspaceApi.getBillingBalance).not.toHaveBeenCalled() + } + ) + it('rejects topup amounts that are not positive whole-dollar cents', async () => { const { topup } = useBillingContext() await expect(topup(550)).rejects.toThrow() diff --git a/src/composables/billing/useBillingContext.ts b/src/composables/billing/useBillingContext.ts index 38a9033b83f..c1b3b9ed3b8 100644 --- a/src/composables/billing/useBillingContext.ts +++ b/src/composables/billing/useBillingContext.ts @@ -25,6 +25,7 @@ import type { } from './types' import { useBillingRouting } from './useBillingRouting' import { useLegacyBilling } from './useLegacyBilling' +import type { WorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' // Legacy per-member team plans use a hyphenated `team-{tier}-{cycle}` slug; the @@ -88,9 +89,7 @@ function useBillingContextInternal(): BillingContext { const legacyBillingRef = shallowRef<(BillingState & BillingActions) | null>( null ) - const workspaceBillingRef = shallowRef< - (BillingState & BillingActions) | null - >(null) + const workspaceBillingRef = shallowRef(null) const getLegacyBilling = () => { if (!legacyBillingRef.value) { @@ -293,6 +292,21 @@ function useBillingContextInternal(): BillingContext { await account.fetchBalance() } + /** + * Reads the checkout rail's status, which resumes any operation the server + * reports pending. True once that operation was adopted, so a caller + * watching for a payment taken elsewhere can hand off to its own polling. + */ + async function readCheckoutOperation(): Promise { + const checkout = checkoutContext.value + const workspace = workspaceBillingRef.value + if (workspace === null || checkout !== workspace) { + await checkout.fetchStatus() + return false + } + return workspace.readAndAdoptPendingOperation() + } + async function subscribe(planSlug: string, options?: SubscribeOptions) { return checkoutContext.value.subscribe(planSlug, options) } @@ -372,6 +386,7 @@ function useBillingContextInternal(): BillingContext { fetchStatus, fetchBalance, reconcileSubscriptionSuccess, + readCheckoutOperation, subscribe, previewSubscribe, manageSubscription, diff --git a/src/platform/workspace/billing/openHostedBillingTab.test.ts b/src/platform/workspace/billing/openHostedBillingTab.test.ts index 27521b89b06..9cf967b7593 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.test.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const mockHostedBillingRoute = vi.hoisted(() => vi.fn()) vi.mock( @@ -17,10 +17,12 @@ vi.mock(import('@/composables/useFeatureFlags'), () => ({ const mockFetchStatus = vi.hoisted(() => vi.fn(async () => {})) const mockFetchBalance = vi.hoisted(() => vi.fn(async () => {})) +const mockReadOperation = vi.hoisted(() => vi.fn(async () => false)) vi.mock(import('@/composables/billing/useBillingContext'), () => ({ useBillingContext: () => ({ fetchStatus: mockFetchStatus, - fetchBalance: mockFetchBalance + fetchBalance: mockFetchBalance, + readCheckoutOperation: mockReadOperation }) })) @@ -43,7 +45,10 @@ vi.mock( import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' -import { openHostedBillingTab } from './openHostedBillingTab' +import { + disarmHostedBillingReturnRefresh, + openHostedBillingTab +} from './openHostedBillingTab' const BILLING_WEB_ROUTE = { kind: 'billing_web' as const, @@ -165,4 +170,109 @@ describe('openHostedBillingTab', () => { expect(mockStop.mock.calls.length).toBe(stopCallsAfterFirstOpen + 1) expect(mockRegisterRefreshOnReturn).toHaveBeenCalledTimes(2) }) + + describe('while a hosted payment tab is open', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.spyOn(window, 'open').mockReturnValue(fakeTab()) + mockReadOperation.mockReset().mockResolvedValue(false) + }) + + afterEach(() => { + disarmHostedBillingReturnRefresh() + }) + + it.for(['checkout', 'subscription'] as const)( + 're-reads the checkout status so the app picks up the payment %s starts', + async (intent) => { + openHostedBillingTab(intent) + + await vi.advanceTimersByTimeAsync(4_000) + expect(mockReadOperation).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(4_000) + expect(mockReadOperation).toHaveBeenCalledTimes(2) + } + ) + + it('hands off once a read finds the pending operation', async () => { + mockReadOperation.mockResolvedValueOnce(false).mockResolvedValueOnce(true) + openHostedBillingTab('checkout') + + await vi.advanceTimersByTimeAsync(60_000) + + expect(mockReadOperation).toHaveBeenCalledTimes(2) + }) + + it('stops watching once the workspace the tab was opened for is left', async () => { + openHostedBillingTab('checkout') + await vi.advanceTimersByTimeAsync(4_000) + expect(mockReadOperation).toHaveBeenCalledOnce() + + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-other' }) + await vi.advanceTimersByTimeAsync(60_000) + + expect(mockReadOperation).toHaveBeenCalledOnce() + }) + + it('does not watch for an intent that starts no payment', async () => { + openHostedBillingTab('payment-methods') + + await vi.advanceTimersByTimeAsync(60_000) + + expect(mockReadOperation).not.toHaveBeenCalled() + }) + + it('reads until fifteen minutes pass, then stops', async () => { + openHostedBillingTab('checkout') + + await vi.advanceTimersByTimeAsync(15 * 60_000 - 1) + const readsBeforeExpiry = mockReadOperation.mock.calls.length + expect(readsBeforeExpiry).toBeGreaterThan(200) + + await vi.advanceTimersByTimeAsync(60_000) + expect(mockReadOperation).toHaveBeenCalledTimes(readsBeforeExpiry) + }) + + it('stops watching when disarmed', async () => { + openHostedBillingTab('checkout') + disarmHostedBillingReturnRefresh() + + await vi.advanceTimersByTimeAsync(60_000) + + expect(mockReadOperation).not.toHaveBeenCalled() + }) + + it('skips a tick while the previous read is still in flight', async () => { + let settle: (found: boolean) => void = () => {} + mockReadOperation.mockImplementationOnce( + () => new Promise((resolve) => (settle = resolve)) + ) + openHostedBillingTab('checkout') + + await vi.advanceTimersByTimeAsync(8_000) + expect(mockReadOperation).toHaveBeenCalledOnce() + + settle(false) + await vi.advanceTimersByTimeAsync(4_000) + expect(mockReadOperation).toHaveBeenCalledTimes(2) + }) + + it('keeps watching after a read fails', async () => { + mockReadOperation.mockRejectedValueOnce(new Error('status read failed')) + openHostedBillingTab('checkout') + + await vi.advanceTimersByTimeAsync(8_000) + + expect(mockReadOperation).toHaveBeenCalledTimes(2) + }) + + it('stops watching when a tab that starts no payment opens next', async () => { + openHostedBillingTab('checkout') + openHostedBillingTab('payment-methods') + + await vi.advanceTimersByTimeAsync(60_000) + + expect(mockReadOperation).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/platform/workspace/billing/openHostedBillingTab.ts b/src/platform/workspace/billing/openHostedBillingTab.ts index 1f4e3fccfa1..6990c4c2605 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.ts @@ -35,18 +35,69 @@ function openDisownedTab(url: URL): boolean { } let stopReturnRefresh: (() => void) | null = null +let stopOperationWatch: (() => void) | null = null export function disarmHostedBillingReturnRefresh(): void { stopReturnRefresh?.() stopReturnRefresh = null + stopOperationWatch?.() + stopOperationWatch = null } -function armReturnRefresh(): void { +const OPERATION_INTENTS: ReadonlySet = new Set([ + 'checkout', + 'subscription' +]) +const OPERATION_POLL_MS = 4_000 +const OPERATION_WATCH_MS = 15 * 60_000 + +/** + * A payment billing-web takes never pushes back to this tab, but a status read + * resumes the operation the server reports pending, and that operation then + * polls itself and shows the same progress and outcome toasts the embedded + * checkout shows. This reads until one is found, for the workspace the tab + * was opened for only. A read still in flight skips the tick, and a failed + * read waits for the next one. + */ +function watchForHostedOperation( + readOperation: () => Promise, + workspaceId: string | undefined +) { + const workspaceStore = useTeamWorkspaceStore() + const startedAt = Date.now() + let reading = false + const timer = setInterval(() => { + if ( + Date.now() - startedAt >= OPERATION_WATCH_MS || + (workspaceStore.activeWorkspaceId ?? undefined) !== workspaceId + ) { + clearInterval(timer) + return + } + if (reading) return + reading = true + void readOperation() + .then((found) => { + if (found) clearInterval(timer) + }) + .catch(() => undefined) + .finally(() => { + reading = false + }) + }, OPERATION_POLL_MS) + return () => clearInterval(timer) +} + +function armReturnRefresh( + intent: BillingIntent, + workspaceId: string | undefined +): void { disarmHostedBillingReturnRefresh() // Resolved inside the call, not at module scope: useBillingContext -> // useWorkspaceBilling -> this module would otherwise dereference the // shared context before its state is constructed. - const { fetchStatus, fetchBalance } = useBillingContext() + const { fetchStatus, fetchBalance, readCheckoutOperation } = + useBillingContext() stopReturnRefresh = registerRefreshOnReturn(() => Promise.allSettled([ fetchStatus(), @@ -54,6 +105,12 @@ function armReturnRefresh(): void { useBillingCapabilities().refresh() ]) ) + if (OPERATION_INTENTS.has(intent)) { + stopOperationWatch = watchForHostedOperation( + readCheckoutOperation, + workspaceId + ) + } } export type HostedBillingTabOutcome = 'opened' | 'unavailable' | 'blocked' @@ -77,7 +134,7 @@ export function openHostedBillingTabOutcome( }) if (route.kind !== 'billing_web') return 'unavailable' if (!openDisownedTab(route.url)) return 'blocked' - armReturnRefresh() + armReturnRefresh(intent, workspaceId) return 'opened' } diff --git a/src/platform/workspace/billing/refreshOnReturn.test.ts b/src/platform/workspace/billing/refreshOnReturn.test.ts index 34a3703e374..b6a4fc997b3 100644 --- a/src/platform/workspace/billing/refreshOnReturn.test.ts +++ b/src/platform/workspace/billing/refreshOnReturn.test.ts @@ -1,11 +1,11 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, onTestFinished, vi } from 'vitest' import { registerRefreshOnReturn } from './refreshOnReturn' describe('registerRefreshOnReturn', () => { it('fires on window focus', () => { const refresh = vi.fn(async () => {}) - registerRefreshOnReturn(refresh) + onTestFinished(registerRefreshOnReturn(refresh)) window.dispatchEvent(new Event('focus')) @@ -14,7 +14,7 @@ describe('registerRefreshOnReturn', () => { it('fires on a visible visibilitychange', () => { const refresh = vi.fn(async () => {}) - registerRefreshOnReturn(refresh) + onTestFinished(registerRefreshOnReturn(refresh)) document.dispatchEvent(new Event('visibilitychange')) @@ -25,7 +25,7 @@ describe('registerRefreshOnReturn', () => { const refresh = vi.fn(async () => {}) const visibilitySpy = vi.spyOn(document, 'visibilityState', 'get') visibilitySpy.mockReturnValue('hidden') - registerRefreshOnReturn(refresh) + onTestFinished(registerRefreshOnReturn(refresh)) document.dispatchEvent(new Event('visibilitychange')) expect(refresh).not.toHaveBeenCalled() @@ -56,7 +56,7 @@ describe('registerRefreshOnReturn', () => { it('refreshes again on a later return, so a return before the hosted tab finishes does not spend it', async () => { const { refresh, settle } = held() - registerRefreshOnReturn(refresh) + onTestFinished(registerRefreshOnReturn(refresh)) come() await settle(0) @@ -68,7 +68,7 @@ describe('registerRefreshOnReturn', () => { it('coalesces the focus and visibilitychange of one return into one refresh', async () => { const { refresh, settle } = held() - registerRefreshOnReturn(refresh) + onTestFinished(registerRefreshOnReturn(refresh)) come() document.dispatchEvent(new Event('visibilitychange')) @@ -80,7 +80,7 @@ describe('registerRefreshOnReturn', () => { it('runs one trailing refresh for a return that arrives while a refresh is in flight', async () => { const { refresh, settle } = held() - registerRefreshOnReturn(refresh) + onTestFinished(registerRefreshOnReturn(refresh)) come() leave() diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 50b94f1f92a..4fd8fbd6a20 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -897,6 +897,31 @@ describe('useBillingSdkStore operation projections', () => { Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-1' }) }) + it.for([ + { + name: 'an adopted operation', + result: { status: 'ok', value: pendingSubscription() }, + adopted: true + }, + { + name: 'nothing pending', + result: { status: 'ok', value: undefined }, + adopted: false + }, + { + name: 'a failed recovery read', + result: { status: 'error', code: 'REQUEST_FAILED' }, + adopted: false + } + ] as const)( + 'recover reports $name as adopted: $adopted', + async ({ result, adopted }) => { + vi.mocked(harness.sdk.lifecycle.recover).mockResolvedValue(result) + + await expect(useBillingSdkStore().recover()).resolves.toBe(adopted) + } + ) + describe('recoverPendingOperation', () => { it('resolves with the operation once the lifecycle settles it', async () => { const store = useBillingSdkStore() diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index ca816f53d29..bded989c868 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -487,8 +487,10 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { return outcome } - function recover() { - void sdk.lifecycle.recover() + /** Adopts the operation the server reports pending; true once one is adopted. */ + async function recover(): Promise { + const adopted = await sdk.lifecycle.recover() + return adopted.status === 'ok' && adopted.value !== undefined } /** diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index aca1395f6fa..575bebe8e53 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -3,6 +3,8 @@ import { useBillingCapabilities } from '@/platform/workspace/composables/useBill import { billingOperation } from './billingOperationTestUtils' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' +import { useBillingSdkStore } from '@/platform/workspace/billing/sdk/billingSdkStore' +import { useFeatureFlags } from '@/composables/useFeatureFlags' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope } from 'vue' @@ -110,6 +112,9 @@ vi.mock( vi.mock(import('@/platform/telemetry')) +vi.mock(import('firebase/auth')) +vi.mock(import('@/composables/useFeatureFlags'), { spy: true }) + // 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' @@ -340,6 +345,64 @@ describe('useWorkspaceBilling', () => { ) }) + describe('reading for a payment taken in a hosted tab', () => { + const pendingStatus = { + ...activeStatus, + billing_status: 'pending_payment', + pending_billing_op_id: 'op-hosted', + pending_billing_op_type: 'subscription' + } satisfies BillingStatusResponse + + it('reports nothing adopted while no operation is pending', async () => { + mockWorkspaceApi.getBillingStatus.mockResolvedValue(activeStatus) + + await expect( + setupBilling().readAndAdoptPendingOperation() + ).resolves.toBe(false) + }) + + it('reports the operation adopted once the operation store holds it', async () => { + mockWorkspaceApi.getBillingStatus.mockResolvedValue(pendingStatus) + + await expect( + setupBilling().readAndAdoptPendingOperation() + ).resolves.toBe(true) + expect(useBillingOperationStore().startOperation).toHaveBeenCalledWith( + 'op-hosted', + 'subscription', + undefined, + undefined + ) + }) + + it('reports a failed SDK adoption as not adopted, so the next read retries', async () => { + const real = useFeatureFlags() + vi.mocked(useFeatureFlags).mockReturnValue({ + ...real, + flags: new Proxy(real.flags, { + get: (target, key) => + key === 'billingSdkSubscriptionRailEnabled' || + Reflect.get(target, key) + }) + }) + const sdk = useBillingSdkStore() + vi.mocked(sdk.readStatus).mockResolvedValue({ + status: 'ok', + value: pendingStatus + }) + vi.mocked(sdk.recover) + .mockResolvedValueOnce(false) + .mockResolvedValueOnce(true) + const billing = setupBilling() + + await expect(billing.readAndAdoptPendingOperation()).resolves.toBe( + false + ) + await expect(billing.readAndAdoptPendingOperation()).resolves.toBe(true) + expect(useBillingOperationStore().startOperation).not.toHaveBeenCalled() + }) + }) + it('recovers a pending subscription operation from billing status', async () => { const actionUrl = 'https://invoice.stripe.com/sensitive-token' mockWorkspaceApi.getBillingStatus.mockResolvedValue({ diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 0b2d26f0606..0d5fd2192b9 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -169,7 +169,16 @@ function seatCapacityFrom(status: BillingStatusResponse): SeatCapacity | null { * Used for team workspaces. * @internal - Use useBillingContext() instead of importing directly. */ -export function useWorkspaceBilling(): BillingState & BillingActions { +export type WorkspaceBilling = BillingState & + BillingActions & { + /** + * Reads status and resolves true once the operation it reports pending + * has been adopted, so its own polling shows progress and outcome. + */ + readAndAdoptPendingOperation: () => Promise + } + +export function useWorkspaceBilling(): WorkspaceBilling { const billingPlans = useBillingPlans() const billingOperationStore = useBillingOperationStore() const workspaceStore = useTeamWorkspaceStore() @@ -181,6 +190,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { const error = ref(null) const statusData = shallowRef(null) + let adoption: Promise = Promise.resolve(false) const seatCapacity = shallowRef(null) const balanceData = shallowRef(null) // Prevent older status and balance responses from overwriting newer state. @@ -290,16 +300,17 @@ export function useWorkspaceBilling(): BillingState & BillingActions { : flags.billingSdkSubscriptionRailEnabled } - function resumePendingOperation(status: BillingStatusResponse): void { - if ( - !status.pending_billing_op_id || - billingOperationStore.getOperation(status.pending_billing_op_id) - ) { - return + async function resumePendingOperation( + status: BillingStatusResponse + ): Promise { + if (!status.pending_billing_op_id) return false + if (billingOperationStore.getOperation(status.pending_billing_op_id)) { + return true } if (railOwnsResume(status.pending_billing_op_type)) { - useBillingSdkStore().recover() - return + return useBillingSdkStore() + .recover() + .catch(() => false) } void billingOperationStore.startOperation( status.pending_billing_op_id, @@ -307,6 +318,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { undefined, status.action_url ) + return true } function isStaleStatusRead( @@ -319,7 +331,13 @@ export function useWorkspaceBilling(): BillingState & BillingActions { ) } + async function readAndAdoptPendingOperation(): Promise { + await fetchStatus() + return adoption + } + async function fetchStatus(): Promise { + adoption = Promise.resolve(false) const requestId = ++latestBillingReadIds.status const workspaceId = workspaceStore.activeWorkspace?.id const rail: BillingReadRail | null = useBillingReadRail() @@ -337,7 +355,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { if (workspaceId && status.billing_rail) { workspaceStore.setWorkspaceBillingRail(workspaceId, status.billing_rail) } - resumePendingOperation(status) + adoption = resumePendingOperation(status) } catch (err) { if (requestId === latestBillingReadIds.status) { error.value = @@ -764,6 +782,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { subscriptionStatus, tier, renewalDate, + readAndAdoptPendingOperation, // Actions initialize, diff --git a/src/storybook/mocks/useBillingContext.ts b/src/storybook/mocks/useBillingContext.ts index 755a7a96bac..356971c00a3 100644 --- a/src/storybook/mocks/useBillingContext.ts +++ b/src/storybook/mocks/useBillingContext.ts @@ -80,6 +80,7 @@ export function useBillingContext(): BillingContext { fetchStatus: async () => {}, fetchBalance: async () => {}, reconcileSubscriptionSuccess: async () => {}, + readCheckoutOperation: async () => false, subscribe: async () => {}, previewSubscribe: async () => null, manageSubscription: async () => {},