From 43502b82be724e649982e4b5082282d8105c44b1 Mon Sep 17 00:00:00 2001 From: Dante Date: Sun, 16 Aug 2026 12:00:52 +0000 Subject: [PATCH] FE-1585 fix(billing): refresh stale Run entitlement on app return (#15207) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why FE-1540 is only partially fixed by #14965. The Run surface no longer shows a paywall before billing initializes, but a successful `inactive` response remains cached when the authoritative subscription changes outside the open app—for example after returning from Stripe Portal, another tab, a delayed webhook, or a support action. `CloudRunButtonWrapper` previously refreshed on focus only when its own paused-payment recovery flow set `refreshBillingOnFocus`. A plain `Subscribe to Run` state had no focus/visibility recovery, so the user needed a manual page reload even after the server became `active`. ## AS IS ```mermaid sequenceDiagram participant FE as Open editor participant API as Billing API participant Provider as Stripe / webhook FE->>API: Fetch billing status API-->>FE: inactive Note over FE: Show Subscribe to Run Provider->>API: Subscription becomes active Note over FE,API: No pending BillingOp and no general refetch Note over FE: Cached inactive state remains until reload ``` ## TO BE ```mermaid sequenceDiagram participant User participant FE as CloudRunButtonWrapper participant Context as useBillingContext participant API as Authoritative billing API User->>FE: Return to app (focus / visible) FE->>FE: Confirm Subscribe to Run is displayed FE->>Context: fetchStatus + fetchBalance alt legacy billing rail Context->>API: Legacy billing reads else workspace billing rail Context->>API: Workspace billing reads end API-->>Context: active + current balance Context-->>FE: Reactive billing state updates Note over FE: Subscribe to Run becomes Run ``` ## Change - Revalidate status and balance when an app showing `Subscribe to Run` regains focus or becomes visible. - Route through `useBillingContext`, so the active legacy or workspace billing adapter remains authoritative. - Deduplicate overlapping `focus` and `visibilitychange` refreshes. - Preserve the existing paused-payment portal recovery behavior. - Do not add continuous polling: known new-billing checkouts retain BillingOp polling, while this is a bounded recovery trigger for changes outside that flow. ## Scope This PR does **not** infer subscription state in the frontend and does not attempt to prevent or resolve duplicate Stripe subscriptions. Provider subscription integrity remains a backend responsibility; the frontend only re-reads the server-authored state. ## Testing - `pnpm test:unit src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts` — 15 passed - `pnpm typecheck` — passed - changed-file ESLint, type-aware oxlint, and formatting checks — passed - `pnpm knip` — blocked by two existing unused devDependencies on `main` (`@storybook/addon-mcp`, `lint-staged`); this PR does not change package or knip configuration The component regression covers the observable AS IS → TO BE transition: stale `inactive`/Subscribe state, app focus, authoritative refresh, and restored Run button. No visual styling changes. Linear: FE-1540 --------- Co-authored-by: Amp --- browser_tests/tests/subscription.spec.ts | 25 ++++ .../CloudRunButtonWrapper.test.ts | 128 ++++++++++++++++++ .../ComfyRunButton/CloudRunButtonWrapper.vue | 31 ++++- 3 files changed, 178 insertions(+), 6 deletions(-) diff --git a/browser_tests/tests/subscription.spec.ts b/browser_tests/tests/subscription.spec.ts index 07188830f0e..7d8c5ec27b1 100644 --- a/browser_tests/tests/subscription.spec.ts +++ b/browser_tests/tests/subscription.spec.ts @@ -125,6 +125,31 @@ unsubscribedTest.describe( } ) + unsubscribedTest( + 'App focus refreshes stale subscription state and restores Run', + async ({ comfyPage, subscriptionHelper }) => { + await expect( + comfyPage.page.getByTestId(TestIds.topbar.subscribeToRunButton) + ).toBeVisible() + + subscriptionHelper.setStatus({ + is_active: true, + subscription_tier: 'STANDARD', + subscription_duration: 'MONTHLY' + }) + await comfyPage.page.evaluate(() => { + window.dispatchEvent(new Event('focus')) + }) + + await expect( + comfyPage.page.getByTestId(TestIds.topbar.queueButton) + ).toBeVisible() + await expect( + comfyPage.page.getByTestId(TestIds.topbar.subscribeToRunButton) + ).toBeHidden() + } + ) + unsubscribedTest( 'Cleanup prevents stale subscription state after dialog close', async ({ comfyPage, subscriptionHelper }) => { diff --git a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts index accd895a849..5747ae8e5be 100644 --- a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts +++ b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.test.ts @@ -112,6 +112,123 @@ describe('CloudRunButtonWrapper', () => { expect(screen.queryByTestId('queue-button')).not.toBeInTheDocument() }) + it('refreshes stale billing state on focus and restores Run', async () => { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'inactive' + state.fetchStatus.mockImplementationOnce(async () => { + mockBillingStatus.value = 'paid' + mockCanRunWorkflows.value = true + }) + renderWrapper() + + window.dispatchEvent(new Event('focus')) + + await waitFor(() => { + expect(state.fetchStatus).toHaveBeenCalledOnce() + expect(state.fetchBalance).toHaveBeenCalledOnce() + expect(screen.getByRole('button', { name: 'Run' })).toBeInTheDocument() + }) + }) + + it('refreshes stale billing state when the app becomes visible', async () => { + const visibilityState = vi + .spyOn(document, 'visibilityState', 'get') + .mockReturnValue('visible') + try { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'inactive' + state.fetchStatus.mockImplementationOnce(async () => { + mockBillingStatus.value = 'paid' + mockCanRunWorkflows.value = true + }) + renderWrapper() + + document.dispatchEvent(new Event('visibilitychange')) + + await waitFor(() => { + expect(state.fetchStatus).toHaveBeenCalledOnce() + expect(state.fetchBalance).toHaveBeenCalledOnce() + expect(screen.getByRole('button', { name: 'Run' })).toBeInTheDocument() + }) + } finally { + visibilityState.mockRestore() + } + }) + + it('deduplicates simultaneous focus and visibility refreshes', async () => { + let resolveRefresh!: () => void + const refresh = new Promise((resolve) => { + resolveRefresh = resolve + }) + const visibilityState = vi + .spyOn(document, 'visibilityState', 'get') + .mockReturnValue('visible') + try { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'inactive' + state.fetchStatus.mockReturnValueOnce(refresh) + state.fetchBalance.mockReturnValueOnce(refresh) + renderWrapper() + + window.dispatchEvent(new Event('focus')) + document.dispatchEvent(new Event('visibilitychange')) + + expect(state.fetchStatus).toHaveBeenCalledOnce() + expect(state.fetchBalance).toHaveBeenCalledOnce() + + resolveRefresh() + await refresh + } finally { + visibilityState.mockRestore() + } + }) + + it('does not refresh billing while Run is already available', () => { + renderWrapper() + + window.dispatchEvent(new Event('focus')) + + expect(state.fetchStatus).not.toHaveBeenCalled() + expect(state.fetchBalance).not.toHaveBeenCalled() + }) + + it('ignores visibility changes while the app remains hidden', () => { + const visibilityState = vi + .spyOn(document, 'visibilityState', 'get') + .mockReturnValue('hidden') + try { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'inactive' + renderWrapper() + + document.dispatchEvent(new Event('visibilitychange')) + + expect(state.fetchStatus).not.toHaveBeenCalled() + expect(state.fetchBalance).not.toHaveBeenCalled() + } finally { + visibilityState.mockRestore() + } + }) + + it('retries a failed stale billing refresh on the next focus', async () => { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'inactive' + state.fetchStatus.mockRejectedValueOnce(new Error('Status unavailable')) + state.fetchBalance.mockRejectedValueOnce(new Error('Balance unavailable')) + renderWrapper() + + window.dispatchEvent(new Event('focus')) + await waitFor(() => expect(state.fetchStatus).toHaveBeenCalledOnce()) + await new Promise((resolve) => setTimeout(resolve)) + + window.dispatchEvent(new Event('focus')) + + await waitFor(() => { + expect(state.fetchStatus).toHaveBeenCalledTimes(2) + expect(state.fetchBalance).toHaveBeenCalledTimes(2) + }) + }) + it('unlocks the run button once the subscription becomes active again', async () => { mockCanRunWorkflows.value = false renderWrapper() @@ -154,6 +271,17 @@ describe('CloudRunButtonWrapper', () => { expect(state.manageSubscription).toHaveBeenCalledOnce() }) + it('does not refresh paused billing before the recovery portal is opened', () => { + mockCanRunWorkflows.value = false + mockBillingStatus.value = 'paused' + renderWrapper() + + window.dispatchEvent(new Event('focus')) + + expect(state.fetchStatus).not.toHaveBeenCalled() + expect(state.fetchBalance).not.toHaveBeenCalled() + }) + it('keeps recovery open and surfaces portal failures', async () => { const error = new Error('Portal unavailable') state.manageSubscription.mockRejectedValueOnce(error) diff --git a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue index e0fba1aa9d0..0aecf58377f 100644 --- a/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue +++ b/src/components/actionbar/ComfyRunButton/CloudRunButtonWrapper.vue @@ -35,6 +35,7 @@ const dialogStore = useDialogStore() const { toastErrorHandler } = useErrorHandling() const isUpdatingPayment = ref(false) let paymentPortalRequest: Promise | null = null +let billingRefreshRequest: Promise | null = null let isUnmounted = false let refreshBillingOnFocus = false @@ -42,12 +43,6 @@ onUnmounted(() => { isUnmounted = true }) -useEventListener(window, 'focus', () => { - if (!refreshBillingOnFocus) return - refreshBillingOnFocus = false - void Promise.allSettled([fetchStatus(), fetchBalance()]) -}) - const paymentRecoveryLock = computed<'owner' | 'member' | null>(() => flags.v1PaymentRecovery && billingStatus.value === 'paused' ? permissions.value.canManageSubscription @@ -56,6 +51,30 @@ const paymentRecoveryLock = computed<'owner' | 'member' | null>(() => : null ) +function refreshStaleBillingState() { + if ( + billingRefreshRequest || + (!refreshBillingOnFocus && + (!showsSubscribeToRunPrompt.value || paymentRecoveryLock.value)) + ) { + return + } + + refreshBillingOnFocus = false + billingRefreshRequest = Promise.allSettled([ + fetchStatus(), + fetchBalance() + ]).then(() => undefined) + void billingRefreshRequest.finally(() => { + billingRefreshRequest = null + }) +} + +useEventListener(window, 'focus', refreshStaleBillingState) +useEventListener(document, 'visibilitychange', () => { + if (document.visibilityState === 'visible') refreshStaleBillingState() +}) + function closePaymentRecoveryDialog() { dialogStore.closeDialog({ key: DIALOG_KEY }) }