diff --git a/src/platform/cloud/subscription/composables/useSubscription.test.ts b/src/platform/cloud/subscription/composables/useSubscription.test.ts index 885f466be9d..f49d29b9ef8 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.test.ts @@ -6,6 +6,8 @@ import { computed, effectScope } from 'vue' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useCurrentUser } from '@/composables/auth/useCurrentUser' +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' +import type { BillingReadRail } from '@/platform/workspace/composables/useBillingReadRail' import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription' import { PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY } from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' @@ -135,11 +137,77 @@ vi.mock( vi.mock(import('@/platform/workspace/api/workspaceApi'), () => ({ workspaceApi: { getBillingStatus: mockGetBillingStatus - } + }, + // What a failed rail read throws; only its message reaches the wrapper. + WorkspaceApiError: class extends Error {} +})) + +/** Null is the legacy client; a rail is what the SDK store would hand back. */ +const railState = vi.hoisted(() => ({ + rail: null as Pick | null })) +vi.mock( + import('@/platform/workspace/composables/useBillingReadRail'), + () => ({ useBillingReadRail: () => railState.rail }) +) vi.mock(import('@/services/dialogService')) +const mockReadStatus = vi.fn() + +const buildStatus = ( + overrides: Partial = {} +): BillingStatusResponse => ({ + is_active: true, + has_funds: true, + max_seats: 1, + occupied_seats: 1, + scheduled_change: null, + team_credit_stop: null, + ...overrides +}) + +/** + * The two clients the status read can go through, so the rows below pin one + * behaviour on both rather than one path's behaviour twice. + */ +const statusReadPaths = [ + { + reader: 'the workspace client', + select: () => { + railState.rail = null + }, + resolve: (status: BillingStatusResponse) => { + mockGetBillingStatus.mockResolvedValue(status) + }, + fail: () => { + mockGetBillingStatus.mockRejectedValue( + new Error('Subscription not found') + ) + }, + failure: 'Subscription not found', + idleReader: () => mockReadStatus + }, + { + reader: 'the SDK reader', + select: () => { + railState.rail = { readStatus: mockReadStatus } + }, + resolve: (status: BillingStatusResponse) => { + mockReadStatus.mockResolvedValue({ status: 'ok', value: status }) + }, + fail: () => { + mockReadStatus.mockResolvedValue({ + status: 'error', + code: 'ACCESS_DENIED', + httpStatus: 403 + }) + }, + failure: 'ACCESS_DENIED', + idleReader: () => mockGetBillingStatus + } +] + // Mock fetch global.fetch = vi.fn() @@ -171,6 +239,7 @@ describe('useSubscription', () => { setDistribution('cloud') mockLocalStorage.__reset() + railState.rail = null Object.assign(useAuthStore(), { userId: 'user-123' }) mockIsCloud.value = true Object.assign(useAuthStore(), { isInitialized: true }) @@ -291,50 +360,60 @@ describe('useSubscription', () => { }) describe('fetchStatus', () => { - it('should fetch subscription status successfully', async () => { - const mockStatus = { - is_active: true, - has_funds: true, - renewal_date: '2025-11-16', - team_credit_stop: null - } + it.for(statusReadPaths)( + 'publishes a status read through $reader and updates the workspace billing rail', + async (path) => { + const status = buildStatus({ + renewal_date: '2025-11-16', + billing_rail: 'stripe' + }) + path.select() + path.resolve(status) - mockGetBillingStatus.mockResolvedValue(mockStatus) + useCurrentUser().isLoggedIn = computed(() => true) + const { subscriptionStatus, fetchStatus } = useSubscriptionWithScope() - useCurrentUser().isLoggedIn = computed(() => true) - const { fetchStatus } = useSubscriptionWithScope() + await fetchStatus() - await fetchStatus() + expect(subscriptionStatus.value).toEqual(status) + expect(mockSetWorkspaceBillingRail).toHaveBeenCalledWith( + 'workspace-123', + 'stripe' + ) + // One transport per read: the rail a read is on is the only client it + // asks, or the panels read one thing and the rail settled another. + expect(path.idleReader()).not.toHaveBeenCalled() + } + ) - expect(mockGetBillingStatus).toHaveBeenCalledOnce() - }) + it.for(statusReadPaths)( + 'reports a failed read through $reader in the same message', + async (path) => { + path.select() + path.fail() - it('should handle fetch errors gracefully', async () => { - mockGetBillingStatus.mockRejectedValue( - new Error('Subscription not found') - ) + const { fetchStatus } = useSubscriptionWithScope() - const { fetchStatus } = useSubscriptionWithScope() + await expect(fetchStatus()).rejects.toThrow( + `Failed to fetch subscription status: ${path.failure}` + ) + } + ) - await expect(fetchStatus()).rejects.toThrow( - 'Failed to fetch subscription status: Subscription not found' - ) - }) + it('keeps the published status when a rail read is superseded', async () => { + const published = buildStatus({ renewal_date: '2025-11-16' }) + mockGetBillingStatus.mockResolvedValue(published) + const { subscriptionStatus, fetchStatus } = useSubscriptionWithScope() + await fetchStatus() - it('updates the active workspace billing rail from status', async () => { - mockGetBillingStatus.mockResolvedValue({ - is_active: true, - has_funds: true, - billing_rail: 'stripe' + railState.rail = { readStatus: mockReadStatus } + mockReadStatus.mockResolvedValue({ + status: 'error', + code: 'SUPERSEDED' }) + await expect(fetchStatus()).resolves.toBeNull() - const { fetchStatus } = useSubscriptionWithScope() - await fetchStatus() - - expect(mockSetWorkspaceBillingRail).toHaveBeenCalledWith( - 'workspace-123', - 'stripe' - ) + expect(subscriptionStatus.value).toEqual(published) }) it('does not apply the previous account response after an identity switch', async () => { diff --git a/src/platform/cloud/subscription/composables/useSubscription.ts b/src/platform/cloud/subscription/composables/useSubscription.ts index 370f024fb76..d9dd2ba6ace 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.ts @@ -20,6 +20,8 @@ import type { } from '@/platform/telemetry/types' import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' import { workspaceApi } from '@/platform/workspace/api/workspaceApi' +import { readOnRail } from '@/platform/workspace/composables/readOnRail' +import { useBillingReadRail } from '@/platform/workspace/composables/useBillingReadRail' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { AuthStoreError, useAuthStore } from '@/stores/authStore' import { useDialogService } from '@/services/dialogService' @@ -380,15 +382,19 @@ function useSubscriptionInternal() { return fetchPromise } - async function performFetchSubscriptionStatus( - ownerId: string | null, - workspaceId: string | null - ): Promise { - if (!isCloud) return null - - let statusData: BillingStatusResponse + /** + * The status read on whichever rail is on, in the failure shape the legacy + * client threw in. The rail is taken before the read and held for it: a flag + * flip mid-read must not start on one client and publish through the other. + */ + async function readSubscriptionStatus(): Promise< + BillingStatusResponse | undefined + > { + const rail = useBillingReadRail() try { - statusData = await workspaceApi.getBillingStatus() + return rail + ? await readOnRail(rail.readStatus) + : await workspaceApi.getBillingStatus() } catch (error) { throw new AuthStoreError( t('toastMessages.failedToFetchSubscription', { @@ -396,6 +402,17 @@ function useSubscriptionInternal() { }) ) } + } + + async function performFetchSubscriptionStatus( + ownerId: string | null, + workspaceId: string | null + ): Promise { + if (!isCloud) return null + + const statusData = await readSubscriptionStatus() + // A superseded read publishes nothing: the scope moved on under it. + if (statusData === undefined) return null if ( (authStore.userId ?? null) !== ownerId || workspaceStore.activeWorkspaceId !== workspaceId