From 6353dd6b3847a70abaec919fc39bd3beb8026961 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 19 Aug 2026 20:08:31 +0530 Subject: [PATCH 01/14] feat(billing): route local billing reads to cloud ingest Off-cloud, getBillingStatus/getBillingBalance/getBillingPlans resolve to the cloud ingest origin (two-tier: prod const or VITE_CLOUD_INGEST_BASE_URL ?? staging) via a per-endpoint resolver, never a client-wide baseURL, so every other billing endpoint stays local-unreachable. shouldUseUnifiedPricing gains the !isCloud arm so the plans rail reads workspace billing off-cloud while type keeps account operations (top-up) on the legacy rail. --- .../billing/useBillingRouting.test.ts | 21 +++++-- src/composables/billing/useBillingRouting.ts | 7 ++- src/config/comfyApi.test.ts | 26 +++++++- src/config/comfyApi.ts | 15 +++++ .../workspace/api/workspaceApi.test.ts | 61 ++++++++++++++++++- src/platform/workspace/api/workspaceApi.ts | 16 ++++- src/vite-env.d.ts | 1 + 7 files changed, 136 insertions(+), 11 deletions(-) diff --git a/src/composables/billing/useBillingRouting.test.ts b/src/composables/billing/useBillingRouting.test.ts index e578072acaa..bdf03d23475 100644 --- a/src/composables/billing/useBillingRouting.test.ts +++ b/src/composables/billing/useBillingRouting.test.ts @@ -58,14 +58,26 @@ describe('useBillingRouting', () => { mockActiveWorkspaceBillingRail.value = null }) - it('uses legacy billing off Cloud', () => { + it('keeps account operations legacy off Cloud while the plans rail uses workspace billing', () => { mockIsCloud.value = false mockActiveWorkspace.value = team - const { type, shouldUseWorkspaceBilling } = useBillingRouting() + const { type, shouldUseWorkspaceBilling, shouldUseUnifiedPricing } = + useBillingRouting() expect(type.value).toBe('legacy') expect(shouldUseWorkspaceBilling.value).toBe(false) + expect(shouldUseUnifiedPricing.value).toBe(true) + }) + + it('routes the plans rail to workspace billing off Cloud before any workspace loads', () => { + mockIsCloud.value = false + mockActiveWorkspace.value = null + + const { type, shouldUseUnifiedPricing } = useBillingRouting() + + expect(type.value).toBe('legacy') + expect(shouldUseUnifiedPricing.value).toBe(true) }) it('uses workspace billing for a Cloud personal workspace', () => { @@ -117,11 +129,12 @@ describe('useBillingRouting', () => { expect(shouldUseWorkspaceBilling.value).toBe(true) }) - it('defaults to legacy while the workspace has not loaded', () => { + it('defaults to legacy while the Cloud workspace has not loaded', () => { mockActiveWorkspace.value = null - const { type } = useBillingRouting() + const { type, shouldUseUnifiedPricing } = useBillingRouting() expect(type.value).toBe('legacy') + expect(shouldUseUnifiedPricing.value).toBe(false) }) }) diff --git a/src/composables/billing/useBillingRouting.ts b/src/composables/billing/useBillingRouting.ts index 6b7d9311aca..7ec01d1014f 100644 --- a/src/composables/billing/useBillingRouting.ts +++ b/src/composables/billing/useBillingRouting.ts @@ -11,14 +11,17 @@ import type { BillingType } from './types' * (`/customers/*`) or workspace-scoped (`/api/billing/*`). Personal workspaces * use workspace billing unless an explicit legacy Stripe rail selects legacy * account operations and its migration flag is off. An unloaded workspace - * remains legacy during bootstrap, and OSS always uses legacy billing. + * remains legacy during bootstrap. Off-cloud, account operations (`type`) stay + * legacy while the plans rail (`shouldUseUnifiedPricing`) reads workspace + * billing from cloud ingest — the same split cloud runs for legacy Stripe + * workspaces. */ export function useBillingRouting() { const { flags } = useFeatureFlags() const workspaceStore = useTeamWorkspaceStore() const shouldUseUnifiedPricing = computed(() => { - return isCloud && workspaceStore.activeWorkspace?.type !== undefined + return !isCloud || workspaceStore.activeWorkspace?.type !== undefined }) const type = computed(() => { diff --git a/src/config/comfyApi.test.ts b/src/config/comfyApi.test.ts index 8e83c031fe5..65bcc4093a1 100644 --- a/src/config/comfyApi.test.ts +++ b/src/config/comfyApi.test.ts @@ -3,7 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' -import { getComfyApiBaseUrl, getComfyPlatformBaseUrl } from './comfyApi' +import { + getCloudIngestBaseUrl, + getComfyApiBaseUrl, + getComfyPlatformBaseUrl +} from './comfyApi' vi.mock('@/scripts/api', () => ({ api: { @@ -68,6 +72,26 @@ describe('getComfyPlatformBaseUrl', () => { }) }) +describe('getCloudIngestBaseUrl', () => { + afterEach(() => { + vi.unstubAllEnvs() + vi.resetModules() + }) + + it('resolves the staging cloud origin in non-prod builds', () => { + expect(getCloudIngestBaseUrl()).toBe('https://stagingcloud.comfy.org') + }) + + it('honors the VITE_CLOUD_INGEST_BASE_URL build-time override', async () => { + vi.stubEnv('VITE_CLOUD_INGEST_BASE_URL', 'https://testcloud.comfy.org') + vi.resetModules() + + const { getCloudIngestBaseUrl: rebuilt } = await import('./comfyApi') + + expect(rebuilt()).toBe('https://testcloud.comfy.org') + }) +}) + describe('compatibility with comfyui servers that predate the override keys', () => { const originalConfig = remoteConfig.value diff --git a/src/config/comfyApi.ts b/src/config/comfyApi.ts index 86e3c5ce8c7..49c29287883 100644 --- a/src/config/comfyApi.ts +++ b/src/config/comfyApi.ts @@ -9,6 +9,9 @@ const STAGING_API_BASE_URL = 'https://stagingapi.comfy.org' const PROD_PLATFORM_BASE_URL = 'https://platform.comfy.org' const STAGING_PLATFORM_BASE_URL = 'https://stagingplatform.comfy.org' +const PROD_CLOUD_INGEST_BASE_URL = 'https://cloud.comfy.org' +const STAGING_CLOUD_INGEST_BASE_URL = 'https://stagingcloud.comfy.org' + const BUILD_TIME_API_BASE_URL = __USE_PROD_CONFIG__ ? PROD_API_BASE_URL : (import.meta.env.VITE_STAGING_API_BASE_URL ?? STAGING_API_BASE_URL) @@ -18,6 +21,14 @@ const BUILD_TIME_PLATFORM_BASE_URL = __USE_PROD_CONFIG__ : (import.meta.env.VITE_STAGING_PLATFORM_BASE_URL ?? STAGING_PLATFORM_BASE_URL) +// Two-tier only: no remote-config override, because this URL is consumed +// off-cloud where remoteConfig is served by the local ComfyUI server and never +// carries cloud keys. +const BUILD_TIME_CLOUD_INGEST_BASE_URL = __USE_PROD_CONFIG__ + ? PROD_CLOUD_INGEST_BASE_URL + : (import.meta.env.VITE_CLOUD_INGEST_BASE_URL ?? + STAGING_CLOUD_INGEST_BASE_URL) + export function getComfyApiBaseUrl(): string { return configValueOrDefault( remoteConfig.value, @@ -33,3 +44,7 @@ export function getComfyPlatformBaseUrl(): string { BUILD_TIME_PLATFORM_BASE_URL ) } + +export function getCloudIngestBaseUrl(): string { + return BUILD_TIME_CLOUD_INGEST_BASE_URL +} diff --git a/src/platform/workspace/api/workspaceApi.test.ts b/src/platform/workspace/api/workspaceApi.test.ts index 42f805f166b..961e47932a2 100644 --- a/src/platform/workspace/api/workspaceApi.test.ts +++ b/src/platform/workspace/api/workspaceApi.test.ts @@ -3,8 +3,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { mockAxiosInstance, mockGetAuthHeaderOrThrow, - mockGetFirebaseAuthHeaderOrThrow + mockGetFirebaseAuthHeaderOrThrow, + mockIsCloud } = vi.hoisted(() => ({ + mockIsCloud: { value: true }, mockAxiosInstance: { get: vi.fn(), post: vi.fn(), @@ -40,6 +42,12 @@ vi.mock('@/scripts/api', () => ({ } })) +vi.mock('@/platform/distribution/types', () => ({ + get isCloud() { + return mockIsCloud.value + } +})) + vi.mock('@/stores/authStore', () => ({ useAuthStore: () => ({ getAuthHeaderOrThrow: mockGetAuthHeaderOrThrow, @@ -53,6 +61,7 @@ const AUTH_HEADER = { Authorization: 'Bearer test-token' } describe('workspaceApi', () => { beforeEach(() => { + mockIsCloud.value = true mockGetAuthHeaderOrThrow.mockResolvedValue(AUTH_HEADER) mockGetFirebaseAuthHeaderOrThrow.mockResolvedValue(AUTH_HEADER) }) @@ -434,6 +443,56 @@ describe('workspaceApi', () => { }) }) + describe('billing routing off cloud', () => { + beforeEach(() => { + mockIsCloud.value = false + }) + + it('routes billing reads to cloud ingest', async () => { + mockAxiosInstance.get.mockResolvedValue({ data: {} }) + + await workspaceApi.getBillingStatus() + await workspaceApi.getBillingBalance() + await workspaceApi.getBillingPlans() + + expect(mockAxiosInstance.get).toHaveBeenNthCalledWith( + 1, + 'https://stagingcloud.comfy.org/api/billing/status', + { headers: AUTH_HEADER } + ) + expect(mockAxiosInstance.get).toHaveBeenNthCalledWith( + 2, + 'https://stagingcloud.comfy.org/api/billing/balance', + { headers: AUTH_HEADER } + ) + expect(mockAxiosInstance.get).toHaveBeenNthCalledWith( + 3, + 'https://stagingcloud.comfy.org/api/billing/plans', + { headers: AUTH_HEADER } + ) + }) + + it('keeps mutating billing endpoints on the local relative form', async () => { + mockAxiosInstance.post.mockResolvedValue({ data: {} }) + + await workspaceApi.createTopup(1000, 'key-local') + await workspaceApi.subscribe('pro-monthly') + + expect(mockAxiosInstance.post).toHaveBeenNthCalledWith( + 1, + '/api/billing/topup', + { amount_cents: 1000, idempotency_key: 'key-local' }, + { headers: AUTH_HEADER } + ) + expect(mockAxiosInstance.post).toHaveBeenNthCalledWith( + 2, + '/api/billing/subscribe', + { plan_slug: 'pro-monthly' }, + { headers: AUTH_HEADER } + ) + }) + }) + describe('subscription', () => { it('previewSubscribe() sends POST with plan_slug', async () => { const data = { allowed: true, transition_type: 'new_subscription' } diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index c36f30e7fba..8ff459b92bd 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -36,8 +36,10 @@ import type { } from '@comfyorg/ingest-types' import axios from 'axios' +import { getCloudIngestBaseUrl } from '@/config/comfyApi' import { attachUnifiedRemintInterceptor } from '@/platform/auth/unified/remintRetry' import { churnkeyAuthResponseSchema } from '@/platform/cloud/churnkey/churnkeyAuthSchema' +import { isCloud } from '@/platform/distribution/types' import { UNKNOWN_ERROR_CODE, errorResponseFromBody @@ -166,6 +168,14 @@ async function getAuthHeaderOrThrow() { return useAuthStore().getAuthHeaderOrThrow() } +// Billing READS resolve per endpoint, never via a client-wide baseURL: off-cloud +// they go to cloud ingest (CORS-allowed for loopback), while every other +// endpoint keeps the relative form so it stays unreachable from local. +function resolveBillingUrl(path: string): string { + if (isCloud) return api.apiURL(path) + return `${getCloudIngestBaseUrl()}/api${path}` +} + function handleAxiosError(err: unknown): never { if (axios.isAxiosError(err)) { const status = err.response?.status @@ -417,7 +427,7 @@ export const workspaceApi = { const headers = await getAuthHeaderOrThrow() try { const response = await workspaceApiClient.get( - api.apiURL('/billing/status'), + resolveBillingUrl('/billing/status'), { headers } ) return response.data @@ -434,7 +444,7 @@ export const workspaceApi = { const headers = await getAuthHeaderOrThrow() try { const response = await workspaceApiClient.get( - api.apiURL('/billing/balance'), + resolveBillingUrl('/billing/balance'), { headers } ) return response.data @@ -451,7 +461,7 @@ export const workspaceApi = { const headers = await getAuthHeaderOrThrow() try { const response = await workspaceApiClient.get( - api.apiURL('/billing/plans'), + resolveBillingUrl('/billing/plans'), { headers } ) return response.data diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts index 6dd540572f4..aab518a3585 100644 --- a/src/vite-env.d.ts +++ b/src/vite-env.d.ts @@ -21,6 +21,7 @@ declare global { VITE_APP_VERSION?: string VITE_STAGING_API_BASE_URL?: string VITE_STAGING_PLATFORM_BASE_URL?: string + VITE_CLOUD_INGEST_BASE_URL?: string } interface ImportMeta { From 1257a7dbbe50dc6be0c96a75095f7dc93616441d Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 19 Aug 2026 20:09:11 +0530 Subject: [PATCH 02/14] feat(billing): fetch live plans for the local plans section The section dispatches one plans fetch through the billing context on mount, so the team credit stops render backend data with the DES-197 constants as the pre-fetch/failure fallback. A late-arriving payload with different breakpoints re-snaps the slider seed to the resolved default, mirroring UnifiedPricingTable. --- .../settings/SettingsPlansSection.test.ts | 49 ++++++++++++++++++- .../dialogs/settings/SettingsPlansSection.vue | 17 ++++++- 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts index 57ac6b70371..42ecf7ebd05 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts @@ -1,13 +1,20 @@ import userEvent from '@testing-library/user-event' -import { describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' import { render, screen } from '@testing-library/vue' import enMessages from '@/locales/en/main.json' +import { useBillingPlans } from '@/platform/cloud/subscription/composables/useBillingPlans' import SettingsPlansSection from './SettingsPlansSection.vue' +const { mockFetchPlans } = vi.hoisted(() => ({ mockFetchPlans: vi.fn() })) + +vi.mock('@/composables/billing/useBillingContext', () => ({ + useBillingContext: () => ({ fetchPlans: mockFetchPlans }) +})) + const i18n = createI18n({ legacy: false, locale: 'en', @@ -32,6 +39,46 @@ function renderSection() { } describe('SettingsPlansSection', () => { + beforeEach(() => { + useBillingPlans().teamCreditStops.value = null + mockFetchPlans.mockReset() + }) + + it('fetches plans through the billing context on mount', () => { + renderSection() + + expect(mockFetchPlans).toHaveBeenCalledTimes(1) + }) + + it('re-snaps the slider to the API default when stops arrive after mount', async () => { + renderSection() + + await userEvent.click(screen.getByRole('button', { name: 'Teams' })) + expect(screen.getByText('147,700')).toBeTruthy() + + useBillingPlans().teamCreditStops.value = { + default_stop_index: 1, + stops: [ + { + id: 'team_300', + credits: 63_300, + monthly: { list_price_cents: 30_000, price_cents: 30_000 }, + yearly: { list_price_cents: 30_000, price_cents: 30_000 } + }, + { + id: 'team_900', + credits: 189_900, + monthly: { list_price_cents: 90_000, price_cents: 85_500 }, + yearly: { list_price_cents: 90_000, price_cents: 81_000 } + } + ] + } + + expect(await screen.findByText('189,900')).toBeTruthy() + expect(screen.getByText('Generates ~17,235 5s videos*')).toBeTruthy() + expect(screen.queryByText('147,700')).toBeNull() + }) + it('renders the three personal cards with yearly pricing by default', () => { renderSection() diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue index 0cb0ac04d49..246d1e26f39 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue @@ -248,9 +248,10 @@ diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts index b644261ceaf..167c9ea320e 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts @@ -5,7 +5,10 @@ import { createI18n } from 'vue-i18n' import { render, screen } from '@testing-library/vue' import enMessages from '@/locales/en/main.json' -import type { Plan } from '@/platform/workspace/api/workspaceApi' +import type { + Plan, + TeamCreditStops +} from '@/platform/workspace/api/workspaceApi' import SettingsPlansSection from './SettingsPlansSection.vue' @@ -15,8 +18,6 @@ const i18n = createI18n({ messages: { en: enMessages } }) -// Pinned to the real billing catalog (cloud common/billing/catalog/catalog_test.go:32-36): -// price_cents is the LIST amount, credits_cents the period credit total. function makePlan( tier: Plan['tier'], duration: Plan['duration'], @@ -48,87 +49,140 @@ const CATALOG: Plan[] = [ makePlan('PRO', 'MONTHLY', 10000, 21100) ] -function renderSection(catalogPlans: Plan[] = CATALOG) { +// Distinct from any frontend constant so a render that ignored the prop would +// show different numbers (147,700 / $700 were the old TEAM_PLAN_CREDIT_STOPS). +const TEAM_STOPS: TeamCreditStops = { + default_stop_index: 1, + stops: [ + { + id: 'team_300', + credits: 63_300, + monthly: { list_price_cents: 30_000, price_cents: 30_000 }, + yearly: { list_price_cents: 30_000, price_cents: 27_000 } + }, + { + id: 'team_900', + credits: 189_900, + monthly: { list_price_cents: 90_000, price_cents: 85_500 }, + yearly: { list_price_cents: 90_000, price_cents: 81_000 } + } + ] +} + +function renderSection( + props: { + catalogPlans?: Plan[] + teamCreditStops?: TeamCreditStops | null + isLoading?: boolean + } = {} +) { return render(SettingsPlansSection, { - props: { catalogPlans }, + props: { catalogPlans: CATALOG, teamCreditStops: TEAM_STOPS, ...props }, global: { plugins: [i18n] } }) } -describe('SettingsPlansSection personal cards from the API catalog', () => { - it('renders the API list price and credits for the yearly cycle', () => { +describe('SettingsPlansSection — API is the source of truth', () => { + it('renders personal prices and credits from the catalog (yearly)', () => { renderSection() - // $20/mo = list 24000/100/12, billed yearly total $240 = 24000/100 — the - // API list price, not the discounted $16/$192 the old constant baked in. expect(screen.getByText('$20')).toBeTruthy() expect(screen.getByText('$35')).toBeTruthy() expect(screen.getByText('$100')).toBeTruthy() - expect(screen.getByText('$240 Billed yearly')).toBeTruthy() - expect(screen.getByText('$420 Billed yearly')).toBeTruthy() expect(screen.getByText('$1200 Billed yearly')).toBeTruthy() - - // credits_cents is the annual total, rendered as-is (no ×12). expect(screen.getByText('50,400')).toBeTruthy() - expect(screen.getByText('88,800')).toBeTruthy() expect(screen.getByText('253,200')).toBeTruthy() }) - it('renders the API price and credits for the monthly cycle', async () => { - renderSection() - await userEvent.click(screen.getByRole('switch')) - - expect(screen.getByText('$20')).toBeTruthy() - expect(screen.getByText('$35')).toBeTruthy() - expect(screen.getByText('$100')).toBeTruthy() - expect(screen.getAllByText('Billed monthly')).toHaveLength(3) - - expect(screen.getByText('4,200')).toBeTruthy() - expect(screen.getByText('7,400')).toBeTruthy() - expect(screen.getByText('21,100')).toBeTruthy() - }) - - it('moves the rendered numbers when the catalog values change', () => { + it('moves the personal numbers when the catalog values change', () => { const mutated = CATALOG.map((p) => p.tier === 'STANDARD' && p.duration === 'ANNUAL' ? makePlan('STANDARD', 'ANNUAL', 30000, 60000) : p ) - renderSection(mutated) + renderSection({ catalogPlans: mutated }) - // $25/mo = 30000/100/12, $300 yearly, 60,000 credits — proof the render is - // wired to the API row, not to a constant. expect(screen.getByText('$25')).toBeTruthy() expect(screen.getByText('$300 Billed yearly')).toBeTruthy() expect(screen.getByText('60,000')).toBeTruthy() expect(screen.queryByText('$240 Billed yearly')).toBeNull() }) - it('renders no cards when the catalog is empty', () => { - renderSection([]) + it('renders team credits from the API stops, not a constant', async () => { + renderSection() + await userEvent.click(screen.getByRole('button', { name: 'Teams' })) + + // default_stop_index 1 => the $900 / 189,900 stop. + expect(screen.getByText('189,900')).toBeTruthy() + // The old constant stop must never appear. + expect(screen.queryByText('147,700')).toBeNull() + }) + + it('moves the team credits when the API stops change', async () => { + const mutated: TeamCreditStops = { + default_stop_index: 0, + stops: [ + { + id: 'team_500', + credits: 111_000, + monthly: { list_price_cents: 50_000, price_cents: 50_000 }, + yearly: { list_price_cents: 50_000, price_cents: 45_000 } + } + ] + } + renderSection({ teamCreditStops: mutated }) + await userEvent.click(screen.getByRole('button', { name: 'Teams' })) + + expect(screen.getByText('111,000')).toBeTruthy() + expect(screen.queryByText('189,900')).toBeNull() + }) + + it('shows the unavailable state for personal when the catalog is empty', () => { + renderSection({ catalogPlans: [], teamCreditStops: null }) - expect(screen.queryByText('Standard')).toBeNull() - expect(screen.queryByText('Creator')).toBeNull() - expect(screen.queryByText('Pro')).toBeNull() + expect(screen.getByText("We couldn't load your plan details.")).toBeTruthy() expect(screen.queryByText(/\$\d+ Billed yearly/)).toBeNull() + expect(screen.queryByText('50,400')).toBeNull() }) - it('only renders tiers that have a matching catalog row', () => { - renderSection([makePlan('STANDARD', 'ANNUAL', 24000, 50400)]) + it('shows the unavailable state for teams when stops are absent', async () => { + renderSection({ teamCreditStops: null }) + await userEvent.click(screen.getByRole('button', { name: 'Teams' })) - expect(screen.getByText('Standard')).toBeTruthy() - expect(screen.queryByText('Creator')).toBeNull() - expect(screen.queryByText('Pro')).toBeNull() + expect(screen.getByText("We couldn't load your plan details.")).toBeTruthy() + // No constant-seeded slider stop. + expect(screen.queryByText('147,700')).toBeNull() + }) + + it('emits retry from the unavailable state', async () => { + const { emitted } = renderSection({ + catalogPlans: [], + teamCreditStops: null + }) + + await userEvent.click(screen.getByRole('button', { name: 'Try again' })) + expect(emitted().retry).toBeTruthy() + }) + + it('shows a spinner and no prices while loading', () => { + renderSection({ isLoading: true, catalogPlans: [], teamCreditStops: null }) + + expect(screen.getByText('Loading')).toBeTruthy() + expect(screen.queryByText("We couldn't load your plan details.")).toBeNull() + expect(screen.queryByText(/\$\d+ Billed yearly/)).toBeNull() }) - it('disables the choose CTA and shows no discount pill or checkout caption', () => { + it('keeps every CTA disabled (checkout is a later slice)', async () => { renderSection() for (const name of ['Choose Standard', 'Choose Creator', 'Choose Pro']) { expect(screen.getByRole('button', { name })).toBeDisabled() } - expect(screen.queryByText('Save 20%')).toBeNull() - expect(screen.queryByText(/Checkout happens right here/)).toBeNull() + await userEvent.click(screen.getByRole('button', { name: 'Teams' })) + expect( + screen.getByRole('button', { name: 'Subscribe to Team Yearly' }) + ).toBeDisabled() + expect(screen.getByRole('button', { name: 'Contact us' })).toBeDisabled() }) }) diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue index 48872532b02..6b5243ef4a3 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue @@ -9,7 +9,16 @@

-
+
+ + + {{ t('settingsPlans.personal') }} + + + {{ t('settingsPlans.teams') }} + + +
@@ -18,7 +27,21 @@
-
+ +
+ + {{ t('g.loading') }} +
+ + +
+ + +
+ + + From 9be5125512e7db70c6c324cdfa148734b2871c17 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Mon, 24 Aug 2026 22:47:48 +0530 Subject: [PATCH 07/14] refactor(billing): drop the redundant team-stop re-snap and cover the fallback The late-arrival re-snap watch was redundant: when the seeded slider value matches no live stop, both selectedTeamStop and CreditSlider's own selectedIndex already fall back to the default stop, so the display stays correct without it. Remove the watch and add a test that swaps the API stops for a disjoint set post-mount and asserts the default-stop credits render, covering that fallback. Also remove an orphaned comment left in UnifiedPricingTable when the shared ratio moved to tierPricing. --- .../components/UnifiedPricingTable.vue | 2 - .../settings/SettingsPlansSection.test.ts | 45 +++++++++++++++++++ .../dialogs/settings/SettingsPlansSection.vue | 12 ++--- 3 files changed, 49 insertions(+), 10 deletions(-) diff --git a/src/platform/workspace/components/UnifiedPricingTable.vue b/src/platform/workspace/components/UnifiedPricingTable.vue index 41f928653ac..778c401eca8 100644 --- a/src/platform/workspace/components/UnifiedPricingTable.vue +++ b/src/platform/workspace/components/UnifiedPricingTable.vue @@ -480,8 +480,6 @@ const QUESTIONS_URL = 'https://portal.usepylon.com/comfy-org/forms/question' const ENTERPRISE_URL = 'https://www.comfy.org/enterprise' const PRICING_URL = 'https://www.comfy.org/pricing' -// Videos-per-credit ratio (shared presentation constant). - interface BillingCycleOption { label: string value: BillingCycle diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts index 167c9ea320e..365fd1cc324 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts @@ -185,4 +185,49 @@ describe('SettingsPlansSection — API is the source of truth', () => { ).toBeDisabled() expect(screen.getByRole('button', { name: 'Contact us' })).toBeDisabled() }) + + it('shows the default stop credits when live stops replace the seeded set', async () => { + // Seed with one breakpoint set, then swap to a disjoint set: the previously + // seeded USD matches no new stop, so the display falls back to the API + // default stop (no stale/blank credits). + const { rerender } = renderSection({ + teamCreditStops: { + default_stop_index: 0, + stops: [ + { + id: 'team_200', + credits: 42_200, + monthly: { list_price_cents: 20_000, price_cents: 20_000 }, + yearly: { list_price_cents: 20_000, price_cents: 18_000 } + } + ] + } + }) + await userEvent.click(screen.getByRole('button', { name: 'Teams' })) + expect(screen.getByText('42,200')).toBeTruthy() + + await rerender({ + catalogPlans: CATALOG, + teamCreditStops: { + default_stop_index: 1, + stops: [ + { + id: 'team_400', + credits: 84_400, + monthly: { list_price_cents: 40_000, price_cents: 40_000 }, + yearly: { list_price_cents: 40_000, price_cents: 36_000 } + }, + { + id: 'team_1200', + credits: 253_200, + monthly: { list_price_cents: 120_000, price_cents: 114_000 }, + yearly: { list_price_cents: 120_000, price_cents: 108_000 } + } + ] + } + }) + + expect(await screen.findByText('253,200')).toBeTruthy() + expect(screen.queryByText('42,200')).toBeNull() + }) }) diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue index 6b5243ef4a3..1544ffa1d48 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue @@ -253,7 +253,7 @@ diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts index 1db4b44d493..f7cbea7ea48 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts @@ -74,6 +74,7 @@ function renderSection( catalogPlans?: Plan[] teamCreditStops?: TeamCreditStops | null isLoading?: boolean + error?: string | null } = {} ) { return render(SettingsPlansSection, { @@ -138,27 +139,32 @@ describe('SettingsPlansSection — API is the source of truth', () => { expect(screen.queryByText('189,900')).toBeNull() }) - it('shows the unavailable state for personal when the catalog is empty', () => { + it('shows the unavailable state and no prices when the personal catalog is empty', () => { renderSection({ catalogPlans: [], teamCreditStops: null }) - expect(screen.getByText("We couldn't load your plan details.")).toBeTruthy() + expect( + screen.getByText('No plans are available right now. Check back soon.') + ).toBeTruthy() expect(screen.queryByText(/\$\d+ Billed yearly/)).toBeNull() expect(screen.queryByText('50,400')).toBeNull() }) - it('shows the unavailable state for teams when stops are absent', async () => { + it('shows the unavailable state and no constant stop when team stops are absent', async () => { renderSection({ teamCreditStops: null }) await userEvent.click(screen.getByRole('button', { name: 'Teams' })) - expect(screen.getByText("We couldn't load your plan details.")).toBeTruthy() + expect( + screen.getByText('No plans are available right now. Check back soon.') + ).toBeTruthy() // No constant-seeded slider stop. expect(screen.queryByText('147,700')).toBeNull() }) - it('emits retry from the unavailable state', async () => { + it('emits retry from the error state', async () => { const { emitted } = renderSection({ catalogPlans: [], - teamCreditStops: null + teamCreditStops: null, + error: 'network down' }) await userEvent.click(screen.getByRole('button', { name: 'Try again' })) @@ -236,4 +242,46 @@ describe('SettingsPlansSection — API is the source of truth', () => { expect(await screen.findByText('253,200')).toBeTruthy() expect(screen.queryByText('42,200')).toBeNull() }) + + it('shows the empty-state copy (no retry) when the catalog loaded but is empty', () => { + renderSection({ catalogPlans: [], teamCreditStops: null, error: null }) + + expect( + screen.getByText('No plans are available right now. Check back soon.') + ).toBeTruthy() + // The empty state must NOT tell the user to retry a load that succeeded. + expect(screen.queryByText("We couldn't load your plan details.")).toBeNull() + expect(screen.queryByRole('button', { name: 'Try again' })).toBeNull() + }) + + it('shows the error copy and a working retry when the load failed', async () => { + const { emitted } = renderSection({ + catalogPlans: [], + teamCreditStops: null, + error: 'network down' + }) + + expect(screen.getByText("We couldn't load your plan details.")).toBeTruthy() + expect( + screen.queryByText('No plans are available right now. Check back soon.') + ).toBeNull() + await userEvent.click(screen.getByRole('button', { name: 'Try again' })) + expect(emitted().retry).toBeTruthy() + }) + + it('keeps the cards visible during a refetch instead of flashing the spinner', async () => { + const { rerender } = renderSection() + expect(screen.getByText('$20')).toBeTruthy() + + // Parent flips isLoading true on a refetch while cards are already shown. + await rerender({ + catalogPlans: CATALOG, + teamCreditStops: TEAM_STOPS, + isLoading: true + }) + + // Cards stay; no full-section spinner replacement. + expect(screen.getByText('$20')).toBeTruthy() + expect(screen.queryByText('Loading')).toBeNull() + }) }) diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue index 340a2640306..4e6c3dd61f2 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue @@ -33,7 +33,7 @@
@@ -131,7 +131,11 @@
- +
@@ -232,7 +236,11 @@ - +
() const emit = defineEmits<{ retry: [] }>() +// A load failure is retryable ('error'); a catalog that loaded with no plans is +// a successful empty result ('empty', no retry). +const unavailableVariant = computed<'empty' | 'error'>(() => + error ? 'error' : 'empty' +) + const { t, n } = useI18n() const audience = ref<'personal' | 'teams'>('personal') From 7456e147aacdc06420e2eabd9ef4ffa8044f4db3 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Tue, 25 Aug 2026 22:39:02 +0530 Subject: [PATCH 10/14] test(billing): drop comments that restate the hardening test titles --- .../components/dialogs/settings/SettingsPlansSection.test.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts index f7cbea7ea48..30826c72e8b 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts @@ -249,7 +249,6 @@ describe('SettingsPlansSection — API is the source of truth', () => { expect( screen.getByText('No plans are available right now. Check back soon.') ).toBeTruthy() - // The empty state must NOT tell the user to retry a load that succeeded. expect(screen.queryByText("We couldn't load your plan details.")).toBeNull() expect(screen.queryByRole('button', { name: 'Try again' })).toBeNull() }) @@ -273,14 +272,12 @@ describe('SettingsPlansSection — API is the source of truth', () => { const { rerender } = renderSection() expect(screen.getByText('$20')).toBeTruthy() - // Parent flips isLoading true on a refetch while cards are already shown. await rerender({ catalogPlans: CATALOG, teamCreditStops: TEAM_STOPS, isLoading: true }) - // Cards stay; no full-section spinner replacement. expect(screen.getByText('$20')).toBeTruthy() expect(screen.queryByText('Loading')).toBeNull() }) From 2fa21354c98f0aa402edb16e14ff4c673da82e38 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 26 Aug 2026 15:46:49 +0530 Subject: [PATCH 11/14] fix(billing): drive the local plans state from the workspace bootstrap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The panel fetched the catalog through useBillingContext but read plans/isLoading/error from the useBillingPlans singleton. Off-cloud, shouldUseUnifiedPricing is `isCloud && ...` so it is false, and before the workspace hydrates useBillingRouting resolves type to 'legacy' — so the fetch landed on useLegacyBilling.fetchPlans(), an empty function that writes neither state nor error. The singleton therefore stayed pristine and the section computed 'empty': a slow bootstrap showed "No plans are available" instead of a spinner, and a failed one (/api/workspaces 500) showed it permanently, with no retry and zero catalog requests ever attempted. The catalog is simply unreachable off-cloud until the workspace exists, so the bootstrap is a precondition of it and has to drive this section. Rather than move fetch/loading/error into useBillingContext — which would change the shared adapter contract that cloud also depends on — the panel now reads teamWorkspaceStore.initState/error alongside the singleton and folds the two into the isLoading/error props the section already takes. Not-ready renders the spinner; a failed bootstrap renders the error variant whose Retry re-runs workspaceStore.initialize(), after which the billing context's own workspace watch initializes billing and fetches the catalog. The empty and fetch-failure paths are unchanged. The old wiring test mocked both composables and had its mock write the singleton it then asserted, so it could not see any of this. It is replaced by a routing suite that runs the real useBillingContext/useBillingRouting/ useBillingPlans (and the real legacy adapter, whose no-op is the mechanism) against a mocked workspaceApi and workspace store. Its two bootstrap cases fail on the pre-fix panel. --- .../PlanCreditsPanelContent.routing.test.ts | 254 ++++++++++++++++++ .../settings/PlanCreditsPanelContent.test.ts | 132 +-------- .../settings/PlanCreditsPanelContent.vue | 39 ++- 3 files changed, 289 insertions(+), 136 deletions(-) create mode 100644 src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.routing.test.ts diff --git a/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.routing.test.ts b/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.routing.test.ts new file mode 100644 index 00000000000..dfe7a61d836 --- /dev/null +++ b/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.routing.test.ts @@ -0,0 +1,254 @@ +import userEvent from '@testing-library/user-event' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createI18n } from 'vue-i18n' + +import { ref } from 'vue' + +import { render, screen, waitFor } from '@testing-library/vue' + +import enMessages from '@/locales/en/main.json' +import { useBillingPlans } from '@/platform/cloud/subscription/composables/useBillingPlans' +import type { + BillingPlansResponse, + Plan +} from '@/platform/workspace/api/workspaceApi' + +import PlanCreditsPanelContent from './PlanCreditsPanelContent.vue' + +// The panel's real defect was a routing one: it fetched through +// useBillingContext (which lands on the legacy no-op before the workspace +// hydrates) while reading state from the useBillingPlans singleton that only +// the workspace adapter writes. These tests therefore run the REAL +// useBillingContext / useBillingRouting / useBillingPlans and mock only what +// this repo owns at its edges: the HTTP client and the workspace store's state. + +type InitState = 'uninitialized' | 'loading' | 'ready' | 'error' + +const workspace = vi.hoisted(() => ({ + initialize: vi.fn(async () => {}) +})) + +// Reactive so a bootstrap that resolves mid-test re-drives the panel exactly as +// the real store would. +const state = { + initState: ref('ready'), + error: ref(null), + active: ref<{ id: string; type: string } | null>({ + id: 'ws-1', + type: 'personal' + }) +} + +const api = vi.hoisted(() => ({ + getBillingPlans: vi.fn(), + getBillingStatus: vi.fn(async () => ({ + is_active: false, + has_funds: true, + team_credit_stop: null + })), + getBillingBalance: vi.fn(async () => ({ amount_micros: 0 })) +})) + +vi.mock('@/platform/distribution/types', () => ({ isCloud: false })) + +// Siblings of the plans section; irrelevant here and each drags in the app graph. +vi.mock('@/components/dialog/content/setting/CreditsPanel.vue', () => ({ + default: { template: '
' } +})) +vi.mock('@/components/dialog/content/setting/UsageLogsTable.vue', () => ({ + default: { template: '
', methods: { refresh: () => {} } } +})) +vi.mock( + '@/platform/cloud/subscription/components/SubscriptionFooterLinks.vue', + () => ({ default: { template: '
' } }) +) +vi.mock( + '@/platform/workspace/components/SubscriptionPanelContentWorkspace.vue', + () => ({ default: { template: '
' } }) +) + +// The legacy adapter itself stays REAL — its no-op fetchPlans is the mechanism +// under test — but its Firebase-backed collaborators are stubbed out. +vi.mock('@/platform/cloud/subscription/composables/useSubscription', () => ({ + useSubscription: () => ({ + canAccessSubscriptionFeatures: ref(false), + subscriptionTier: ref(null), + subscriptionDuration: ref(null), + subscriptionStatus: ref(null), + isCancelled: ref(false), + fetchStatus: vi.fn(async () => {}), + manageSubscription: vi.fn(), + subscribe: vi.fn(), + subscribeDirect: vi.fn(), + showSubscriptionDialog: vi.fn() + }) +})) +vi.mock('@/stores/authStore', () => ({ + useAuthStore: () => ({ isLoggedIn: ref(true), balance: ref(null) }) +})) +vi.mock('@/composables/auth/useAuthActions', () => ({ + useAuthActions: () => ({ purchaseCredits: vi.fn(), fetchBalance: vi.fn() }) +})) + +vi.mock('@/platform/workspace/api/workspaceApi', () => ({ + workspaceApi: api, + WorkspaceApiError: class extends Error {} +})) + +vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({ + useTeamWorkspaceStore: () => ({ + get initState() { + return state.initState.value + }, + get error() { + return state.error.value + }, + get activeWorkspace() { + return state.active.value + }, + get activeWorkspaceBillingRail() { + return undefined + }, + get isPersonalWorkspace() { + return true + }, + initialize: workspace.initialize, + updateActiveWorkspace: vi.fn(), + setWorkspaceBillingRail: vi.fn() + }) +})) + +function makePlan( + tier: Plan['tier'], + duration: Plan['duration'], + price_cents: number, + credits_cents: number +): Plan { + return { + slug: `${tier.toLowerCase()}-${duration.toLowerCase()}`, + tier, + duration, + price_cents, + credits_cents, + max_seats: 1, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: price_cents, + total_credits_cents: credits_cents + } + } +} + +const CATALOG: BillingPlansResponse = { + plans: [makePlan('STANDARD', 'ANNUAL', 24000, 50400)] +} + +function renderPanel() { + const i18n = createI18n({ + legacy: false, + locale: 'en', + messages: { en: enMessages } + }) + return render(PlanCreditsPanelContent, { global: { plugins: [i18n] } }) +} + +const EMPTY_COPY = 'No plans are available right now. Check back soon.' +const ERROR_COPY = "We couldn't load your plan details." + +// useBillingPlans is a module singleton; reset the state each test rather than +// resetting the module graph (a fresh graph deadlocks on the workspace). +beforeEach(() => { + const billingPlans = useBillingPlans() + billingPlans.plans.value = [] + billingPlans.teamCreditStops.value = null + billingPlans.currentPlanSlug.value = null + billingPlans.isLoading.value = false + billingPlans.error.value = null + + state.initState.value = 'ready' + state.error.value = null + state.active.value = { id: 'ws-1', type: 'personal' } + workspace.initialize.mockReset() + workspace.initialize.mockImplementation(async () => {}) + api.getBillingPlans.mockReset() + api.getBillingPlans.mockResolvedValue(CATALOG) +}) + +describe('PlanCreditsPanelContent — workspace bootstrap drives the plans state', () => { + it('shows the loading state until the workspace hydrates, then the catalog', async () => { + state.initState.value = 'loading' + state.active.value = null + + renderPanel() + + expect(await screen.findByText('Loading')).toBeTruthy() + expect(screen.queryAllByText(EMPTY_COPY)).toHaveLength(0) + expect(api.getBillingPlans).not.toHaveBeenCalled() + + state.initState.value = 'ready' + state.active.value = { id: 'ws-1', type: 'personal' } + + expect(await screen.findByText('$20')).toBeTruthy() + expect(screen.getByText('50,400')).toBeTruthy() + expect(screen.queryByText('Loading')).toBeNull() + expect(api.getBillingPlans).toHaveBeenCalledOnce() + }) + + it('shows a retryable error when the workspace bootstrap failed, and recovers', async () => { + state.initState.value = 'error' + state.error.value = new Error('workspaces unavailable') + state.active.value = null + + renderPanel() + + expect((await screen.findAllByText(ERROR_COPY)).length).toBeGreaterThan(0) + expect(screen.queryAllByText(EMPTY_COPY)).toHaveLength(0) + + // Retry re-runs the workspace bootstrap; the billing context's workspace + // watch is what then fetches the catalog. + workspace.initialize.mockImplementation(async () => { + state.initState.value = 'ready' + state.active.value = { id: 'ws-1', type: 'personal' } + }) + + await userEvent.click( + screen.getAllByRole('button', { name: 'Try again' })[0] + ) + + expect(workspace.initialize).toHaveBeenCalledOnce() + await waitFor(() => + expect(screen.getAllByText('$20').length).toBeGreaterThan(0) + ) + }) + + it('shows the empty state without a retry for a successful but empty catalog', async () => { + api.getBillingPlans.mockResolvedValue({ plans: [] }) + + renderPanel() + + expect((await screen.findAllByText(EMPTY_COPY)).length).toBeGreaterThan(0) + expect(screen.queryByText(ERROR_COPY)).toBeNull() + expect(screen.queryByRole('button', { name: 'Try again' })).toBeNull() + }) + + it('shows a retryable error when the catalog fetch fails, and recovers', async () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + api.getBillingPlans.mockRejectedValueOnce(new Error('plans exploded')) + + renderPanel() + + expect((await screen.findAllByText(ERROR_COPY)).length).toBeGreaterThan(0) + expect(screen.queryAllByText(EMPTY_COPY)).toHaveLength(0) + + await userEvent.click( + screen.getAllByRole('button', { name: 'Try again' })[0] + ) + + await waitFor(() => + expect(screen.getAllByText('$20').length).toBeGreaterThan(0) + ) + // Retry re-fetches the catalog rather than re-running the bootstrap. + expect(workspace.initialize).not.toHaveBeenCalled() + }) +}) diff --git a/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.test.ts b/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.test.ts index c7ad1b57843..ae8be20e3da 100644 --- a/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.test.ts +++ b/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.test.ts @@ -1,5 +1,5 @@ import userEvent from '@testing-library/user-event' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' import { ref } from 'vue' @@ -7,7 +7,6 @@ import { ref } from 'vue' import { render, screen, waitFor } from '@testing-library/vue' import enMessages from '@/locales/en/main.json' -import type { Plan } from '@/platform/workspace/api/workspaceApi' import PlanCreditsPanelContent from './PlanCreditsPanelContent.vue' @@ -155,132 +154,3 @@ describe('PlanCreditsPanelContent', () => { ) }) }) - -describe('PlanCreditsPanelContent — the fetch drives the rendered offer', () => { - function makePlan( - tier: Plan['tier'], - duration: Plan['duration'], - price_cents: number, - credits_cents: number - ): Plan { - return { - slug: `${tier.toLowerCase()}-${duration.toLowerCase()}`, - tier, - duration, - price_cents, - credits_cents, - max_seats: 1, - availability: { available: true }, - seat_summary: { - seat_count: 1, - total_cost_cents: price_cents, - total_credits_cents: credits_cents - } - } - } - - // Section rendered UNSTUBBED so the assertion is on real rendered values — - // a stubbed section would pass with the wire cut (the round-1 failure). - const wireStubs = { - SubscriptionPanelContentWorkspace: { - template: '
' - }, - CreditsPanel: { - props: ['embedded'], - template: '
' - }, - SubscriptionFooterLinks: { - template: '
' - }, - UsageLogsTable: { - template: '
', - methods: { refresh: refreshSpy } - } - } - - function renderWired({ cloud = false } = {}) { - mockDistribution.cloud = cloud - const i18n = createI18n({ - legacy: false, - locale: 'en', - messages: { en: enMessages } - }) - return render(PlanCreditsPanelContent, { - global: { plugins: [i18n], stubs: wireStubs } - }) - } - - beforeEach(() => { - billingState.plans.value = [] - billingState.teamCreditStops.value = null - billingState.isLoading.value = false - billingState.error.value = null - billing.fetchPlans.mockReset() - // fetchPlans populates the singleton the section reads — the real wire. - billing.fetchPlans.mockImplementation(async () => { - billingState.plans.value = [makePlan('STANDARD', 'ANNUAL', 24000, 50400)] - }) - }) - - it('fetches on mount off-cloud and renders the fetched catalog', async () => { - renderWired({ cloud: false }) - - expect(billing.fetchPlans).toHaveBeenCalledTimes(1) - // The fetched STANDARD/ANNUAL row: $20/mo, 50,400 credits — from the fetch, - // not a constant. - expect(await screen.findByText('$20')).toBeTruthy() - expect(screen.getByText('50,400')).toBeTruthy() - }) - - it('renders different numbers when the fetch returns different data', async () => { - billing.fetchPlans.mockImplementation(async () => { - billingState.plans.value = [makePlan('STANDARD', 'ANNUAL', 30000, 60000)] - }) - renderWired({ cloud: false }) - - expect(await screen.findByText('$25')).toBeTruthy() - expect(screen.getByText('60,000')).toBeTruthy() - expect(screen.queryByText('$20')).toBeNull() - }) - - it('renders the empty state when the fetch yields no catalog', async () => { - billing.fetchPlans.mockImplementation(async () => { - billingState.plans.value = [] - }) - renderWired({ cloud: false }) - - expect( - await screen.findByText( - 'No plans are available right now. Check back soon.' - ) - ).toBeTruthy() - expect(screen.queryByText("We couldn't load your plan details.")).toBeNull() - expect(screen.queryByText(/\$\d+ Billed yearly/)).toBeNull() - }) - - it('renders the error state when the fetch fails', async () => { - billing.fetchPlans.mockImplementation(async () => { - billingState.plans.value = [] - billingState.error.value = 'network down' - }) - renderWired({ cloud: false }) - - expect( - await screen.findByText("We couldn't load your plan details.") - ).toBeTruthy() - expect(screen.getByRole('button', { name: 'Try again' })).toBeTruthy() - expect( - screen.queryByText('No plans are available right now. Check back soon.') - ).toBeNull() - }) - - it('does not fetch or mount the section on cloud', () => { - renderWired({ cloud: true }) - - expect(billing.fetchPlans).not.toHaveBeenCalled() - expect(screen.queryByText('$20')).toBeNull() - expect( - screen.getByRole('region', { name: 'Plan and credits overview' }) - ).toBeTruthy() - }) -}) diff --git a/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.vue b/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.vue index b2d9abb55e0..56b7c6cf89f 100644 --- a/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.vue +++ b/src/platform/workspace/components/dialogs/settings/PlanCreditsPanelContent.vue @@ -23,9 +23,9 @@ !isCloud && workspaceStore.initState !== 'ready' +) +const workspaceError = computed(() => + !isCloud && workspaceStore.initState === 'error' + ? (workspaceStore.error?.message ?? t('subscription.planLoadError')) + : null +) + +const isCatalogLoading = computed( + () => + isLoadingPlans.value || (isWorkspacePending.value && !workspaceError.value) +) +const catalogError = computed(() => workspaceError.value ?? plansError.value) + +function retry() { + if (workspaceError.value) { + // The context's workspace watch initializes billing and fetches the + // catalog once a workspace appears. A repeat failure is already reported + // by the store and re-renders this same error state. + void workspaceStore.initialize().catch(() => undefined) + return + } void fetchPlans() } // Off-cloud only: on cloud the local plans section never mounts, so no extra // local fetch fires. Deduped across re-mounts by useBillingPlans.fetchPromise. onMounted(() => { - if (!isCloud) loadPlans() + if (!isCloud) void fetchPlans() }) function openFullActivity() { From fbeebc9df7cba3d38f5af5fc8536887db9e87d98 Mon Sep 17 00:00:00 2001 From: Maanil Verma Date: Wed, 26 Aug 2026 15:47:46 +0530 Subject: [PATCH 12/14] fix(billing): surface a failed plans refetch over cached cards useBillingPlans keeps the previous plans alongside a fresh error so a failed refetch does not flash the section to empty. That is the right call, but the unavailable block only renders when there are no cards, so the failure was invisible: stale prices with no indication they were stale and no way to retry. Keep the cards and add a banner that states it and offers the retry. Also drop the dead settingsPlans.checkoutCaption key and point the enterprise CTA at the existing subscription.contactUs rather than its duplicate. --- src/locales/en/main.json | 5 ++- .../settings/SettingsPlansSection.test.ts | 16 ++++++++++ .../dialogs/settings/SettingsPlansSection.vue | 31 ++++++++++++++++++- 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 4b7fdb6bb32..f278294f8bf 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2672,9 +2672,7 @@ "creditsPerMonth": "{credits} credits per month", "comingSharedWorkflows": "Shared workflows & assets", "comingProjects": "Projects", - "enterpriseCopy": "Need more members? Looking for more flexibility or custom features?", - "contactUs": "Contact us", - "checkoutCaption": "Checkout happens right here: payment details handled securely by Stripe. Prefer no plan? Keep topping up, anytime." + "enterpriseCopy": "Need more members? Looking for more flexibility or custom features?" }, "credits": { "activity": "Activity", @@ -2891,6 +2889,7 @@ "whatsIncluded": "What's included:", "planLoadError": "We couldn't load your plan details.", "planLoadErrorRetry": "Try again", + "planLoadErrorStale": "We couldn't refresh your plan details. These prices may be out of date.", "teamPlanName": "Team", "teamPlanIncludes": "Your plan includes everything in {plan}, plus:", "inactiveTeamTitle": "Inactive team subscription", diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts index cb9760acaa1..99e4c1849a2 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.test.ts @@ -203,6 +203,22 @@ describe('SettingsPlansSection — API is the source of truth', () => { expect(emitted().retry).toBeTruthy() }) + it('surfaces a retryable failure over cached cards on a refetch error', async () => { + const { emitted } = renderSection({ error: 'network down' }) + + // The cached catalog stays on screen rather than flashing to empty... + expect(screen.getByText('$20')).toBeTruthy() + // ...but the failure is stated and retryable, not silent. + expect( + screen.getByText( + "We couldn't refresh your plan details. These prices may be out of date." + ) + ).toBeTruthy() + + await userEvent.click(screen.getByRole('button', { name: 'Try again' })) + expect(emitted().retry).toBeTruthy() + }) + it('shows a spinner and no prices while loading', () => { renderSection({ isLoading: true, catalogPlans: [], teamCreditStops: null }) diff --git a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue index e436ad41e96..70d824bfb17 100644 --- a/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue +++ b/src/platform/workspace/components/dialogs/settings/SettingsPlansSection.vue @@ -30,6 +30,28 @@
+ +