From 611081cbbfb9e890e6356f22cf04b4f09483e6f8 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 27 Sep 2026 17:18:57 -0400 Subject: [PATCH 01/10] test(billing): a return before the hosted tab finishes must not spend the refresh --- .../workspace/billing/refreshOnReturn.test.ts | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/platform/workspace/billing/refreshOnReturn.test.ts b/src/platform/workspace/billing/refreshOnReturn.test.ts index dd7bda4e214..adbfd4f0e16 100644 --- a/src/platform/workspace/billing/refreshOnReturn.test.ts +++ b/src/platform/workspace/billing/refreshOnReturn.test.ts @@ -35,14 +35,38 @@ describe('registerRefreshOnReturn', () => { expect(refresh).toHaveBeenCalledTimes(1) }) - it('is one-shot: a second return does not refetch', () => { + it('refreshes again on a later return, so a return before the hosted tab finishes does not spend it', async () => { const refresh = vi.fn(async () => {}) registerRefreshOnReturn(refresh) window.dispatchEvent(new Event('focus')) + await refresh.mock.results[0]?.value + await Promise.resolve() window.dispatchEvent(new Event('focus')) + expect(refresh).toHaveBeenCalledTimes(2) + }) + + it('coalesces the focus and visibilitychange of one return into one refresh', async () => { + let settle!: () => void + const refresh = vi.fn( + () => + new Promise((resolve) => { + settle = resolve + }) + ) + registerRefreshOnReturn(refresh) + + window.dispatchEvent(new Event('focus')) + document.dispatchEvent(new Event('visibilitychange')) expect(refresh).toHaveBeenCalledTimes(1) + + settle() + await refresh.mock.results[0]?.value + await Promise.resolve() + window.dispatchEvent(new Event('focus')) + + expect(refresh).toHaveBeenCalledTimes(2) }) it('stops listening once the returned callback runs', () => { From 32639eccec8cf177e34b9e1f0fb75b3396e0efbb Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 27 Sep 2026 17:28:15 -0400 Subject: [PATCH 02/10] fix(billing): refresh the app on every return from a hosted billing tab --- .../workspace/billing/openHostedBillingTab.ts | 7 +++++- .../workspace/billing/refreshOnReturn.ts | 23 +++++++++++-------- .../composables/useWorkspaceBilling.test.ts | 6 ++--- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/platform/workspace/billing/openHostedBillingTab.ts b/src/platform/workspace/billing/openHostedBillingTab.ts index 82a24e30672..1f4e3fccfa1 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.ts @@ -36,8 +36,13 @@ function openDisownedTab(url: URL): boolean { let stopReturnRefresh: (() => void) | null = null -function armReturnRefresh(): void { +export function disarmHostedBillingReturnRefresh(): void { stopReturnRefresh?.() + stopReturnRefresh = null +} + +function armReturnRefresh(): 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. diff --git a/src/platform/workspace/billing/refreshOnReturn.ts b/src/platform/workspace/billing/refreshOnReturn.ts index 1197410cb92..1f7ed770395 100644 --- a/src/platform/workspace/billing/refreshOnReturn.ts +++ b/src/platform/workspace/billing/refreshOnReturn.ts @@ -1,16 +1,15 @@ /** * A cancellation, card change, or payment made in a hosted tab never pushes - * back to this one, so the next `focus`/`visibilitychange` re-reads whatever - * that tab could have changed. Shared by every opener of a hosted billing + * back to this one, so every `focus`/`visibilitychange` re-reads whatever + * that tab could have changed. It stays armed until the returned callback + * runs: a return before the hosted tab finishes must not spend the refresh + * the customer needs after it. Shared by every opener of a hosted billing * tab or window so they arm the same return signal one way. */ export function registerRefreshOnReturn( refresh: () => Promise ): () => void { - const stopListening = () => { - document.removeEventListener('visibilitychange', onReturn) - window.removeEventListener('focus', onReturn) - } + let inFlight = false const onReturn = (event: Event) => { if ( event.type === 'visibilitychange' && @@ -18,10 +17,16 @@ export function registerRefreshOnReturn( ) { return } - stopListening() - void refresh() + if (inFlight) return + inFlight = true + void refresh().finally(() => { + inFlight = false + }) } document.addEventListener('visibilitychange', onReturn) window.addEventListener('focus', onReturn) - return stopListening + return () => { + document.removeEventListener('visibilitychange', onReturn) + window.removeEventListener('focus', onReturn) + } } diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index bd23b7c4fe6..9a8a6a0ed44 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -1,3 +1,4 @@ +import { disarmHostedBillingReturnRefresh } from '@/platform/workspace/billing/openHostedBillingTab' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { billingOperation } from './billingOperationTestUtils' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -871,10 +872,7 @@ describe('useWorkspaceBilling', () => { }) afterEach(() => { - // Flushes any return-refresh listener a test armed but never fired - // (openHostedBillingTab's own, independent of this instance's - // stopPortalReturnRefresh), so it cannot fire twice for a later test. - window.dispatchEvent(new Event('focus')) + disarmHostedBillingReturnRefresh() mockRail.enabled = false localStorage.clear() Object.defineProperty(window, 'location', { From 8aaca52e652b1936188b1ae72f30b5ca0f89aa5d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 27 Sep 2026 19:01:54 -0400 Subject: [PATCH 03/10] test(billing): the app watches the billing status while a hosted payment tab is open --- .../billing/openHostedBillingTab.test.ts | 60 ++++++++++++++++++- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/src/platform/workspace/billing/openHostedBillingTab.test.ts b/src/platform/workspace/billing/openHostedBillingTab.test.ts index 27521b89b06..00f6d3db9c7 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( @@ -43,7 +43,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 +168,57 @@ 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()) + }) + + afterEach(() => { + disarmHostedBillingReturnRefresh() + }) + + it.for(['checkout', 'subscription'] as const)( + 're-reads the billing status so the app picks up the payment %s starts', + (intent) => { + openHostedBillingTab(intent) + mockFetchStatus.mockClear() + + vi.advanceTimersByTime(4_000) + expect(mockFetchStatus).toHaveBeenCalledTimes(1) + vi.advanceTimersByTime(4_000) + expect(mockFetchStatus).toHaveBeenCalledTimes(2) + } + ) + + it('does not watch for an intent that starts no payment', () => { + openHostedBillingTab('payment-methods') + mockFetchStatus.mockClear() + + vi.advanceTimersByTime(60_000) + + expect(mockFetchStatus).not.toHaveBeenCalled() + }) + + it('stops watching after fifteen minutes', () => { + openHostedBillingTab('checkout') + vi.advanceTimersByTime(15 * 60_000) + mockFetchStatus.mockClear() + + vi.advanceTimersByTime(60_000) + + expect(mockFetchStatus).not.toHaveBeenCalled() + }) + + it('stops watching when disarmed', () => { + openHostedBillingTab('checkout') + disarmHostedBillingReturnRefresh() + mockFetchStatus.mockClear() + + vi.advanceTimersByTime(60_000) + + expect(mockFetchStatus).not.toHaveBeenCalled() + }) + }) }) From fca393749805473440466b6439789df20b41f0d5 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 27 Sep 2026 19:10:19 -0400 Subject: [PATCH 04/10] feat(billing): show the payment progress in the app while billing-web takes the payment --- .../workspace/billing/openHostedBillingTab.ts | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/platform/workspace/billing/openHostedBillingTab.ts b/src/platform/workspace/billing/openHostedBillingTab.ts index 1f4e3fccfa1..7ea38f4cf87 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.ts @@ -35,13 +35,41 @@ 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 each status + * read resumes the operation the server reports pending, which shows the same + * progress and outcome toasts the embedded checkout shows. Reading it while + * the hosted tab is open is what lets this tab show them too. + */ +function watchForHostedOperation(fetchStatus: () => Promise) { + const startedAt = Date.now() + const timer = setInterval(() => { + if (Date.now() - startedAt >= OPERATION_WATCH_MS) { + clearInterval(timer) + return + } + void fetchStatus() + }, OPERATION_POLL_MS) + return () => clearInterval(timer) +} + +function armReturnRefresh(intent: BillingIntent): void { disarmHostedBillingReturnRefresh() // Resolved inside the call, not at module scope: useBillingContext -> // useWorkspaceBilling -> this module would otherwise dereference the @@ -54,6 +82,9 @@ function armReturnRefresh(): void { useBillingCapabilities().refresh() ]) ) + if (OPERATION_INTENTS.has(intent)) { + stopOperationWatch = watchForHostedOperation(fetchStatus) + } } export type HostedBillingTabOutcome = 'opened' | 'unavailable' | 'blocked' @@ -77,7 +108,7 @@ export function openHostedBillingTabOutcome( }) if (route.kind !== 'billing_web') return 'unavailable' if (!openDisownedTab(route.url)) return 'blocked' - armReturnRefresh() + armReturnRefresh(intent) return 'opened' } From f2f905e7289d1ecfddbfe57e181474281980724f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 27 Sep 2026 23:21:38 -0400 Subject: [PATCH 05/10] test(billing): a return during an in-flight refresh gets one trailing refresh --- .../workspace/billing/refreshOnReturn.test.ts | 57 +++++++++++++------ 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/src/platform/workspace/billing/refreshOnReturn.test.ts b/src/platform/workspace/billing/refreshOnReturn.test.ts index adbfd4f0e16..34a3703e374 100644 --- a/src/platform/workspace/billing/refreshOnReturn.test.ts +++ b/src/platform/workspace/billing/refreshOnReturn.test.ts @@ -35,36 +35,59 @@ describe('registerRefreshOnReturn', () => { expect(refresh).toHaveBeenCalledTimes(1) }) + function held() { + const settles: Array<() => void> = [] + const refresh = vi.fn( + () => + new Promise((resolve) => { + settles.push(resolve) + }) + ) + const settle = async (index: number) => { + settles[index]() + await refresh.mock.results[index]?.value + await Promise.resolve() + } + return { refresh, settle } + } + + const leave = () => window.dispatchEvent(new Event('blur')) + const come = () => window.dispatchEvent(new Event('focus')) + it('refreshes again on a later return, so a return before the hosted tab finishes does not spend it', async () => { - const refresh = vi.fn(async () => {}) + const { refresh, settle } = held() registerRefreshOnReturn(refresh) - window.dispatchEvent(new Event('focus')) - await refresh.mock.results[0]?.value - await Promise.resolve() - window.dispatchEvent(new Event('focus')) + come() + await settle(0) + leave() + come() expect(refresh).toHaveBeenCalledTimes(2) }) it('coalesces the focus and visibilitychange of one return into one refresh', async () => { - let settle!: () => void - const refresh = vi.fn( - () => - new Promise((resolve) => { - settle = resolve - }) - ) + const { refresh, settle } = held() registerRefreshOnReturn(refresh) - window.dispatchEvent(new Event('focus')) + come() document.dispatchEvent(new Event('visibilitychange')) expect(refresh).toHaveBeenCalledTimes(1) + await settle(0) - settle() - await refresh.mock.results[0]?.value - await Promise.resolve() - window.dispatchEvent(new Event('focus')) + expect(refresh).toHaveBeenCalledTimes(1) + }) + + it('runs one trailing refresh for a return that arrives while a refresh is in flight', async () => { + const { refresh, settle } = held() + registerRefreshOnReturn(refresh) + + come() + leave() + come() + expect(refresh).toHaveBeenCalledTimes(1) + + await settle(0) expect(refresh).toHaveBeenCalledTimes(2) }) From 58861dc7dfa033ccfc8df4f90c1c200096ff5e9a Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Sun, 27 Sep 2026 23:31:04 -0400 Subject: [PATCH 06/10] fix(billing): give a return during an in-flight refresh one trailing refresh --- .../workspace/billing/refreshOnReturn.ts | 51 +++++++++++++------ 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/src/platform/workspace/billing/refreshOnReturn.ts b/src/platform/workspace/billing/refreshOnReturn.ts index 1f7ed770395..e72b4d44f98 100644 --- a/src/platform/workspace/billing/refreshOnReturn.ts +++ b/src/platform/workspace/billing/refreshOnReturn.ts @@ -1,32 +1,53 @@ /** * A cancellation, card change, or payment made in a hosted tab never pushes - * back to this one, so every `focus`/`visibilitychange` re-reads whatever - * that tab could have changed. It stays armed until the returned callback - * runs: a return before the hosted tab finishes must not spend the refresh - * the customer needs after it. Shared by every opener of a hosted billing - * tab or window so they arm the same return signal one way. + * back to this one, so every return to this tab re-reads whatever that tab + * could have changed. A return is leaving (`blur` or hidden) and coming back + * (`focus` or visible): the focus and visibility events of one return count + * once, and a return that lands while a refresh is still in flight gets one + * trailing refresh, because that read may predate what the hosted tab just + * did. It stays armed until the returned callback runs. Shared by every + * opener of a hosted billing tab or window so they arm the same return + * signal one way. */ export function registerRefreshOnReturn( refresh: () => Promise ): () => void { + let away = true let inFlight = false - const onReturn = (event: Event) => { - if ( - event.type === 'visibilitychange' && - document.visibilityState !== 'visible' - ) { - return - } - if (inFlight) return + let trailing = false + + const run = () => { inFlight = true void refresh().finally(() => { inFlight = false + if (!trailing) return + trailing = false + run() }) } - document.addEventListener('visibilitychange', onReturn) + const onLeave = () => { + away = true + } + const onReturn = () => { + if (!away) return + away = false + if (inFlight) { + trailing = true + return + } + run() + } + const onVisibilityChange = () => { + if (document.visibilityState === 'visible') onReturn() + else onLeave() + } + + document.addEventListener('visibilitychange', onVisibilityChange) window.addEventListener('focus', onReturn) + window.addEventListener('blur', onLeave) return () => { - document.removeEventListener('visibilitychange', onReturn) + document.removeEventListener('visibilitychange', onVisibilityChange) window.removeEventListener('focus', onReturn) + window.removeEventListener('blur', onLeave) } } From afaff602cfd8842b3a8a4c666c2389b84df1c51f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 28 Sep 2026 02:53:55 -0400 Subject: [PATCH 07/10] fix(billing): poll the checkout rail for a hosted payment, one read at a time --- .../billing/openHostedBillingTab.test.ts | 64 +++++++++++++++---- .../workspace/billing/openHostedBillingTab.ts | 19 ++++-- .../workspace/billing/refreshOnReturn.test.ts | 14 ++-- 3 files changed, 71 insertions(+), 26 deletions(-) diff --git a/src/platform/workspace/billing/openHostedBillingTab.test.ts b/src/platform/workspace/billing/openHostedBillingTab.test.ts index 00f6d3db9c7..290d11d19e3 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.test.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.test.ts @@ -17,10 +17,12 @@ vi.mock(import('@/composables/useFeatureFlags'), () => ({ const mockFetchStatus = vi.hoisted(() => vi.fn(async () => {})) const mockFetchBalance = vi.hoisted(() => vi.fn(async () => {})) +const mockReconcile = vi.hoisted(() => vi.fn(async () => {})) vi.mock(import('@/composables/billing/useBillingContext'), () => ({ useBillingContext: () => ({ fetchStatus: mockFetchStatus, - fetchBalance: mockFetchBalance + fetchBalance: mockFetchBalance, + reconcileSubscriptionSuccess: mockReconcile }) })) @@ -180,45 +182,79 @@ describe('openHostedBillingTab', () => { }) it.for(['checkout', 'subscription'] as const)( - 're-reads the billing status so the app picks up the payment %s starts', - (intent) => { + 're-reads the checkout status so the app picks up the payment %s starts', + async (intent) => { openHostedBillingTab(intent) - mockFetchStatus.mockClear() + mockReconcile.mockClear() - vi.advanceTimersByTime(4_000) - expect(mockFetchStatus).toHaveBeenCalledTimes(1) - vi.advanceTimersByTime(4_000) - expect(mockFetchStatus).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(4_000) + expect(mockReconcile).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(4_000) + expect(mockReconcile).toHaveBeenCalledTimes(2) } ) it('does not watch for an intent that starts no payment', () => { openHostedBillingTab('payment-methods') - mockFetchStatus.mockClear() + mockReconcile.mockClear() vi.advanceTimersByTime(60_000) - expect(mockFetchStatus).not.toHaveBeenCalled() + expect(mockReconcile).not.toHaveBeenCalled() }) it('stops watching after fifteen minutes', () => { openHostedBillingTab('checkout') vi.advanceTimersByTime(15 * 60_000) - mockFetchStatus.mockClear() + mockReconcile.mockClear() vi.advanceTimersByTime(60_000) - expect(mockFetchStatus).not.toHaveBeenCalled() + expect(mockReconcile).not.toHaveBeenCalled() }) it('stops watching when disarmed', () => { openHostedBillingTab('checkout') disarmHostedBillingReturnRefresh() - mockFetchStatus.mockClear() + mockReconcile.mockClear() vi.advanceTimersByTime(60_000) - expect(mockFetchStatus).not.toHaveBeenCalled() + expect(mockReconcile).not.toHaveBeenCalled() + }) + + it('skips a tick while the previous read is still in flight', async () => { + let settle: () => void = () => {} + mockReconcile.mockImplementationOnce( + () => new Promise((resolve) => (settle = resolve)) + ) + openHostedBillingTab('checkout') + + vi.advanceTimersByTime(8_000) + expect(mockReconcile).toHaveBeenCalledOnce() + + settle() + await vi.advanceTimersByTimeAsync(4_000) + expect(mockReconcile).toHaveBeenCalledTimes(2) + }) + + it('keeps watching after a read fails', async () => { + mockReconcile.mockRejectedValueOnce(new Error('status read failed')) + openHostedBillingTab('checkout') + + await vi.advanceTimersByTimeAsync(8_000) + + expect(mockReconcile).toHaveBeenCalledTimes(2) + }) + + it('stops watching when a tab that starts no payment opens next', () => { + openHostedBillingTab('checkout') + openHostedBillingTab('payment-methods') + mockReconcile.mockClear() + + vi.advanceTimersByTime(60_000) + + expect(mockReconcile).not.toHaveBeenCalled() }) }) }) diff --git a/src/platform/workspace/billing/openHostedBillingTab.ts b/src/platform/workspace/billing/openHostedBillingTab.ts index 7ea38f4cf87..73f032dba87 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.ts @@ -55,16 +55,24 @@ const OPERATION_WATCH_MS = 15 * 60_000 * A payment billing-web takes never pushes back to this tab, but each status * read resumes the operation the server reports pending, which shows the same * progress and outcome toasts the embedded checkout shows. Reading it while - * the hosted tab is open is what lets this tab show them too. + * the hosted tab is open is what lets this tab show them too. A read still in + * flight skips the tick, and a failed read waits for the next one. */ -function watchForHostedOperation(fetchStatus: () => Promise) { +function watchForHostedOperation(readStatus: () => Promise) { const startedAt = Date.now() + let reading = false const timer = setInterval(() => { if (Date.now() - startedAt >= OPERATION_WATCH_MS) { clearInterval(timer) return } - void fetchStatus() + if (reading) return + reading = true + void readStatus() + .catch(() => undefined) + .finally(() => { + reading = false + }) }, OPERATION_POLL_MS) return () => clearInterval(timer) } @@ -74,7 +82,8 @@ function armReturnRefresh(intent: BillingIntent): void { // 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, reconcileSubscriptionSuccess } = + useBillingContext() stopReturnRefresh = registerRefreshOnReturn(() => Promise.allSettled([ fetchStatus(), @@ -83,7 +92,7 @@ function armReturnRefresh(intent: BillingIntent): void { ]) ) if (OPERATION_INTENTS.has(intent)) { - stopOperationWatch = watchForHostedOperation(fetchStatus) + stopOperationWatch = watchForHostedOperation(reconcileSubscriptionSuccess) } } 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() From ae1618d4a9bfd6a59766fe10689a80c71b75e488 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 28 Sep 2026 04:23:28 -0400 Subject: [PATCH 08/10] fix(billing): watch only the opened workspace and stop once the operation is adopted --- .../billing/__mocks__/useBillingContext.ts | 3 +- src/composables/billing/types.ts | 2 + .../billing/useBillingContext.test.ts | 23 ++++++ src/composables/billing/useBillingContext.ts | 18 ++++- .../billing/openHostedBillingTab.test.ts | 80 ++++++++++++------- .../workspace/billing/openHostedBillingTab.ts | 41 +++++++--- .../composables/useWorkspaceBilling.ts | 13 ++- src/storybook/mocks/useBillingContext.ts | 1 + 8 files changed, 133 insertions(+), 48 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 45ff70ad910..fd0d028a5cc 100644 --- a/src/composables/billing/types.ts +++ b/src/composables/billing/types.ts @@ -129,6 +129,8 @@ export interface BillingState { export interface BillingContext extends BillingState, BillingActions { type: ComputedRef reconcileSubscriptionSuccess: () => Promise + /** Reads the checkout rail's status; true once it reports a pending operation. */ + 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 1ff24c5ddbd..19fff680d67 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -505,6 +505,29 @@ describe('useBillingContext', () => { expect(useAuthStore().fetchBalance).not.toHaveBeenCalled() }) + it.for([ + { pending: 'op-1', found: true }, + { pending: undefined, found: false } + ])( + 'reads the checkout rail for a hosted payment (pending: $pending)', + async ({ pending, found }) => { + mockBillingStatus.value = { + ...DEFAULT_BILLING_STATUS, + pending_billing_op_id: pending + } + const context = useBillingContext() + await vi.waitFor(() => + expect(workspaceApi.getBillingStatus).toHaveBeenCalled() + ) + vi.clearAllMocks() + + 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 69b9bdcbbb3..5009590b0cc 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 @@ -90,9 +91,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) { @@ -295,6 +294,18 @@ function useBillingContextInternal(): BillingContext { await account.fetchBalance() } + /** + * Reads the checkout rail's status, which resumes any operation the server + * reports pending. True once one was reported, so a caller watching for a + * payment taken elsewhere can hand off to the operation's own polling. + */ + async function readCheckoutOperation(): Promise { + const checkout = checkoutContext.value + await checkout.fetchStatus() + const workspace = workspaceBillingRef.value + return checkout === workspace && workspace.hasPendingOperation.value + } + async function subscribe(planSlug: string, options?: SubscribeOptions) { return checkoutContext.value.subscribe(planSlug, options) } @@ -374,6 +385,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 290d11d19e3..9cf967b7593 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.test.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.test.ts @@ -17,12 +17,12 @@ vi.mock(import('@/composables/useFeatureFlags'), () => ({ const mockFetchStatus = vi.hoisted(() => vi.fn(async () => {})) const mockFetchBalance = vi.hoisted(() => vi.fn(async () => {})) -const mockReconcile = vi.hoisted(() => vi.fn(async () => {})) +const mockReadOperation = vi.hoisted(() => vi.fn(async () => false)) vi.mock(import('@/composables/billing/useBillingContext'), () => ({ useBillingContext: () => ({ fetchStatus: mockFetchStatus, fetchBalance: mockFetchBalance, - reconcileSubscriptionSuccess: mockReconcile + readCheckoutOperation: mockReadOperation }) })) @@ -175,6 +175,7 @@ describe('openHostedBillingTab', () => { beforeEach(() => { vi.useFakeTimers() vi.spyOn(window, 'open').mockReturnValue(fakeTab()) + mockReadOperation.mockReset().mockResolvedValue(false) }) afterEach(() => { @@ -185,76 +186,93 @@ describe('openHostedBillingTab', () => { 're-reads the checkout status so the app picks up the payment %s starts', async (intent) => { openHostedBillingTab(intent) - mockReconcile.mockClear() await vi.advanceTimersByTimeAsync(4_000) - expect(mockReconcile).toHaveBeenCalledTimes(1) + expect(mockReadOperation).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(4_000) - expect(mockReconcile).toHaveBeenCalledTimes(2) + expect(mockReadOperation).toHaveBeenCalledTimes(2) } ) - it('does not watch for an intent that starts no payment', () => { + 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') - mockReconcile.mockClear() - vi.advanceTimersByTime(60_000) + await vi.advanceTimersByTimeAsync(60_000) - expect(mockReconcile).not.toHaveBeenCalled() + expect(mockReadOperation).not.toHaveBeenCalled() }) - it('stops watching after fifteen minutes', () => { + it('reads until fifteen minutes pass, then stops', async () => { openHostedBillingTab('checkout') - vi.advanceTimersByTime(15 * 60_000) - mockReconcile.mockClear() - vi.advanceTimersByTime(60_000) + await vi.advanceTimersByTimeAsync(15 * 60_000 - 1) + const readsBeforeExpiry = mockReadOperation.mock.calls.length + expect(readsBeforeExpiry).toBeGreaterThan(200) - expect(mockReconcile).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(60_000) + expect(mockReadOperation).toHaveBeenCalledTimes(readsBeforeExpiry) }) - it('stops watching when disarmed', () => { + it('stops watching when disarmed', async () => { openHostedBillingTab('checkout') disarmHostedBillingReturnRefresh() - mockReconcile.mockClear() - vi.advanceTimersByTime(60_000) + await vi.advanceTimersByTimeAsync(60_000) - expect(mockReconcile).not.toHaveBeenCalled() + expect(mockReadOperation).not.toHaveBeenCalled() }) it('skips a tick while the previous read is still in flight', async () => { - let settle: () => void = () => {} - mockReconcile.mockImplementationOnce( - () => new Promise((resolve) => (settle = resolve)) + let settle: (found: boolean) => void = () => {} + mockReadOperation.mockImplementationOnce( + () => new Promise((resolve) => (settle = resolve)) ) openHostedBillingTab('checkout') - vi.advanceTimersByTime(8_000) - expect(mockReconcile).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(8_000) + expect(mockReadOperation).toHaveBeenCalledOnce() - settle() + settle(false) await vi.advanceTimersByTimeAsync(4_000) - expect(mockReconcile).toHaveBeenCalledTimes(2) + expect(mockReadOperation).toHaveBeenCalledTimes(2) }) it('keeps watching after a read fails', async () => { - mockReconcile.mockRejectedValueOnce(new Error('status read failed')) + mockReadOperation.mockRejectedValueOnce(new Error('status read failed')) openHostedBillingTab('checkout') await vi.advanceTimersByTimeAsync(8_000) - expect(mockReconcile).toHaveBeenCalledTimes(2) + expect(mockReadOperation).toHaveBeenCalledTimes(2) }) - it('stops watching when a tab that starts no payment opens next', () => { + it('stops watching when a tab that starts no payment opens next', async () => { openHostedBillingTab('checkout') openHostedBillingTab('payment-methods') - mockReconcile.mockClear() - vi.advanceTimersByTime(60_000) + await vi.advanceTimersByTimeAsync(60_000) - expect(mockReconcile).not.toHaveBeenCalled() + expect(mockReadOperation).not.toHaveBeenCalled() }) }) }) diff --git a/src/platform/workspace/billing/openHostedBillingTab.ts b/src/platform/workspace/billing/openHostedBillingTab.ts index 73f032dba87..6990c4c2605 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.ts @@ -52,23 +52,34 @@ 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 each status - * read resumes the operation the server reports pending, which shows the same - * progress and outcome toasts the embedded checkout shows. Reading it while - * the hosted tab is open is what lets this tab show them too. A read still in - * flight skips the tick, and a failed read waits for the next one. + * 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(readStatus: () => Promise) { +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) { + if ( + Date.now() - startedAt >= OPERATION_WATCH_MS || + (workspaceStore.activeWorkspaceId ?? undefined) !== workspaceId + ) { clearInterval(timer) return } if (reading) return reading = true - void readStatus() + void readOperation() + .then((found) => { + if (found) clearInterval(timer) + }) .catch(() => undefined) .finally(() => { reading = false @@ -77,12 +88,15 @@ function watchForHostedOperation(readStatus: () => Promise) { return () => clearInterval(timer) } -function armReturnRefresh(intent: BillingIntent): void { +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, reconcileSubscriptionSuccess } = + const { fetchStatus, fetchBalance, readCheckoutOperation } = useBillingContext() stopReturnRefresh = registerRefreshOnReturn(() => Promise.allSettled([ @@ -92,7 +106,10 @@ function armReturnRefresh(intent: BillingIntent): void { ]) ) if (OPERATION_INTENTS.has(intent)) { - stopOperationWatch = watchForHostedOperation(reconcileSubscriptionSuccess) + stopOperationWatch = watchForHostedOperation( + readCheckoutOperation, + workspaceId + ) } } @@ -117,7 +134,7 @@ export function openHostedBillingTabOutcome( }) if (route.kind !== 'billing_web') return 'unavailable' if (!openDisownedTab(route.url)) return 'blocked' - armReturnRefresh(intent) + armReturnRefresh(intent, workspaceId) return 'opened' } diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 0b2d26f0606..9030786b33e 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -6,6 +6,7 @@ import { shallowRef, watch } from 'vue' +import type { ComputedRef } from 'vue' import type { PreviewSubscribeInput } from '@comfyorg/account-core/billing' @@ -169,7 +170,13 @@ 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 & { + /** Whether the last status read reported an operation still pending. */ + hasPendingOperation: ComputedRef + } + +export function useWorkspaceBilling(): WorkspaceBilling { const billingPlans = useBillingPlans() const billingOperationStore = useBillingOperationStore() const workspaceStore = useTeamWorkspaceStore() @@ -181,6 +188,9 @@ export function useWorkspaceBilling(): BillingState & BillingActions { const error = ref(null) const statusData = shallowRef(null) + const hasPendingOperation = computed( + () => !!statusData.value?.pending_billing_op_id + ) const seatCapacity = shallowRef(null) const balanceData = shallowRef(null) // Prevent older status and balance responses from overwriting newer state. @@ -764,6 +774,7 @@ export function useWorkspaceBilling(): BillingState & BillingActions { subscriptionStatus, tier, renewalDate, + hasPendingOperation, // 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 () => {}, From 19bfabd4c15f686c5f5aafceb7d19d6166bbe18f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 28 Sep 2026 04:50:21 -0400 Subject: [PATCH 09/10] test(billing): find a pending operation the server reports after the first read --- src/composables/billing/useBillingContext.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/composables/billing/useBillingContext.test.ts b/src/composables/billing/useBillingContext.test.ts index 19fff680d67..8adce3d564d 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -509,17 +509,17 @@ describe('useBillingContext', () => { { pending: 'op-1', found: true }, { pending: undefined, found: false } ])( - 'reads the checkout rail for a hosted payment (pending: $pending)', + 'finds an operation the server reports after the first read (pending: $pending)', async ({ pending, found }) => { - mockBillingStatus.value = { - ...DEFAULT_BILLING_STATUS, - pending_billing_op_id: pending - } 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) From 2256f6010323a4af40ff4a0ebcf841b0c34fdbd7 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 28 Sep 2026 05:54:45 -0400 Subject: [PATCH 10/10] fix(billing): stop watching a hosted payment only once its operation is adopted --- src/composables/billing/types.ts | 2 +- src/composables/billing/useBillingContext.ts | 11 ++-- .../billing/sdk/billingSdkStore.test.ts | 25 ++++++++ .../workspace/billing/sdk/billingSdkStore.ts | 6 +- .../composables/useWorkspaceBilling.test.ts | 63 +++++++++++++++++++ .../composables/useWorkspaceBilling.ts | 40 +++++++----- 6 files changed, 124 insertions(+), 23 deletions(-) diff --git a/src/composables/billing/types.ts b/src/composables/billing/types.ts index fd0d028a5cc..1dfe396da8c 100644 --- a/src/composables/billing/types.ts +++ b/src/composables/billing/types.ts @@ -129,7 +129,7 @@ export interface BillingState { export interface BillingContext extends BillingState, BillingActions { type: ComputedRef reconcileSubscriptionSuccess: () => Promise - /** Reads the checkout rail's status; true once it reports a pending operation. */ + /** 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 diff --git a/src/composables/billing/useBillingContext.ts b/src/composables/billing/useBillingContext.ts index 5009590b0cc..7f5172fa8f1 100644 --- a/src/composables/billing/useBillingContext.ts +++ b/src/composables/billing/useBillingContext.ts @@ -296,14 +296,17 @@ function useBillingContextInternal(): BillingContext { /** * Reads the checkout rail's status, which resumes any operation the server - * reports pending. True once one was reported, so a caller watching for a - * payment taken elsewhere can hand off to the operation's own polling. + * 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 - await checkout.fetchStatus() const workspace = workspaceBillingRef.value - return checkout === workspace && workspace.hasPendingOperation.value + if (workspace === null || checkout !== workspace) { + await checkout.fetchStatus() + return false + } + return workspace.readAndAdoptPendingOperation() } async function subscribe(planSlug: string, options?: SubscribeOptions) { diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index a78987d445c..203740fdc8b 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -880,6 +880,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 9a8a6a0ed44..cda204d82ee 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' @@ -104,6 +106,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' @@ -334,6 +339,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 9030786b33e..0d5fd2192b9 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -6,7 +6,6 @@ import { shallowRef, watch } from 'vue' -import type { ComputedRef } from 'vue' import type { PreviewSubscribeInput } from '@comfyorg/account-core/billing' @@ -172,8 +171,11 @@ function seatCapacityFrom(status: BillingStatusResponse): SeatCapacity | null { */ export type WorkspaceBilling = BillingState & BillingActions & { - /** Whether the last status read reported an operation still pending. */ - hasPendingOperation: ComputedRef + /** + * 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 { @@ -188,9 +190,7 @@ export function useWorkspaceBilling(): WorkspaceBilling { const error = ref(null) const statusData = shallowRef(null) - const hasPendingOperation = computed( - () => !!statusData.value?.pending_billing_op_id - ) + let adoption: Promise = Promise.resolve(false) const seatCapacity = shallowRef(null) const balanceData = shallowRef(null) // Prevent older status and balance responses from overwriting newer state. @@ -300,16 +300,17 @@ export function useWorkspaceBilling(): WorkspaceBilling { : 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, @@ -317,6 +318,7 @@ export function useWorkspaceBilling(): WorkspaceBilling { undefined, status.action_url ) + return true } function isStaleStatusRead( @@ -329,7 +331,13 @@ export function useWorkspaceBilling(): WorkspaceBilling { ) } + 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() @@ -347,7 +355,7 @@ export function useWorkspaceBilling(): WorkspaceBilling { if (workspaceId && status.billing_rail) { workspaceStore.setWorkspaceBillingRail(workspaceId, status.billing_rail) } - resumePendingOperation(status) + adoption = resumePendingOperation(status) } catch (err) { if (requestId === latestBillingReadIds.status) { error.value = @@ -774,7 +782,7 @@ export function useWorkspaceBilling(): WorkspaceBilling { subscriptionStatus, tier, renewalDate, - hasPendingOperation, + readAndAdoptPendingOperation, // Actions initialize,