From 37d9210ed8d35824a04c454ba31a1d58919e738f Mon Sep 17 00:00:00 2001 From: Dante Date: Sat, 22 Aug 2026 02:00:54 +0000 Subject: [PATCH] fix(billing): make the Credits panel follow the active billing rail (#15151) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Settings → Credits still assumed the legacy `/customers` rail, so its activity table never loaded when the balance came from anywhere else, and Invoice History opened the wrong Stripe customer. ## Changes - **What**: - `UsageLogsTable` owns its first load (`immediate` watch on the billing route). It previously started at `loading = true` and waited for a parent `refresh()`, which `CreditsPanel` only fired from `authStore.lastBalanceUpdateTime` — written solely by the legacy `/customers/balance` success path (`authStore.ts:374`). Any path that does not write it leaves the spinner up forever. - `CreditsPanel` refreshes activity off the balance it renders instead of that legacy-only timestamp, so a top-up refreshes the table on both rails. First hydration is skipped, since the table now loads itself. - Invoice History routes through `useBillingContext().manageSubscription()`, matching `SubscriptionFooterLinks`. The legacy `/customers` portal bills a different Stripe customer than the workspace on screen. ## Review Focus Two independent ways to reach the stuck spinner on `main`: 1. **Local/Desktop, new account** — `authStore.fetchBalance()` returns early on a `404` from `/customers/balance` (`authStore.ts:355-358`), so `lastBalanceUpdateTime` is never written. A user with no customer record yet gets a Credits tab that spins forever. 2. **Cloud, workspace rail** — with `billing_control_enabled` off the standalone Credits panel stays in the sidebar (`useSettingUI.ts:325`) while `useWorkspaceBilling.fetchBalance()` supplies the balance from `/billing/balance` and never touches the timestamp. This also becomes the default failure once the workspace switcher is exposed on Local/Desktop (#15051). Other notes: - `AutoRefreshWrapper` is gone from the `UsageLogsTable` tests; the component no longer needs a parent to drive its first fetch. Reverting the `immediate` flag alone fails 19 of the 21 tests. - Legacy `manageSubscription()` also starts the cancellation watcher, which the raw `accessBillingPortal()` call did not. `SubscriptionFooterLinks` already accepts that for the same action, and `browser_tests/tests/localCreditsNoSubscribeUi.spec.ts` (which asserts Invoice History issues `POST /customers/billing`) still passes. ## Screenshots Captured from the same local dev-server setup and viewport with a fully mocked Personal workspace on the workspace billing rail. `billing_control_enabled` is off so the standalone Settings → Credits panel is visible. AS-IS uses base `085c6ec51`; TO-BE uses this PR's head `e9fcd6adc`. | AS-IS | TO-BE | | --- | --- | | Activity stays on the loading indicator because no initial request is issued. | Activity loads from `/api/billing/events` on mount. | | ![AS-IS — Credits activity stuck loading](https://ampcode.com/user-content/artifacts/50a4a56fc1f0a33cf6c00e5fb3bfd64b4365b2261217eace1e01ec243a61aa7d-file.png) | ![TO-BE — Credits activity loaded](https://ampcode.com/user-content/artifacts/cb6f3f0d3dda7ca1f329ce34517f851dc451afccd8748bd7ccdc0e0e1479a762-file.png) | Linear: [FE-1584](https://linear.app/comfyorg/issue/FE-1584/add-workspace-switcher-to-localdesktop-credits-only-no-settings) Prototype this supports: #15051 --- .../content/setting/CreditsPanel.test.ts | 117 ++++++++++++++++++ .../dialog/content/setting/CreditsPanel.vue | 20 ++- .../content/setting/UsageLogsTable.test.ts | 56 ++++----- .../dialog/content/setting/UsageLogsTable.vue | 14 ++- 4 files changed, 160 insertions(+), 47 deletions(-) create mode 100644 src/components/dialog/content/setting/CreditsPanel.test.ts diff --git a/src/components/dialog/content/setting/CreditsPanel.test.ts b/src/components/dialog/content/setting/CreditsPanel.test.ts new file mode 100644 index 00000000000..69e295a1596 --- /dev/null +++ b/src/components/dialog/content/setting/CreditsPanel.test.ts @@ -0,0 +1,117 @@ +import { render, screen } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h, nextTick } from 'vue' +import { createI18n } from 'vue-i18n' + +import type { BalanceInfo } from '@/composables/billing/types' + +import CreditsPanel from './CreditsPanel.vue' + +const billingMocks = vi.hoisted(() => ({ + balance: { value: null as BalanceInfo | null }, + manageSubscription: vi.fn() +})) +vi.mock('@/composables/billing/useBillingContext', async () => { + const { ref } = await import('vue') + const balance = ref(null) + Object.defineProperty(billingMocks, 'balance', { get: () => balance }) + return { + useBillingContext: () => ({ + balance, + manageSubscription: billingMocks.manageSubscription + }) + } +}) + +const refreshActivity = vi.hoisted(() => vi.fn()) +vi.mock('./UsageLogsTable.vue', async () => { + const { defineComponent, h } = await import('vue') + return { + default: defineComponent({ + setup(_props, { expose }) { + expose({ refresh: refreshActivity }) + return () => h('div', { 'data-testid': 'usage-logs-table' }) + } + }) + } +}) + +vi.mock('@/platform/cloud/subscription/components/CreditsTile.vue', () => ({ + default: defineComponent({ setup: () => () => h('div') }) +})) + +vi.mock('@/platform/telemetry', () => ({ + useTelemetry: () => ({ trackHelpResourceClicked: vi.fn() }) +})) + +vi.mock('@/stores/commandStore', () => ({ + useCommandStore: () => ({ execute: vi.fn() }) +})) + +vi.mock('@/composables/useExternalLink', () => ({ + useExternalLink: () => ({ + buildDocsUrl: () => 'https://docs.comfy.org', + docsPaths: { partnerNodesPricing: '/partner-nodes' } + }) +})) + +const i18n = createI18n({ + legacy: false, + locale: 'en', + messages: { + en: { + credits: { + credits: 'Credits', + activity: 'Activity', + invoiceHistory: 'Invoice History', + faqs: 'FAQs', + messageSupport: 'Message Support' + }, + subscription: { partnerNodesCredits: 'Partner Nodes Credits' } + } + } +}) + +function makeBalance(amountMicros: number): BalanceInfo { + return { + amountMicros, + currency: 'usd', + effectiveBalanceMicros: amountMicros, + prepaidBalanceMicros: 0, + cloudCreditBalanceMicros: 0 + } +} + +describe('CreditsPanel', () => { + beforeEach(() => { + billingMocks.balance.value = null + }) + + function renderComponent() { + return render(CreditsPanel, { + global: { plugins: [i18n], stubs: { Divider: true } } + }) + } + + it('opens the billing portal for the active billing rail', async () => { + const user = userEvent.setup() + renderComponent() + + await user.click(screen.getByRole('button', { name: /Invoice History/ })) + + expect(billingMocks.manageSubscription).toHaveBeenCalledOnce() + }) + + it('refreshes activity on a balance change but not on first hydration', async () => { + renderComponent() + + billingMocks.balance.value = makeBalance(5000) + await nextTick() + expect(refreshActivity).not.toHaveBeenCalled() + + billingMocks.balance.value = makeBalance(9000) + await nextTick() + expect(refreshActivity).toHaveBeenCalledOnce() + }) +}) diff --git a/src/components/dialog/content/setting/CreditsPanel.vue b/src/components/dialog/content/setting/CreditsPanel.vue index e9753640a8d..05d84bc6635 100644 --- a/src/components/dialog/content/setting/CreditsPanel.vue +++ b/src/components/dialog/content/setting/CreditsPanel.vue @@ -65,11 +65,10 @@ import { ref, watch } from 'vue' import UsageLogsTable from '@/components/dialog/content/setting/UsageLogsTable.vue' import Button from '@/components/ui/button/Button.vue' -import { useAuthActions } from '@/composables/auth/useAuthActions' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useExternalLink } from '@/composables/useExternalLink' import CreditsTile from '@/platform/cloud/subscription/components/CreditsTile.vue' import { useTelemetry } from '@/platform/telemetry' -import { useAuthStore } from '@/stores/authStore' import { useCommandStore } from '@/stores/commandStore' const { embedded = false } = defineProps<{ @@ -77,24 +76,19 @@ const { embedded = false } = defineProps<{ }>() const { buildDocsUrl, docsPaths } = useExternalLink() -const authStore = useAuthStore() -const authActions = useAuthActions() +const { balance, manageSubscription } = useBillingContext() const commandStore = useCommandStore() const telemetry = useTelemetry() const usageLogsTableRef = ref | null>(null) -watch( - () => authStore.lastBalanceUpdateTime, - (newTime, oldTime) => { - if (newTime && newTime !== oldTime && usageLogsTableRef.value) { - void usageLogsTableRef.value.refresh() - } - } -) +watch(balance, (next, previous) => { + if (!next || !previous) return + void usageLogsTableRef.value?.refresh() +}) const handleCreditsHistoryClick = async () => { - await authActions.accessBillingPortal() + await manageSubscription() } const handleMessageSupport = async () => { diff --git a/src/components/dialog/content/setting/UsageLogsTable.test.ts b/src/components/dialog/content/setting/UsageLogsTable.test.ts index 2558ac1dac3..be93eeb29fa 100644 --- a/src/components/dialog/content/setting/UsageLogsTable.test.ts +++ b/src/components/dialog/content/setting/UsageLogsTable.test.ts @@ -2,7 +2,7 @@ import { createTestingPinia } from '@pinia/testing' import PrimeVue from 'primevue/config' import Tooltip from 'primevue/tooltip' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { defineComponent, nextTick, onMounted, ref } from 'vue' +import { nextTick } from 'vue' import { createI18n } from 'vue-i18n' import { render, screen, waitFor } from '@testing-library/vue' @@ -91,22 +91,6 @@ const globalConfig = { directives: { tooltip: Tooltip } } -/** - * The component starts with loading=true and only loads data when refresh() - * is called via template ref. This wrapper auto-calls refresh on mount. - */ -const AutoRefreshWrapper = defineComponent({ - components: { UsageLogsTable }, - setup() { - const tableRef = ref | null>(null) - onMounted(async () => { - await tableRef.value?.refresh() - }) - return { tableRef } - }, - template: '' -}) - async function flushMicrotasks() { await new Promise((resolve) => setTimeout(resolve, 0)) await nextTick() @@ -208,12 +192,8 @@ describe('UsageLogsTable', () => { return render(UsageLogsTable, { global: globalConfig }) } - function renderWithAutoRefresh() { - return render(AutoRefreshWrapper, { global: globalConfig }) - } - async function renderLoaded() { - const result = renderWithAutoRefresh() + const result = renderComponent() await waitFor(() => { expect(screen.getByRole('table')).toBeInTheDocument() }) @@ -221,7 +201,25 @@ describe('UsageLogsTable', () => { } describe('loading states', () => { - it('shows loading spinner before refresh is called', () => { + it('loads activity on mount without an external refresh', async () => { + await renderLoaded() + + expect(mockCustomerEventsService.getMyEvents).toHaveBeenCalledTimes(1) + }) + + it('loads activity on mount on the workspace billing rail', async () => { + mockBillingRouting.shouldUseWorkspaceBilling = true + + await renderLoaded() + + expect(mockWorkspaceApi.getBillingEvents).toHaveBeenCalledTimes(1) + }) + + it('shows a loading spinner while the initial load is in flight', () => { + mockCustomerEventsService.getMyEvents.mockReturnValue( + new Promise(() => {}) + ) + renderComponent() expect(screen.getByRole('progressbar')).toBeInTheDocument() @@ -232,7 +230,7 @@ describe('UsageLogsTable', () => { mockCustomerEventsService.getMyEvents.mockResolvedValue(null) mockCustomerEventsService.error.value = 'Failed to load events' - renderWithAutoRefresh() + renderComponent() await waitFor(() => { expect(screen.getByText('Failed to load events')).toBeInTheDocument() @@ -244,7 +242,7 @@ describe('UsageLogsTable', () => { new Error('Network error') ) - renderWithAutoRefresh() + renderComponent() await waitFor(() => { expect( @@ -260,7 +258,7 @@ describe('UsageLogsTable', () => { mockCustomerEventsService.getMyEvents.mockResolvedValue(null) mockCustomerEventsService.error.value = null - renderWithAutoRefresh() + renderComponent() await waitFor(() => { expect( @@ -312,7 +310,7 @@ describe('UsageLogsTable', () => { ]) ) - renderWithAutoRefresh() + renderComponent() await waitFor(() => { expect(screen.getByText('Account initialized')).toBeInTheDocument() @@ -400,7 +398,7 @@ describe('UsageLogsTable', () => { ]) ) - renderWithAutoRefresh() + renderComponent() mockBillingRouting.shouldUseWorkspaceBilling = true await waitFor(() => { @@ -442,7 +440,7 @@ describe('UsageLogsTable', () => { ]) ) - renderWithAutoRefresh() + renderComponent() mockBillingRouting.shouldUseWorkspaceBilling = true await waitFor(() => { diff --git a/src/components/dialog/content/setting/UsageLogsTable.vue b/src/components/dialog/content/setting/UsageLogsTable.vue index 8137c7b0716..60cdc5f600c 100644 --- a/src/components/dialog/content/setting/UsageLogsTable.vue +++ b/src/components/dialog/content/setting/UsageLogsTable.vue @@ -212,11 +212,15 @@ const refresh = async () => { await loadEvents() } -watch(shouldUseWorkspaceBilling, () => { - refresh().catch((error) => { - console.error('Error loading events:', error) - }) -}) +watch( + shouldUseWorkspaceBilling, + () => { + refresh().catch((error) => { + console.error('Error loading events:', error) + }) + }, + { immediate: true } +) defineExpose({ refresh