diff --git a/src/composables/billing/types.ts b/src/composables/billing/types.ts index f4ba5694f0d..accdf9c4cf3 100644 --- a/src/composables/billing/types.ts +++ b/src/composables/billing/types.ts @@ -103,6 +103,8 @@ export interface BalanceInfo { cloudCreditBalanceMicros?: number /** Server-suggested top-up that covers a negative balance; null otherwise. */ suggestedTopupAmountCents?: number | null + /** Served `low_balance`. Absent when the balance response omits it. */ + lowBalance?: boolean } /** Whether the billing portal opened, and why not when it did not. */ diff --git a/src/composables/useFeatureFlags.test.ts b/src/composables/useFeatureFlags.test.ts index 128024b4526..f6157643256 100644 --- a/src/composables/useFeatureFlags.test.ts +++ b/src/composables/useFeatureFlags.test.ts @@ -375,9 +375,12 @@ describe('useFeatureFlags', () => { }) describe.for([ - { flag: 'unifiedBillingSettingsEnabled' as const }, - { flag: 'autoTopUpEnabled' as const } - ])('$flag', ({ flag }) => { + { + flag: 'unifiedBillingSettingsEnabled' as const, + offCloudTrue: true + }, + { flag: 'autoTopUpEnabled' as const, offCloudTrue: false } + ])('$flag', ({ flag, offCloudTrue }) => { afterEach(() => { vi.mocked(distributionTypes).isCloud = false }) @@ -397,7 +400,25 @@ describe('useFeatureFlags', () => { expected: false }, { case: 'true on cloud', cloud: true, value: true, expected: true }, - { case: 'true off cloud', cloud: false, value: true, expected: false } + { + case: 'missing off cloud', + cloud: false, + value: undefined, + expected: false + }, + { case: 'false off cloud', cloud: false, value: false, expected: false }, + { + case: 'malformed off cloud', + cloud: false, + value: 'true', + expected: false + }, + { + case: 'true off cloud', + cloud: false, + value: true, + expected: offCloudTrue + } ])('is $expected when $case', ({ cloud, value, expected }) => { vi.mocked(distributionTypes).isCloud = cloud vi.mocked(api.getServerFeature).mockReturnValue(value) diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index 9edb0a7eb24..bc1565dcee4 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -307,8 +307,6 @@ export function useFeatureFlags() { return this.billingSdkSubscriptionEnabled && this.unifiedCloudAuthEnabled }, get unifiedBillingSettingsEnabled() { - if (!isCloud) return false - return resolveStrictBooleanFlag( ServerFeatureFlag.UNIFIED_BILLING_SETTINGS, remoteConfig.value.unified_billing_settings diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 53393b384bc..67f31b4b2af 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -3698,6 +3698,10 @@ "addCredits": "Add credits", "dismiss": "Dismiss" }, + "lowCredits": { + "title": "Credits are low", + "localBody": "You have {credits} credits left. Add credits to keep running Partner Nodes." + }, "ending": { "title": "Your Team plan ends on {date}", "body": "You won't be charged again. Members keep full access until then. Resume your plan to keep your team's shared credits.", diff --git a/src/platform/settings/composables/useSettingUI.test.ts b/src/platform/settings/composables/useSettingUI.test.ts index 823b40ab0ea..b0d88343b0b 100644 --- a/src/platform/settings/composables/useSettingUI.test.ts +++ b/src/platform/settings/composables/useSettingUI.test.ts @@ -252,7 +252,10 @@ describe('useSettingUI', () => { }) }) - it('shows only Plan & Credits in the local Workspace group', () => { + it('keeps Plan & Credits on local when unified billing settings is off', () => { + env.state.isCloud = false + vi.mocked(useFeatureFlags().flags).unifiedBillingSettingsEnabled = false + vi.mocked(useFeatureFlags().flags).partnerNodeGovernanceEnabled = true const { findPanelByKey, navGroups } = useSettingUI() const workspaceItems = navGroups.value .find((group) => group.title === 'Workspace') @@ -261,6 +264,25 @@ describe('useSettingUI', () => { expect(workspaceItems).toEqual([ { id: 'workspace', label: 'PlanCredits' } ]) + expect(findPanelByKey('workspace')?.props).toEqual({ + section: 'planCredits' + }) + expect(findPanelByKey('workspace-members')).toBeNull() + expect(findPanelByKey('workspace-allowlist')).toBeNull() + }) + + it('mounts the Billing tab on local when unified billing settings is on', () => { + env.state.isCloud = false + const flags = vi.mocked(useFeatureFlags().flags) + flags.unifiedBillingSettingsEnabled = true + flags.partnerNodeGovernanceEnabled = true + const { findPanelByKey, navGroups } = useSettingUI('workspace') + const workspaceItems = navGroups.value + .find((group) => group.title === 'Workspace') + ?.items.map(({ id, label }) => ({ id, label })) + + expect(workspaceItems).toEqual([{ id: 'workspace', label: 'Billing' }]) + expect(findPanelByKey('workspace')?.props).toBeUndefined() expect(findPanelByKey('workspace-members')).toBeNull() expect(findPanelByKey('workspace-allowlist')).toBeNull() }) diff --git a/src/platform/workspace/components/dialogs/settings/billing/BillingLocalCreditBanner.test.ts b/src/platform/workspace/components/dialogs/settings/billing/BillingLocalCreditBanner.test.ts new file mode 100644 index 00000000000..ea01784c1a5 --- /dev/null +++ b/src/platform/workspace/components/dialogs/settings/billing/BillingLocalCreditBanner.test.ts @@ -0,0 +1,302 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import userEvent from '@testing-library/user-event' +import { render, screen } from '@testing-library/vue' +import { describe, expect, it, vi } from 'vitest' +import { computed, nextTick, ref } from 'vue' +import { createI18n } from 'vue-i18n' + +import type { BalanceInfo, SubscriptionInfo } from '@/composables/billing/types' +import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useBillingDialogs } from '@/composables/billing/useBillingDialogs' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import enMessages from '@/locales/en/main.json' +import { canManageBillingFact } from '@/platform/workspace/composables/__mocks__/useBillingCapabilities' +import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' + +import BillingLocalCreditBanner from './BillingLocalCreditBanner.vue' + +const distribution = vi.hoisted(() => ({ isCloud: false })) + +vi.mock(import('@/platform/distribution/types'), () => ({ + get isCloud() { + return distribution.isCloud + } +})) +vi.mock(import('@/composables/billing/useBillingContext')) +vi.mock(import('@/composables/useFeatureFlags')) +vi.mock(import('@/composables/billing/useBillingDialogs')) +vi.mock(import('@/platform/workspace/composables/useBillingCapabilities')) +vi.mock(import('@/platform/workspace/composables/useWorkspaceUI')) + +const personalSubscription: SubscriptionInfo = { + isActive: true, + tier: 'PRO', + duration: 'MONTHLY', + planSlug: 'pro-monthly', + scheduledChange: null, + renewalDate: null, + endDate: null, + isCancelled: false, + hasFunds: true, + agentHasFunds: true +} + +function arrange(options: { + isCloud?: boolean + unified?: boolean + isTeamPlan?: boolean + subscription?: SubscriptionInfo + balance?: BalanceInfo | null + renewalDate?: string | null + canTopUp?: boolean + topUpDenial?: string + canManageBilling?: boolean + canManageSubscription?: boolean +}) { + distribution.isCloud = options.isCloud ?? false + vi.mocked(useFeatureFlags().flags).unifiedBillingSettingsEnabled = + options.unified ?? true + const subscription = ref(options.subscription ?? personalSubscription) + const balance = ref(options.balance ?? null) + vi.mocked(useBillingContext).mockReturnValue( + fromPartial({ + subscription: computed(() => subscription.value), + balance: computed(() => balance.value), + isTeamPlan: computed(() => options.isTeamPlan ?? false), + renewalDate: computed(() => options.renewalDate ?? null), + billingStatus: computed(() => 'paid' as const) + }) + ) + useBillingCapabilities().canTopUp = computed(() => options.canTopUp ?? true) + useBillingCapabilities().topUpDenial = computed(() => options.topUpDenial) + useBillingCapabilities().canManageBilling = canManageBillingFact( + options.canManageBilling ?? true + ) + const workspace = useWorkspaceUI() + const permissions = workspace.permissions.value + workspace.permissions = computed(() => ({ + ...permissions, + canManageSubscription: options.canManageSubscription ?? true + })) + + render(BillingLocalCreditBanner, { + global: { + plugins: [ + createI18n({ + legacy: false, + locale: 'en', + messages: { en: enMessages } + }) + ] + } + }) + + return { subscription, balance } +} + +describe('BillingLocalCreditBanner', () => { + it('renders nothing off the unified billing flag', () => { + arrange({ + unified: false, + subscription: { ...personalSubscription, hasFunds: false } + }) + + expect( + screen.queryByTestId('billing-local-credit-banner') + ).not.toBeInTheDocument() + }) + + it('renders nothing on cloud', () => { + arrange({ + isCloud: true, + subscription: { + ...personalSubscription, + hasFunds: false, + isCancelled: true, + endDate: '2026-08-01T00:00:00Z' + }, + balance: { amountMicros: 500, currency: 'usd', lowBalance: true } + }) + + expect( + screen.queryByTestId('billing-local-credit-banner') + ).not.toBeInTheDocument() + expect(screen.queryByText('Subscription paused')).not.toBeInTheDocument() + }) + + it.for([ + { + name: 'a personal owner', + isTeamPlan: false, + renewalDate: '2026-10-01T00:00:00Z', + body: "You've used all your credits. Add more credits or wait until credits refill on October 1, 2026.", + buttons: ['Dismiss', 'Add credits'] + }, + { + name: 'a team owner without a refill date', + isTeamPlan: true, + renewalDate: null, + body: 'Your team has used all its credits. Add more credits.', + buttons: ['Dismiss', 'Add credits'] + }, + { + name: 'a team member', + isTeamPlan: true, + canManageSubscription: false, + renewalDate: '2026-10-01T00:00:00Z', + body: 'Your team has used all its credits. Ask your workspace owner to add more credits or wait until credits refill on October 1, 2026.', + buttons: ['Dismiss'] + } + ])( + 'shows out of credits to $name', + async ({ + isTeamPlan, + renewalDate, + canManageSubscription, + body, + buttons + }) => { + arrange({ + isTeamPlan, + renewalDate, + canManageSubscription, + subscription: { ...personalSubscription, hasFunds: false } + }) + + const banner = screen.getByTestId('billing-local-credit-banner') + expect(banner).toHaveTextContent('Out of credits') + expect(banner).toHaveTextContent(body) + expect( + screen.getAllByRole('button').map((button) => button.textContent.trim()) + ).toEqual(buttons) + if (buttons.includes('Add credits')) { + await userEvent.click( + screen.getByRole('button', { name: 'Add credits' }) + ) + expect(useBillingDialogs().showTopUpCreditsDialog).toHaveBeenCalled() + } + } + ) + + it.for([ + { + name: 'a personal owner', + isTeamPlan: false, + canManageBilling: true, + body: "You've used all your credits. Update your payment method to add more.", + buttons: ['Dismiss', 'Update payment'] + }, + { + name: 'a team owner', + isTeamPlan: true, + canManageBilling: true, + body: 'Your team has used all its credits. Update your payment method to add more.', + buttons: ['Dismiss', 'Update payment'] + }, + { + name: 'a team member', + isTeamPlan: true, + canManageBilling: false, + body: 'Your team has used all its credits. Ask your workspace owner to update the payment method.', + buttons: ['Dismiss'] + } + ])( + 'uses the past-due out-of-credits copy for $name', + ({ isTeamPlan, canManageBilling, body, buttons }) => { + arrange({ + isTeamPlan, + canManageBilling, + topUpDenial: 'payment_past_due', + canTopUp: false, + subscription: { ...personalSubscription, hasFunds: false } + }) + + const banner = screen.getByTestId('billing-local-credit-banner') + expect(banner).toHaveTextContent(body) + expect( + screen.getAllByRole('button').map((button) => button.textContent.trim()) + ).toEqual(buttons) + expect(banner).not.toHaveTextContent('credits refill') + } + ) + + it('shows low credits from the served low_balance flag', () => { + arrange({ + balance: { amountMicros: 500, currency: 'usd', lowBalance: true } + }) + + const banner = screen.getByTestId('billing-local-credit-banner') + expect(banner).toHaveTextContent('Credits are low') + expect(banner).toHaveTextContent( + 'You have 1,055 credits left. Add credits to keep running Partner Nodes.' + ) + expect( + screen.getByRole('button', { name: 'Add credits' }) + ).toBeInTheDocument() + }) + + it('skips low credits when the balance response omits low_balance', () => { + arrange({ + balance: { amountMicros: 500, currency: 'usd' } + }) + + expect( + screen.queryByTestId('billing-local-credit-banner') + ).not.toBeInTheDocument() + }) + + it('keeps out of credits ahead of low credits and plan copy', () => { + arrange({ + subscription: { + ...personalSubscription, + hasFunds: false, + isCancelled: true, + endDate: '2026-08-01T00:00:00Z' + }, + balance: { amountMicros: 500, currency: 'usd', lowBalance: true } + }) + + const banner = screen.getByTestId('billing-local-credit-banner') + expect(banner).toHaveTextContent('Out of credits') + expect(banner).not.toHaveTextContent('Credits are low') + expect(banner).not.toHaveTextContent('Subscription paused') + expect(banner).not.toHaveTextContent('plan ends') + expect(banner).not.toHaveTextContent('plan ended') + }) + + it('shows nothing for a paused or ending plan that still has credits', () => { + arrange({ + subscription: { + ...personalSubscription, + hasFunds: true, + isCancelled: true, + endDate: '2026-08-01T00:00:00Z' + } + }) + + expect( + screen.queryByTestId('billing-local-credit-banner') + ).not.toBeInTheDocument() + }) + + it('brings out of credits back after credits return and run out again', async () => { + const { subscription } = arrange({ + subscription: { ...personalSubscription, hasFunds: false } + }) + + await userEvent.click(screen.getByRole('button', { name: 'Dismiss' })) + expect( + screen.queryByTestId('billing-local-credit-banner') + ).not.toBeInTheDocument() + + subscription.value = { ...personalSubscription, hasFunds: true } + await nextTick() + subscription.value = { ...personalSubscription, hasFunds: false } + await nextTick() + + expect(screen.getByTestId('billing-local-credit-banner')).toHaveTextContent( + 'Out of credits' + ) + }) +}) diff --git a/src/platform/workspace/components/dialogs/settings/billing/BillingLocalCreditBanner.vue b/src/platform/workspace/components/dialogs/settings/billing/BillingLocalCreditBanner.vue new file mode 100644 index 00000000000..91b3664fe57 --- /dev/null +++ b/src/platform/workspace/components/dialogs/settings/billing/BillingLocalCreditBanner.vue @@ -0,0 +1,230 @@ + + + diff --git a/src/platform/workspace/components/dialogs/settings/billing/BillingTab.test.ts b/src/platform/workspace/components/dialogs/settings/billing/BillingTab.test.ts index 85faccfcfd8..d9fab3c51a5 100644 --- a/src/platform/workspace/components/dialogs/settings/billing/BillingTab.test.ts +++ b/src/platform/workspace/components/dialogs/settings/billing/BillingTab.test.ts @@ -68,6 +68,7 @@ interface Scenario { autoTopUpFlag?: boolean canManageAutoTopUp?: boolean canTopUp?: boolean + topUpDenial?: string isPaused?: boolean } @@ -103,6 +104,7 @@ function arrange(scenario: Scenario = {}) { fromPartial({ slug: 'creator-yearly', tier: 'CREATOR' }) ]), balance: computed(() => scenario.balance ?? null), + renewalDate: computed(() => null), currentTeamCreditStop: computed(() => null), initialize, fetchStatus, @@ -130,7 +132,14 @@ function arrange(scenario: Scenario = {}) { scenario.canManageBilling ?? true ) ), + paymentRecoveryAvailable: computed(() => + receiveServerFact('payment_recovery_available', false) + ), + runDeniedPaymentPastDue: computed(() => + receiveServerFact('denied_reasons.can_run_workflows', false) + ), canTopUp: computed(() => scenario.canTopUp ?? true), + topUpDenial: computed(() => scenario.topUpDenial), canManageAutoTopUp: computed(() => receiveServerFact( 'can_manage_auto_top_up', @@ -224,6 +233,39 @@ describe('BillingTab', () => { }) }) + it('shows out of credits on the local Billing tab when unified billing settings is on', () => { + vi.mocked(useFeatureFlags().flags).unifiedBillingSettingsEnabled = true + arrange({ + subscription: { ...activeSubscription, hasFunds: false } + }) + + const banner = screen.getByTestId('billing-local-credit-banner') + expect(banner).toHaveTextContent('Out of credits') + expect(banner).toHaveTextContent( + "You've used all your credits. Add more credits." + ) + expect( + screen.queryByTestId('billing-paused-banner') + ).not.toBeInTheDocument() + expect(banner).not.toHaveTextContent('Subscription paused') + expect(banner).not.toHaveTextContent('plan ends') + }) + + it('hides local credit banners when unified billing settings is off', () => { + arrange({ + subscription: { ...activeSubscription, hasFunds: false }, + balance: { + amountMicros: 500, + currency: 'usd', + lowBalance: true + } + }) + + expect( + screen.queryByTestId('billing-local-credit-banner') + ).not.toBeInTheDocument() + }) + it('shows a skeleton and no plan row while billing loads', () => { arrange({ isInitialized: false }) diff --git a/src/platform/workspace/components/dialogs/settings/billing/BillingTab.vue b/src/platform/workspace/components/dialogs/settings/billing/BillingTab.vue index 3145dd23fe2..670e64c2c8c 100644 --- a/src/platform/workspace/components/dialogs/settings/billing/BillingTab.vue +++ b/src/platform/workspace/components/dialogs/settings/billing/BillingTab.vue @@ -4,6 +4,7 @@ +
) { + return deriveLocalCreditBanner({ ...open, ...overrides }) +} + +describe('deriveLocalCreditBanner', () => { + it('stays hidden when unified billing settings is off', () => { + expect( + derive({ + unifiedBillingSettingsEnabled: false, + hasFunds: false, + lowBalance: true + }) + ).toBeNull() + }) + + it.for([ + { lowBalance: undefined, kind: null }, + { lowBalance: false, kind: null }, + { lowBalance: true, kind: 'lowCredits' as const } + ])('reads low_balance $lowBalance as $kind', ({ lowBalance, kind }) => { + expect(derive({ lowBalance })).toBe(kind) + }) + + it('ranks out of credits above low credits', () => { + expect(derive({ hasFunds: false, lowBalance: true })).toBe('outOfCredits') + }) + + it('shows low credits once out of credits is dismissed', () => { + expect( + derive({ + hasFunds: false, + lowBalance: true, + outOfCreditsDismissed: true + }) + ).toBe('lowCredits') + }) + + it('hides a dismissed low-credits banner', () => { + expect(derive({ lowBalance: true, lowCreditsDismissed: true })).toBeNull() + }) +}) diff --git a/src/platform/workspace/composables/deriveLocalCreditBanner.ts b/src/platform/workspace/composables/deriveLocalCreditBanner.ts new file mode 100644 index 00000000000..bb50f22e595 --- /dev/null +++ b/src/platform/workspace/composables/deriveLocalCreditBanner.ts @@ -0,0 +1,22 @@ +export type LocalCreditBannerKind = 'outOfCredits' | 'lowCredits' + +export interface LocalCreditBannerInput { + unifiedBillingSettingsEnabled: boolean + hasFunds: boolean | null + lowBalance: boolean | undefined + outOfCreditsDismissed: boolean + lowCreditsDismissed: boolean +} + +export function deriveLocalCreditBanner( + input: LocalCreditBannerInput +): LocalCreditBannerKind | null { + if (!input.unifiedBillingSettingsEnabled) return null + if (input.hasFunds === false && !input.outOfCreditsDismissed) { + return 'outOfCredits' + } + if (input.lowBalance === true && !input.lowCreditsDismissed) { + return 'lowCredits' + } + return null +} diff --git a/src/platform/workspace/composables/useBillingBanner.test.ts b/src/platform/workspace/composables/useBillingBanner.test.ts index 473512e6f0f..41daea757a7 100644 --- a/src/platform/workspace/composables/useBillingBanner.test.ts +++ b/src/platform/workspace/composables/useBillingBanner.test.ts @@ -8,7 +8,12 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import type { BillingStatus } from '@/platform/workspace/api/workspaceApi' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' -vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) +const distribution = vi.hoisted(() => ({ isCloud: true })) +vi.mock(import('@/platform/distribution/types'), () => ({ + get isCloud() { + return distribution.isCloud + } +})) vi.mock(import('@/composables/useFeatureFlags')) @@ -65,6 +70,7 @@ describe('useBillingBanner', () => { } beforeEach(() => { + distribution.isCloud = true const workspaceUI = vi.mocked(useWorkspaceUI()) const defaultPermissions = workspaceUI.permissions.value workspaceUI.permissions = computed(() => ({ @@ -94,6 +100,20 @@ describe('useBillingBanner', () => { expect(kind.value).toBeNull() }) + it('stays quiet off cloud, including when unified billing settings is on', async () => { + distribution.isCloud = false + vi.mocked(useFeatureFlags().flags).unifiedBillingSettingsEnabled = true + const billing = setupBilling() + const { kind } = useBillingBanner() + + billing.tier.value = 'PRO' + billing.billingStatus.value = 'paused' + billing.subscription.value = { hasFunds: false } + await nextTick() + + expect(kind.value).toBeNull() + }) + it('re-shows the out-of-credits banner after a top-up and a later exhaustion', async () => { const billing = setupBilling() const { kind, dismiss } = useBillingBanner() diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index bba3f49396e..0fde75a8a2a 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -729,6 +729,33 @@ describe('useWorkspaceBilling', () => { }) }) + it.for([ + { served: true, expected: true }, + { served: false, expected: false } + ])( + 'passes low_balance $served through as received', + async ({ served, expected }) => { + mockWorkspaceApi.getBillingBalance.mockResolvedValue({ + ...positiveBalance, + low_balance: served + }) + + const billing = setupBilling() + await billing.fetchBalance() + + expect(billing.balance.value?.lowBalance).toBe(expected) + } + ) + + it('leaves low balance unset when the balance response omits it', async () => { + mockWorkspaceApi.getBillingBalance.mockResolvedValue(positiveBalance) + + const billing = setupBilling() + await billing.fetchBalance() + + expect(billing.balance.value?.lowBalance).toBeUndefined() + }) + it('passes the server-suggested top-up through as received', async () => { mockWorkspaceApi.getBillingBalance.mockResolvedValue({ ...positiveBalance, diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index 931c1a74f2e..ca60c90ee3d 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -258,7 +258,8 @@ export function useWorkspaceBilling(): WorkspaceBilling { effectiveBalanceAuthoritative: data.effective_balance_authoritative, prepaidBalanceMicros: data.prepaid_balance_micros ?? 0, cloudCreditBalanceMicros: data.cloud_credit_balance_micros ?? 0, - suggestedTopupAmountCents: data.suggested_topup_amount_cents + suggestedTopupAmountCents: data.suggested_topup_amount_cents, + lowBalance: data.low_balance } })