diff --git a/browser_tests/fixtures/ComfyPage.ts b/browser_tests/fixtures/ComfyPage.ts index 0bf9eab3c7c..37a6efc0ab4 100644 --- a/browser_tests/fixtures/ComfyPage.ts +++ b/browser_tests/fixtures/ComfyPage.ts @@ -6,6 +6,12 @@ import MCR from 'monocart-coverage-reports' import { COVERAGE_OUTPUT_DIR } from '@e2e/coverageConfig' import { TOURS, TOUR_SEEN_SETTING } from '@/platform/onboarding/onboardingTours' import { NodeBadgeMode } from '@/types/nodeSource' +import { + EMPTY_BILLING_BALANCE, + EMPTY_BILLING_PLANS, + LEGACY_PERSONAL_BILLING_STATUS +} from '@e2e/fixtures/data/cloudWorkspace' +import { ZERO_BALANCE } from '@e2e/fixtures/data/subscriptionFixtures' import { ComfyActionbar } from '@e2e/fixtures/components/Actionbar' import { ComfyTemplates } from '@e2e/fixtures/components/Templates' import { ComfyMouse } from '@e2e/fixtures/ComfyMouse' @@ -13,6 +19,7 @@ import { TestIds } from '@e2e/fixtures/selectors' import { comfyExpect } from '@e2e/fixtures/utils/customMatchers' import { assetPath } from '@e2e/fixtures/utils/paths' import { nextFrame, sleep } from '@e2e/fixtures/utils/timing' +import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' import { BottomPanel } from '@e2e/fixtures/components/BottomPanel' import { ComfyNodeSearchBox } from '@e2e/fixtures/components/ComfyNodeSearchBox' @@ -561,6 +568,23 @@ export const comfyPageFixture = base.extend<{ } if (testInfo.tags.includes('@cloud')) { + const context = page.context() + await context.route('**/api/auth/session', (route) => + route.fulfill({ status: 204 }) + ) + await context.route('**/api/billing/status', (route) => + route.fulfill({ json: LEGACY_PERSONAL_BILLING_STATUS }) + ) + await context.route('**/api/billing/balance', (route) => + route.fulfill({ json: EMPTY_BILLING_BALANCE }) + ) + await context.route('**/api/billing/plans', (route) => + route.fulfill({ json: EMPTY_BILLING_PLANS }) + ) + await context.route('**/customers/balance', (route) => + route.fulfill({ json: ZERO_BALANCE }) + ) + await mockWorkspace(context, workspace('personal', 'owner'), []) await comfyPage.cloudAuth.mockAuth() } diff --git a/browser_tests/fixtures/data/cloudWorkspace.ts b/browser_tests/fixtures/data/cloudWorkspace.ts index fbd97e53e74..7a27f7cc486 100644 --- a/browser_tests/fixtures/data/cloudWorkspace.ts +++ b/browser_tests/fixtures/data/cloudWorkspace.ts @@ -1,4 +1,8 @@ -import type { BillingStatusResponse as IngestBillingStatusResponse } from '@comfyorg/ingest-types' +import type { + BillingBalanceResponse, + BillingPlansResponse, + BillingStatusResponse as IngestBillingStatusResponse +} from '@comfyorg/ingest-types' import type { Member, @@ -7,12 +11,27 @@ import type { } from '@/platform/workspace/api/workspaceApi' import type { RemoteConfig } from '@/platform/remoteConfig/types' -// `/api/features` is the remote-config source: production builds resolve the -// workspaces flag from it (the `ff:` localStorage override is dev-only). -export const WORKSPACE_FEATURE_FLAG: RemoteConfig = { - team_workspaces_enabled: true, - consolidated_billing_enabled: true -} +export const CLOUD_REMOTE_CONFIG: RemoteConfig = {} + +export const LEGACY_PERSONAL_BILLING_STATUS = { + billing_rail: 'legacy_stripe', + billing_status: 'inactive', + has_funds: true, + is_active: false, + subscription_status: 'ended', + subscription_tier: 'FREE', + team_credit_stop: null +} satisfies IngestBillingStatusResponse + +export const EMPTY_BILLING_BALANCE = { + amount_micros: 0, + currency: 'usd', + effective_balance_micros: 0 +} satisfies BillingBalanceResponse + +export const EMPTY_BILLING_PLANS = { + plans: [] +} satisfies BillingPlansResponse export const TEAM_WORKSPACE: WorkspaceWithRole = { id: 'ws-team', diff --git a/browser_tests/fixtures/data/subscriptionFixtures.ts b/browser_tests/fixtures/data/subscriptionFixtures.ts index 87fae8d9301..eb24b0ef79c 100644 --- a/browser_tests/fixtures/data/subscriptionFixtures.ts +++ b/browser_tests/fixtures/data/subscriptionFixtures.ts @@ -1,22 +1,18 @@ import type { operations } from '@comfyorg/registry-types' -export type SubscriptionStatusResponse = - operations['GetCloudSubscriptionStatus']['responses']['200']['content']['application/json'] +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' export type BalanceResponse = operations['GetCustomerBalance']['responses']['200']['content']['application/json'] export function createSubscriptionStatus( - overrides: Partial = {} -): SubscriptionStatusResponse { + overrides: Partial = {} +): BillingStatusResponse { return { is_active: false, - subscription_id: null, subscription_tier: 'FREE', - subscription_duration: null, - has_fund: false, - renewal_date: null, - end_date: null, + has_funds: false, + billing_rail: 'legacy_stripe', ...overrides } } @@ -35,13 +31,10 @@ export function createBalance( } } -export const UNSUBSCRIBED: SubscriptionStatusResponse = - createSubscriptionStatus({ - is_active: false, - subscription_id: null, - subscription_tier: 'FREE', - end_date: null - }) +export const UNSUBSCRIBED: BillingStatusResponse = createSubscriptionStatus({ + is_active: false, + subscription_tier: 'FREE' +}) export const ZERO_BALANCE: BalanceResponse = createBalance({ amount_micros: 0, diff --git a/browser_tests/fixtures/helpers/CloudWorkspaceMockHelper.ts b/browser_tests/fixtures/helpers/CloudWorkspaceMockHelper.ts index ff5b29227a9..b17f4bbba28 100644 --- a/browser_tests/fixtures/helpers/CloudWorkspaceMockHelper.ts +++ b/browser_tests/fixtures/helpers/CloudWorkspaceMockHelper.ts @@ -9,11 +9,11 @@ import type { import { mockSystemStats } from '@e2e/fixtures/data/systemStats' import { + CLOUD_REMOTE_CONFIG, DEFAULT_TEAM_MEMBERS, TEAM_BILLING_STATUS, TEAM_PRO_PLAN, - TEAM_WORKSPACE, - WORKSPACE_FEATURE_FLAG + TEAM_WORKSPACE } from '@e2e/fixtures/data/cloudWorkspace' import { CloudAuthHelper } from '@e2e/fixtures/helpers/CloudAuthHelper' import { mockWorkspaceTokenMint } from '@e2e/fixtures/utils/workspaceMocks' @@ -71,7 +71,7 @@ export class CloudWorkspaceMockHelper { const { page } = this await page.route('**/api/features', (r) => - r.fulfill(jsonRoute(WORKSPACE_FEATURE_FLAG)) + r.fulfill(jsonRoute(CLOUD_REMOTE_CONFIG)) ) await page.route('**/api/system_stats', (r) => r.fulfill(jsonRoute(mockSystemStats)) diff --git a/browser_tests/fixtures/helpers/SubscriptionHelper.ts b/browser_tests/fixtures/helpers/SubscriptionHelper.ts index f3b6bd80968..3f25e2e820d 100644 --- a/browser_tests/fixtures/helpers/SubscriptionHelper.ts +++ b/browser_tests/fixtures/helpers/SubscriptionHelper.ts @@ -1,21 +1,22 @@ import { expect } from '@playwright/test' import type { Page, Route } from '@playwright/test' -import { PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY } from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' +import { + PENDING_SUBSCRIPTION_CHECKOUT_EVENT, + PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY +} from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' import { createBalance, createSubscriptionStatus, UNSUBSCRIBED, ZERO_BALANCE } from '@e2e/fixtures/data/subscriptionFixtures' -import type { - BalanceResponse, - SubscriptionStatusResponse -} from '@e2e/fixtures/data/subscriptionFixtures' +import type { BalanceResponse } from '@e2e/fixtures/data/subscriptionFixtures' import { TestIds } from '@e2e/fixtures/selectors' export interface SubscriptionConfig { - status: SubscriptionStatusResponse + status: BillingStatusResponse balance: BalanceResponse } @@ -31,7 +32,7 @@ export type SubscriptionOperator = ( ) => SubscriptionConfig function withSubscriptionStatus( - overrides: Partial + overrides: Partial ): SubscriptionOperator { return (config) => ({ ...config, @@ -40,35 +41,31 @@ function withSubscriptionStatus( } export function withActiveSubscription( - tier: NonNullable = 'CREATOR' + tier: NonNullable = 'CREATOR' ): SubscriptionOperator { return withSubscriptionStatus({ is_active: true, subscription_tier: tier, - renewal_date: '2099-12-31T00:00:00.000Z', - end_date: null + renewal_date: '2099-12-31T00:00:00.000Z' }) } export function withFreeTier(): SubscriptionOperator { return withSubscriptionStatus({ is_active: true, - subscription_tier: 'FREE', - end_date: null + subscription_tier: 'FREE' }) } export function withUnsubscribed(): SubscriptionOperator { return withSubscriptionStatus({ is_active: false, - subscription_tier: 'FREE', - end_date: null, - renewal_date: null + subscription_tier: 'FREE' }) } export class SubscriptionHelper { - private statusResponse: SubscriptionStatusResponse + private statusResponse: BillingStatusResponse private balanceResponse: BalanceResponse private routeHandlers: Array<{ pattern: string @@ -104,7 +101,7 @@ export class SubscriptionHelper { }) await this.page.route(featuresPattern, featuresHandler) - const statusPattern = '**/customers/cloud-subscription-status' + const statusPattern = '**/api/billing/status' const statusHandler = async (route: Route) => { await route.fulfill({ json: this.statusResponse }) } @@ -143,7 +140,7 @@ export class SubscriptionHelper { this.balanceResponse = { ...config.balance } } - setStatus(overrides: Partial): void { + setStatus(overrides: Partial): void { this.statusResponse = { ...this.statusResponse, ...overrides } } @@ -179,14 +176,14 @@ export class SubscriptionHelper { } /** - * Dispatch `visibilitychange` to simulate returning from Stripe checkout. - * The app re-fetches subscription status when a pending checkout attempt - * exists in localStorage (seeded via `seedPendingCheckout`). + * Notify the app that a pending checkout attempt needs to be recovered. */ async triggerSubscriptionRefetch(): Promise { - await this.page.evaluate(() => { - document.dispatchEvent(new Event('visibilitychange')) - }) + const eventName = PENDING_SUBSCRIPTION_CHECKOUT_EVENT + await this.page.evaluate( + (name) => window.dispatchEvent(new Event(name)), + eventName + ) } /** diff --git a/browser_tests/fixtures/utils/cloudBillingMocks.ts b/browser_tests/fixtures/utils/cloudBillingMocks.ts index 0d30bf81061..49f6576791a 100644 --- a/browser_tests/fixtures/utils/cloudBillingMocks.ts +++ b/browser_tests/fixtures/utils/cloudBillingMocks.ts @@ -25,9 +25,6 @@ export async function mockBilling(page: Page) { await page.route('**/api/billing/plans', (r) => r.fulfill(jsonRoute({ plans: [] })) ) - await page.route('**/customers/cloud-subscription-status', (r) => - r.fulfill(jsonRoute({ is_active: false })) - ) await page.route('**/customers/balance', (r) => r.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) ) diff --git a/browser_tests/fixtures/utils/cloudBootMocks.ts b/browser_tests/fixtures/utils/cloudBootMocks.ts index ec127cb01c8..ddb89d5cbc1 100644 --- a/browser_tests/fixtures/utils/cloudBootMocks.ts +++ b/browser_tests/fixtures/utils/cloudBootMocks.ts @@ -5,6 +5,7 @@ import type { RemoteConfig } from '@/platform/remoteConfig/types' import { mockSystemStats } from '@e2e/fixtures/data/systemStats' import { CloudAuthHelper } from '@e2e/fixtures/helpers/CloudAuthHelper' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' interface CloudBootOptions { /** Remote-config payload for `/api/features` (enables the flags under test). */ @@ -47,6 +48,7 @@ export async function mockCloudBoot( await page.route('**/api/auth/session', (r) => r.fulfill(jsonRoute({ token: 'mock-workspace-token' })) ) + await mockWorkspace(page, workspace('personal', 'owner'), []) await page.route('**/releases**', (r) => r.fulfill(jsonRoute([]))) } diff --git a/browser_tests/fixtures/utils/workspaceMocks.ts b/browser_tests/fixtures/utils/workspaceMocks.ts index 75b6f9b65c9..eeee8b40cb2 100644 --- a/browser_tests/fixtures/utils/workspaceMocks.ts +++ b/browser_tests/fixtures/utils/workspaceMocks.ts @@ -1,4 +1,4 @@ -import type { Page } from '@playwright/test' +import type { BrowserContext, Page } from '@playwright/test' import type { Member, @@ -38,10 +38,10 @@ export function member( * this the mint fails and auth cannot resolve the active workspace. */ export async function mockWorkspaceTokenMint( - page: Page, + routeTarget: Page | BrowserContext, ws: Pick ) { - await page.route('**/api/auth/token', (r) => + await routeTarget.route('**/api/auth/token', (r) => r.fulfill( jsonRoute({ token: 'mock-workspace-token', @@ -59,16 +59,16 @@ export async function mockWorkspaceTokenMint( * given workspace with the given roster (drives the original-owner gate). */ export async function mockWorkspace( - page: Page, + routeTarget: Page | BrowserContext, ws: WorkspaceWithRole, members: Member[] ) { - await page.route('**/api/workspaces', async (route) => { + await routeTarget.route('**/api/workspaces', async (route) => { if (route.request().method() !== 'GET') return route.fallback() await route.fulfill(jsonRoute({ workspaces: [ws] })) }) - await mockWorkspaceTokenMint(page, ws) - await page.route('**/api/workspace/members**', (r) => + await mockWorkspaceTokenMint(routeTarget, ws) + await routeTarget.route('**/api/workspace/members**', (r) => r.fulfill( jsonRoute({ members, diff --git a/browser_tests/tests/authAccountSwitch.spec.ts b/browser_tests/tests/authAccountSwitch.spec.ts index e6e5b88e2e9..c81476f3450 100644 --- a/browser_tests/tests/authAccountSwitch.spec.ts +++ b/browser_tests/tests/authAccountSwitch.spec.ts @@ -6,9 +6,9 @@ import type { WorkspaceTokenResponse } from '@/platform/workspace/stores/workspa import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' import { AssetsSidebarTab } from '@e2e/fixtures/components/SidebarTab' import { + CLOUD_REMOTE_CONFIG, DEFAULT_TEAM_MEMBERS, - TEAM_WORKSPACE, - WORKSPACE_FEATURE_FLAG + TEAM_WORKSPACE } from '@e2e/fixtures/data/cloudWorkspace' import { AssetsHelper, createMockJob } from '@e2e/fixtures/helpers/AssetsHelper' import { CloudWorkspaceMockHelper } from '@e2e/fixtures/helpers/CloudWorkspaceMockHelper' @@ -141,7 +141,7 @@ test.describe('Cloud account switch', { tag: '@cloud' }, () => { await page.unroute('**/securetoken.googleapis.com/**') const features = { - ...WORKSPACE_FEATURE_FLAG, + ...CLOUD_REMOTE_CONFIG, onboarding_survey_enabled: false, unified_cloud_auth: false } satisfies RemoteConfig diff --git a/browser_tests/tests/billingFacadeConsumers.spec.ts b/browser_tests/tests/billingFacadeConsumers.spec.ts index bc3ae2eb920..11579243af3 100644 --- a/browser_tests/tests/billingFacadeConsumers.spec.ts +++ b/browser_tests/tests/billingFacadeConsumers.spec.ts @@ -1,7 +1,6 @@ import { expect } from '@playwright/test' import type { Page } from '@playwright/test' -import type { CloudSubscriptionStatusResponse } from '@/platform/cloud/subscription/composables/useSubscription' import type { RemoteConfig } from '@/platform/remoteConfig/types' import type { BillingBalanceResponse, @@ -19,11 +18,9 @@ import { /** * Billing facade consumers — FE-933 (B3) regression. * - * The repointed surfaces (avatar popover tier badge / balance, free-tier - * dialog renewal date) must keep rendering from `useBillingContext`. The facade - * selects its backend by flag: `team_workspaces_enabled: false` routes through - * the legacy `/customers/*` endpoints, while `true` routes a personal workspace - * through the workspace `/api/billing/*` endpoints. Both shapes are mocked here. + * The repointed surfaces (avatar popover balance, free-tier dialog renewal + * date) must keep rendering from `useBillingContext`. Cloud + * personal workspaces route through the workspace `/api/billing/*` endpoints. * Drives a raw `page` (not the `comfyPage` fixture) so the cloud app boots * against fully mocked endpoints — same pattern as creditsTile.spec.ts. */ @@ -35,30 +32,29 @@ const jsonRoute = (body: unknown) => ({ body: JSON.stringify(body) }) -// The workspace `/api/billing/status` shape mirrors the legacy subscription -// status; map the fields so a single test fixture drives both backends. -const toWorkspaceStatus = ( - s: CloudSubscriptionStatusResponse -): BillingStatusResponse => ({ - is_active: s.is_active ?? false, - subscription_tier: s.subscription_tier ?? undefined, - subscription_duration: s.subscription_duration ?? undefined, - renewal_date: s.renewal_date ?? undefined, - cancel_at: s.end_date ?? undefined, - has_funds: s.has_fund ?? true -}) - const mockBalance: BillingBalanceResponse = { amount_micros: 6000, // -> 12,660 credits currency: 'usd', effective_balance_micros: 6000 } +const mockWorkspaceBalance: BillingBalanceResponse = { + amount_micros: 0, + currency: 'usd', + effective_balance_micros: 0 +} + async function mockCloudBoot( page: Page, - subscriptionStatus: CloudSubscriptionStatusResponse, - remoteConfig: RemoteConfig = { team_workspaces_enabled: false } + subscriptionStatus: BillingStatusResponse, + remoteConfig: RemoteConfig = {}, + billingRail?: BillingStatusResponse['billing_rail'] ) { + const billingRequests = { + legacyBalance: 0, + workspaceStatus: 0 + } + await page.route('**/api/features', (r) => r.fulfill(jsonRoute(remoteConfig))) await page.route('**/api/system_stats', (r) => r.fulfill(jsonRoute(mockSystemStats)) @@ -104,25 +100,29 @@ async function mockCloudBoot( ) ) - // Legacy backend (team_workspaces_enabled: false). - await page.route('**/customers/cloud-subscription-status', (r) => - r.fulfill(jsonRoute(subscriptionStatus)) - ) - await page.route('**/customers/balance', (r) => - r.fulfill(jsonRoute(mockBalance)) - ) + await page.route('**/customers/balance', (r) => { + billingRequests.legacyBalance++ + return r.fulfill(jsonRoute(mockBalance)) + }) - // Workspace backend (team_workspaces_enabled: true) — a personal workspace - // now routes through `/api/billing/*`. - await page.route('**/api/billing/status', (r) => - r.fulfill(jsonRoute(toWorkspaceStatus(subscriptionStatus))) - ) - await page.route('**/api/billing/balance', (r) => - r.fulfill(jsonRoute(mockBalance)) - ) + // Cloud personal workspaces route through `/api/billing/*`. + await page.route('**/api/billing/status', (r) => { + billingRequests.workspaceStatus++ + return r.fulfill( + jsonRoute({ + ...subscriptionStatus, + billing_rail: billingRail + }) + ) + }) + await page.route('**/api/billing/balance', (r) => { + return r.fulfill(jsonRoute(mockWorkspaceBalance)) + }) await page.route('**/api/billing/plans', (r) => r.fulfill(jsonRoute({ plans: [] })) ) + + return billingRequests } async function bootApp(page: Page) { @@ -140,27 +140,33 @@ async function bootApp(page: Page) { } test.describe('Billing facade consumers (FE-933)', { tag: '@cloud' }, () => { - test('avatar popover renders tier badge and balance from the facade', async ({ + test('avatar popover renders a legacy-rail balance from the facade', async ({ page }) => { test.setTimeout(60_000) - await mockCloudBoot(page, { - is_active: true, - subscription_tier: 'PRO', - subscription_duration: 'MONTHLY', - renewal_date: '2099-02-20T10:00:00Z', - end_date: null - }) + const billingRequests = await mockCloudBoot( + page, + { + is_active: true, + subscription_tier: 'PRO', + subscription_duration: 'MONTHLY', + renewal_date: '2099-02-20T10:00:00Z', + has_funds: true + }, + {}, + 'legacy_stripe' + ) await bootApp(page) await page.getByRole('button', { name: 'Current user' }).click() const popover = page.locator('.current-user-popover') await expect(popover).toBeVisible() - await expect(popover.getByText('Pro', { exact: true })).toBeVisible() await expect(popover.getByText('12,660')).toBeVisible() await expect(popover.getByTestId('add-credits-button')).toBeVisible() + expect(billingRequests.workspaceStatus).toBeGreaterThan(0) + expect(billingRequests.legacyBalance).toBeGreaterThan(0) }) test('subscribe-to-run routes an inactive FREE user to the pricing table', async ({ @@ -168,8 +174,8 @@ test.describe('Billing facade consumers (FE-933)', { tag: '@cloud' }, () => { }) => { test.setTimeout(60_000) - // Boots with team workspaces enabled (production shape); the facade routes a - // personal workspace through the workspace `/api/billing/*` endpoints. With + // The facade routes a personal workspace through the workspace + // `/api/billing/*` endpoints. With // subscription gating on, an inactive FREE user gets the "Subscribe to run" // button, which opens the pricing table on click. (refreshRemoteConfig // overwrites window.__CONFIG__ from /api/features, so the flags must come @@ -182,14 +188,16 @@ test.describe('Billing facade consumers (FE-933)', { tag: '@cloud' }, () => { subscription_duration: 'MONTHLY', // 10:00Z keeps the en-US calendar date stable across CI timezones. renewal_date: '2099-02-20T10:00:00Z', - end_date: null + has_funds: false }, - { team_workspaces_enabled: true, subscription_required: true } + { subscription_required: true } ) await bootApp(page) await page.getByTestId('subscribe-to-run-button').click() - await expect(page.getByRole('heading', { name: /Plans for/ })).toBeVisible() + await expect( + page.getByRole('heading', { name: 'Choose a Plan' }) + ).toBeVisible() }) }) diff --git a/browser_tests/tests/currentUserPopoverCredits.spec.ts b/browser_tests/tests/currentUserPopoverCredits.spec.ts index c7538fd8241..2305fde8326 100644 --- a/browser_tests/tests/currentUserPopoverCredits.spec.ts +++ b/browser_tests/tests/currentUserPopoverCredits.spec.ts @@ -1,6 +1,5 @@ import { expect } from '@playwright/test' -import type { CloudSubscriptionStatusResponse } from '@/platform/cloud/subscription/composables/useSubscription' import type { RemoteConfig } from '@/platform/remoteConfig/types' import type { BillingStatusResponse, @@ -17,7 +16,7 @@ type CustomerBalanceResponse = NonNullable< const PERSONAL_WORKSPACE_NAME = 'Personal Workspace' const FUTURE_DATE = '2099-01-01T00:00:00Z' -const mockRemoteConfig: RemoteConfig = { team_workspaces_enabled: true } +const mockRemoteConfig: RemoteConfig = {} const mockListWorkspacesResponse: { workspaces: WorkspaceWithRole[] } = { workspaces: [ @@ -44,18 +43,8 @@ const mockTokenResponse: WorkspaceTokenResponse = { permissions: [] } -// Cancelled but still active: `end_date` set (cancelled) while `is_active` is -// true. A personal owner in this state sees BOTH "Add credits" and "Resubscribe" -// in the credits row. -const mockSubscriptionStatus: CloudSubscriptionStatusResponse = { - is_active: true, - subscription_id: 'sub_e2e', - renewal_date: FUTURE_DATE, - end_date: FUTURE_DATE -} - -// With team workspaces enabled, the facade routes a personal workspace through -// `/api/billing/*`. The cancelled-but-active state maps to `is_active: true` +// The facade routes a Cloud personal workspace through `/api/billing/*`. The +// cancelled-but-active state maps to `is_active: true` // with `subscription_status: 'canceled'`; a paid tier keeps "Add credits" // visible (free tier would swap it for "Upgrade to add credits"). const mockBillingStatus: BillingStatusResponse = { @@ -110,14 +99,6 @@ const test = comfyPageFixture.extend({ route.fulfill({ status: 204 }) ) - await page.route('**/customers/cloud-subscription-status', (route) => - route.fulfill({ - status: 200, - contentType: 'application/json', - body: JSON.stringify(mockSubscriptionStatus) - }) - ) - await page.route('**/customers/balance', (route) => route.fulfill({ status: 200, @@ -126,8 +107,7 @@ const test = comfyPageFixture.extend({ }) ) - // Flag-on (team workspaces enabled) routes a personal workspace through the - // workspace billing endpoints, so the popover sources its data from here. + // The popover sources its data from the workspace billing endpoints. await page.route('**/api/billing/status', (route) => route.fulfill({ status: 200, diff --git a/browser_tests/tests/dialogs/creditsTile.spec.ts b/browser_tests/tests/dialogs/creditsTile.spec.ts index 726ff769b8e..376a1e68817 100644 --- a/browser_tests/tests/dialogs/creditsTile.spec.ts +++ b/browser_tests/tests/dialogs/creditsTile.spec.ts @@ -28,10 +28,9 @@ import { * The credits tile only lives inside the authenticated cloud app, which the * shared `comfyPage` fixture can't boot (it expects the OSS devtools backend). * Instead this drives a raw page: mock Firebase auth + every boot endpoint so - * the cloud app initializes against fully stubbed data. With team workspaces - * enabled the facade routes a personal workspace through the workspace - * `/api/billing/*` endpoints (mocked with an active Pro subscription); the - * legacy `/customers/*` shapes are mocked too for the flag-off path. The tile + * the cloud app initializes against fully stubbed data. The facade routes a + * personal workspace through the workspace `/api/billing/*` endpoints (mocked + * with an active Pro subscription). The tile * should then render its total / progress bar / monthly+additional breakdown / * add-credits. */ @@ -71,13 +70,10 @@ const mockBillingStatus: BillingStatusResponse = { async function mockCloudBoot(page: Page, billingControlEnabled = true) { // Frontend-origin boot endpoints (proxied to the backend in production). - // `/api/features` is the remote-config source: production builds resolve - // workspace availability and the billing UX rollout from it (the `ff:` - // localStorage override is dev-only). + // `/api/features` is the remote-config source for the billing UX rollout. await page.route('**/api/features', (r) => r.fulfill( jsonRoute({ - team_workspaces_enabled: true, billing_control_enabled: billingControlEnabled } satisfies RemoteConfig) ) @@ -129,24 +125,10 @@ async function mockCloudBoot(page: Page, billingControlEnabled = true) { ) ) - // Legacy billing (flag-off path, api.comfy.org/customers/*). - await page.route('**/customers/cloud-subscription-status', (r) => - r.fulfill( - jsonRoute({ - is_active: true, - subscription_tier: 'PRO', - subscription_duration: 'MONTHLY', - renewal_date: '2099-02-20T12:00:00Z', - end_date: null - }) - ) - ) await page.route('**/customers/balance', (r) => r.fulfill(balanceRoute(DEFAULT_BALANCE)) ) - // Workspace billing (flag-on path) — a personal workspace now routes through - // `/api/billing/*`. await page.route('**/api/billing/status', (r) => r.fulfill(jsonRoute(mockBillingStatus)) ) diff --git a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts index a3c5f68c87a..6ab70d5e0a9 100644 --- a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts +++ b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts @@ -41,11 +41,7 @@ const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' const SELF_EMAIL = 'e2e@test.comfy.org' -// consolidated_billing_enabled routes personal workspaces to the unified -// pricing table asserted here; without it they fall back to the legacy table. const BOOT_FEATURES = { - team_workspaces_enabled: true, - consolidated_billing_enabled: true, billing_control_enabled: true } satisfies RemoteConfig // Disable the experimental Asset API: with it on (cloud default) the unmocked diff --git a/browser_tests/tests/freeTierQuota.spec.ts b/browser_tests/tests/freeTierQuota.spec.ts index 968a8c21c3e..b8872732c35 100644 --- a/browser_tests/tests/freeTierQuota.spec.ts +++ b/browser_tests/tests/freeTierQuota.spec.ts @@ -15,8 +15,14 @@ test.describe('Free Tier Quota', { tag: ['@cloud', '@vue-nodes'] }, () => { free_tier_balance: { allowance: 5, remaining: 3, used: 0 } } await page.route('**/api/features', (r) => r.fulfill(jsonRoute(features))) - await page.route('**/customers/cloud-subscription-status', (r) => - r.fulfill(jsonRoute({ is_active: true, subscription_tier: 'FREE' })) + await page.route('**/api/billing/status', (r) => + r.fulfill( + jsonRoute({ + is_active: true, + has_funds: true, + subscription_tier: 'FREE' + }) + ) ) }) diff --git a/browser_tests/tests/propertiesPanel/errorsTabMissingMediaRuntime.spec.ts b/browser_tests/tests/propertiesPanel/errorsTabMissingMediaRuntime.spec.ts index a39b55b98b6..4af8ed686fd 100644 --- a/browser_tests/tests/propertiesPanel/errorsTabMissingMediaRuntime.spec.ts +++ b/browser_tests/tests/propertiesPanel/errorsTabMissingMediaRuntime.spec.ts @@ -142,13 +142,6 @@ async function routeCloudBootstrapApis(page: Page) { body: JSON.stringify({}) }) }) - await page.route('**/customers/cloud-subscription-status', async (route) => { - await route.fulfill({ - status: 200, - contentType: 'application/json', - body: JSON.stringify({ is_active: true }) - }) - }) } const cloudOutputTest = createCloudAssetsFixture([ diff --git a/browser_tests/tests/workspaceSwitcher.spec.ts b/browser_tests/tests/workspaceSwitcher.spec.ts index 02e6ab8a0f7..662be567a7c 100644 --- a/browser_tests/tests/workspaceSwitcher.spec.ts +++ b/browser_tests/tests/workspaceSwitcher.spec.ts @@ -14,7 +14,6 @@ const TEAM_WORKSPACE_NAME = 'Team Workspace' const SINGLE_LINE_MAX_HEIGHT_PX = 28 const mockRemoteConfig: RemoteConfig = { - team_workspaces_enabled: true, unified_cloud_auth: true } diff --git a/src/components/topbar/CurrentUserButton.test.ts b/src/components/topbar/CurrentUserButton.test.ts index 610870a0bf8..7b166c05ee4 100644 --- a/src/components/topbar/CurrentUserButton.test.ts +++ b/src/components/topbar/CurrentUserButton.test.ts @@ -8,10 +8,6 @@ import enMessages from '@/locales/en/main.json' with { type: 'json' } import CurrentUserButton from './CurrentUserButton.vue' -const mockFeatureFlags = vi.hoisted(() => ({ - teamWorkspacesEnabled: false -})) - const mockTeamWorkspaceStore = vi.hoisted(() => ({ workspaceName: { value: '' }, initState: { value: 'idle' }, @@ -40,13 +36,6 @@ vi.mock('pinia', () => ({ storeToRefs: vi.fn((store: Record) => store) })) -// Mock the useFeatureFlags composable -vi.mock('@/composables/useFeatureFlags', () => ({ - useFeatureFlags: vi.fn(() => ({ - flags: mockFeatureFlags - })) -})) - // Mock the useTeamWorkspaceStore vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({ useTeamWorkspaceStore: vi.fn(() => mockTeamWorkspaceStore) @@ -88,6 +77,20 @@ vi.mock('@/platform/workspace/components/WorkspaceProfilePic.vue', () => ({ } })) +const CurrentUserPopoverWorkspaceStub = defineComponent({ + name: 'CurrentUserPopoverWorkspace', + props: { + accountActionsOnly: Boolean + }, + setup(props) { + return () => + h('div', [ + h('span', 'Workspace Popover Content'), + props.accountActionsOnly ? h('span', 'Account Actions Only') : '' + ]) + } +}) + // Mock the CurrentUserPopoverLegacy component vi.mock('./CurrentUserPopoverLegacy.vue', () => ({ default: defineComponent({ @@ -96,7 +99,7 @@ vi.mock('./CurrentUserPopoverLegacy.vue', () => ({ setup(_, { emit }) { return () => h('div', [ - 'Popover Content', + h('span', 'Popover Content'), h( 'button', { @@ -113,7 +116,6 @@ vi.mock('./CurrentUserPopoverLegacy.vue', () => ({ describe('CurrentUserButton', () => { beforeEach(() => { vi.clearAllMocks() - mockFeatureFlags.teamWorkspacesEnabled = false mockTeamWorkspaceStore.workspaceName.value = '' mockTeamWorkspaceStore.initState.value = 'idle' mockTeamWorkspaceStore.isInPersonalWorkspace.value = false @@ -132,6 +134,7 @@ describe('CurrentUserButton', () => { global: { plugins: [i18n], stubs: { + CurrentUserPopoverWorkspace: CurrentUserPopoverWorkspaceStub, Popover: defineComponent({ setup(_, { slots, expose }) { const shown = ref(false) @@ -170,6 +173,20 @@ describe('CurrentUserButton', () => { expect(screen.getByText('Popover Content')).toBeInTheDocument() }) + it.for(['loading', 'error'])( + 'shows account actions while Cloud workspace initialization is %s', + async (initState) => { + mockIsCloud.value = true + mockTeamWorkspaceStore.initState.value = initState + const { user } = renderComponent() + + await user.click(screen.getByRole('button', { name: 'Current user' })) + + expect(screen.getByText('Workspace Popover Content')).toBeInTheDocument() + expect(screen.getByText('Account Actions Only')).toBeInTheDocument() + } + ) + it('hides popover when closePopover is called', async () => { const { user } = renderComponent() @@ -183,7 +200,6 @@ describe('CurrentUserButton', () => { it('shows UserAvatar in personal workspace', () => { mockIsCloud.value = true - mockFeatureFlags.teamWorkspacesEnabled = true mockTeamWorkspaceStore.initState.value = 'ready' mockTeamWorkspaceStore.isInPersonalWorkspace.value = true @@ -194,7 +210,6 @@ describe('CurrentUserButton', () => { it('shows WorkspaceProfilePic in team workspace', () => { mockIsCloud.value = true - mockFeatureFlags.teamWorkspacesEnabled = true mockTeamWorkspaceStore.initState.value = 'ready' mockTeamWorkspaceStore.isInPersonalWorkspace.value = false mockTeamWorkspaceStore.workspaceName.value = 'My Team' diff --git a/src/components/topbar/CurrentUserButton.vue b/src/components/topbar/CurrentUserButton.vue index 22840928205..490d6011f34 100644 --- a/src/components/topbar/CurrentUserButton.vue +++ b/src/components/topbar/CurrentUserButton.vue @@ -48,17 +48,13 @@ }" @show="onPopoverShow" > - - - + @@ -73,7 +69,6 @@ import UserAvatar from '@/components/common/UserAvatar.vue' import WorkspaceProfilePic from '@/platform/workspace/components/WorkspaceProfilePic.vue' import Button from '@/components/ui/button/Button.vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' -import { useFeatureFlags } from '@/composables/useFeatureFlags' import { isCloud } from '@/platform/distribution/types' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { cn } from '@comfyorg/tailwind-utils' @@ -90,9 +85,6 @@ const { showArrow = true, compact = false } = defineProps<{ compact?: boolean }>() -const { flags } = useFeatureFlags() -const teamWorkspacesEnabled = computed(() => flags.teamWorkspacesEnabled) - const { isLoggedIn, userPhotoUrl } = useCurrentUser() const photoURL = computed( @@ -106,14 +98,10 @@ const { } = storeToRefs(useTeamWorkspaceStore()) const showWorkspaceSkeleton = computed( - () => isCloud && teamWorkspacesEnabled.value && initState.value === 'loading' + () => isCloud && initState.value === 'loading' ) const showWorkspaceIcon = computed( - () => - isCloud && - teamWorkspacesEnabled.value && - initState.value === 'ready' && - !isInPersonalWorkspace.value + () => isCloud && initState.value === 'ready' && !isInPersonalWorkspace.value ) const workspaceName = computed(() => { diff --git a/src/composables/billing/useBillingContext.test.ts b/src/composables/billing/useBillingContext.test.ts index 847e952ae33..730f5ba4cf1 100644 --- a/src/composables/billing/useBillingContext.test.ts +++ b/src/composables/billing/useBillingContext.test.ts @@ -19,8 +19,6 @@ const DEFAULT_BILLING_STATUS: BillingStatusResponse = { } const { - mockTeamWorkspacesEnabled, - mockConsolidatedBillingEnabled, mockIsPersonal, mockBillingRail, mockPlans, @@ -33,8 +31,6 @@ const { mockSetWorkspaceBillingRail, mockBillingStatus } = vi.hoisted(() => ({ - mockTeamWorkspacesEnabled: { value: false }, - mockConsolidatedBillingEnabled: { value: false }, mockIsPersonal: { value: true }, mockBillingRail: { value: undefined as BillingRail | undefined }, mockPlans: { value: [] as Plan[] }, @@ -63,37 +59,7 @@ vi.mock('@vueuse/core', async (importOriginal) => { } }) -vi.mock('@/composables/useFeatureFlags', async () => { - const { ref } = await import('vue') - const teamWorkspacesEnabledRef = ref(mockTeamWorkspacesEnabled.value) - Object.defineProperty(mockTeamWorkspacesEnabled, 'value', { - get: () => teamWorkspacesEnabledRef.value, - set: (value: boolean) => { - teamWorkspacesEnabledRef.value = value - } - }) - const consolidatedBillingEnabledRef = ref( - mockConsolidatedBillingEnabled.value - ) - Object.defineProperty(mockConsolidatedBillingEnabled, 'value', { - get: () => consolidatedBillingEnabledRef.value, - set: (value: boolean) => { - consolidatedBillingEnabledRef.value = value - } - }) - return { - useFeatureFlags: () => ({ - flags: { - get teamWorkspacesEnabled() { - return mockTeamWorkspacesEnabled.value - }, - get consolidatedBillingEnabled() { - return mockConsolidatedBillingEnabled.value - } - } - }) - } -}) +vi.mock('@/platform/distribution/types', () => ({ isCloud: true })) vi.mock('@/platform/workspace/stores/teamWorkspaceStore', async () => { const { ref } = await import('vue') @@ -129,7 +95,11 @@ vi.mock('@/platform/cloud/subscription/composables/useSubscription', () => ({ subscriptionTier: { value: 'PRO' }, subscriptionDuration: { value: 'MONTHLY' }, subscriptionStatus: { - value: { renewal_date: '2025-01-01T00:00:00Z', end_date: null } + value: { + is_active: true, + has_funds: true, + renewal_date: '2025-01-01T00:00:00Z' + } }, isCancelled: { value: false }, fetchStatus: mockLegacyFetchStatus, @@ -191,8 +161,6 @@ describe('useBillingContext', () => { beforeEach(() => { setActivePinia(createPinia()) vi.clearAllMocks() - mockTeamWorkspacesEnabled.value = false - mockConsolidatedBillingEnabled.value = false mockIsPersonal.value = true mockBillingRail.value = undefined mockSetWorkspaceBillingRail.mockImplementation( @@ -204,33 +172,14 @@ describe('useBillingContext', () => { mockBillingStatus.value = { ...DEFAULT_BILLING_STATUS } }) - it('selects legacy type when team workspaces are disabled', () => { - mockTeamWorkspacesEnabled.value = false - const { type } = useBillingContext() - expect(type.value).toBe('legacy') - }) - - it('keeps personal on legacy when consolidated billing is disabled', () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = false - mockIsPersonal.value = true - - const { type } = useBillingContext() - expect(type.value).toBe('legacy') - }) - - it('selects workspace type for personal when consolidated billing is enabled', () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = true + it('selects workspace type for a Cloud personal workspace', () => { mockIsPersonal.value = true const { type } = useBillingContext() expect(type.value).toBe('workspace') }) - it('selects workspace type for team regardless of consolidated billing', () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = false + it('selects workspace type for a Cloud team workspace', () => { mockIsPersonal.value = false const { type } = useBillingContext() @@ -238,6 +187,7 @@ describe('useBillingContext', () => { }) it('provides subscription info from legacy billing', () => { + mockBillingRail.value = 'legacy_stripe' const { subscription } = useBillingContext() expect(subscription.value).toEqual({ @@ -253,6 +203,7 @@ describe('useBillingContext', () => { }) it('provides balance info from legacy billing', () => { + mockBillingRail.value = 'legacy_stripe' const { balance } = useBillingContext() expect(balance.value).toEqual({ @@ -281,15 +232,19 @@ describe('useBillingContext', () => { it('exposes subscribe action', async () => { const { subscribe } = useBillingContext() - await expect(subscribe('pro-monthly')).resolves.toBeUndefined() + await expect(subscribe('pro-monthly')).resolves.toEqual({ + status: 'subscribed' + }) }) it('exposes manageSubscription action', async () => { + mockBillingRail.value = 'legacy_stripe' const { manageSubscription } = useBillingContext() await expect(manageSubscription()).resolves.toBeUndefined() }) it('converts topup cents to whole dollars for the legacy credit endpoint', async () => { + mockBillingRail.value = 'legacy_stripe' const { topup } = useBillingContext() await topup(500) @@ -297,8 +252,6 @@ describe('useBillingContext', () => { }) it('uses workspace checkout while keeping legacy topups on legacy Stripe', async () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = true mockBillingRail.value = 'legacy_stripe' mockPlans.value = [ { @@ -327,7 +280,7 @@ describe('useBillingContext', () => { await context.fetchStatus() expect(mockFetchPlans).toHaveBeenCalledOnce() - expect(mockLegacyFetchStatus).toHaveBeenCalledOnce() + expect(mockLegacyFetchStatus).toHaveBeenCalled() expect(workspaceApi.getBillingStatus).not.toHaveBeenCalled() await context.previewSubscribe('creator-annual') @@ -347,8 +300,6 @@ describe('useBillingContext', () => { }) it('switches billing adapters before refreshing a migrated balance', async () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = true mockBillingRail.value = 'legacy_stripe' mockBillingStatus.value = { ...DEFAULT_BILLING_STATUS, @@ -356,6 +307,10 @@ describe('useBillingContext', () => { } const context = useBillingContext() + await vi.waitFor(() => { + expect(mockLegacyFetchStatus).toHaveBeenCalled() + expect(mockLegacyFetchBalance).toHaveBeenCalled() + }) vi.clearAllMocks() await context.reconcileSubscriptionSuccess() @@ -372,11 +327,13 @@ describe('useBillingContext', () => { }) it('does not refresh a balance through a stale rail after discovery fails', async () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = true mockBillingRail.value = 'legacy_stripe' const context = useBillingContext() + await vi.waitFor(() => { + expect(mockLegacyFetchStatus).toHaveBeenCalled() + expect(mockLegacyFetchBalance).toHaveBeenCalled() + }) vi.clearAllMocks() vi.mocked(workspaceApi.getBillingStatus).mockRejectedValueOnce( new Error('status unavailable') @@ -399,6 +356,7 @@ describe('useBillingContext', () => { }) it('provides isActiveSubscription convenience computed', () => { + mockBillingRail.value = 'legacy_stripe' const { isActiveSubscription } = useBillingContext() expect(isActiveSubscription.value).toBe(true) }) @@ -413,48 +371,8 @@ describe('useBillingContext', () => { expect(() => showSubscriptionDialog()).not.toThrow() }) - it('reinitializes workspace billing when the type flips on after legacy init', async () => { - mockTeamWorkspacesEnabled.value = false - mockIsPersonal.value = true - - const { type, initialize } = useBillingContext() - await initialize() - await nextTick() - - expect(type.value).toBe('legacy') - expect(workspaceApi.getBillingStatus).not.toHaveBeenCalled() - - // Authenticated remote config resolves the flag on for the same workspace - mockConsolidatedBillingEnabled.value = true - mockTeamWorkspacesEnabled.value = true - - await vi.waitFor(() => { - expect(type.value).toBe('workspace') - expect(workspaceApi.getBillingStatus).toHaveBeenCalled() - }) - }) - - it('moves a personal workspace to workspace billing when consolidated billing flips on', async () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = false - mockIsPersonal.value = true - - const { type } = useBillingContext() - await nextTick() - expect(type.value).toBe('legacy') - - mockConsolidatedBillingEnabled.value = true - - await vi.waitFor(() => { - expect(type.value).toBe('workspace') - expect(workspaceApi.getBillingStatus).toHaveBeenCalled() - }) - }) - describe('subscription mirror to workspace store', () => { - it('mirrors subscription for personal workspaces on the consolidated billing flow', async () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = true + it('mirrors subscription for personal workspaces', async () => { mockIsPersonal.value = true const { initialize } = useBillingContext() @@ -468,7 +386,6 @@ describe('useBillingContext', () => { }) it('never clobbers the list-derived store when a subscription is absent', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false const { initialize } = useBillingContext() @@ -483,16 +400,15 @@ describe('useBillingContext', () => { }) describe('getMaxSeats', () => { - it('returns 1 for personal workspaces regardless of tier', () => { + it('uses plan seat limits for Cloud personal workspaces', () => { const { getMaxSeats } = useBillingContext() expect(getMaxSeats('standard')).toBe(1) - expect(getMaxSeats('creator')).toBe(1) - expect(getMaxSeats('pro')).toBe(1) + expect(getMaxSeats('creator')).toBe(5) + expect(getMaxSeats('pro')).toBe(20) expect(getMaxSeats('founder')).toBe(1) }) it('falls back to hardcoded values when no API plans available', () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false const { getMaxSeats } = useBillingContext() @@ -503,7 +419,6 @@ describe('useBillingContext', () => { }) it('prefers API max_seats when plans are loaded', () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockPlans.value = [ { @@ -536,7 +451,6 @@ describe('useBillingContext', () => { }) it('is true for an active team plan: team- slug and no credit stop', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -553,7 +467,6 @@ describe('useBillingContext', () => { }) it('is true for any legacy team tier, not just standard', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -570,7 +483,6 @@ describe('useBillingContext', () => { }) it('is false for a new credit-slider team subscriber', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false // Real BE shape: underscore slug + populated credit stop. (subscription_tier // is 'TEAM' on the wire, not yet in the FE SubscriptionTier union, so it is @@ -595,7 +507,6 @@ describe('useBillingContext', () => { }) it('is false for a new team sub even before its credit stop is populated', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false // Provisioning lag: credit stop not yet attached. The underscore slug // (team_per_credit, not team-) must still exclude it from the legacy table. @@ -614,7 +525,6 @@ describe('useBillingContext', () => { }) it('is false for a team workspace on a personal-tier plan', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -631,7 +541,6 @@ describe('useBillingContext', () => { }) it('stays true for a cancelled-but-still-active legacy team sub', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -650,7 +559,6 @@ describe('useBillingContext', () => { }) it('is false for a FREE-tier team even on a team- prefixed slug', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -666,7 +574,6 @@ describe('useBillingContext', () => { }) it('matches the legacy slug case-insensitively', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -695,7 +602,6 @@ describe('useBillingContext', () => { // isTeamPlan reads the credit stop and the slug, never the tier — which is // what keeps it working despite that divergence. it('is true for a credit-slider team sub, which carries a credit stop', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -715,8 +621,6 @@ describe('useBillingContext', () => { }) it('is true for a per-credit Team plan in a personal workspace before its credit stop is populated', async () => { - mockTeamWorkspacesEnabled.value = true - mockConsolidatedBillingEnabled.value = true mockIsPersonal.value = true mockBillingStatus.value = { is_active: true, @@ -733,7 +637,6 @@ describe('useBillingContext', () => { }) it('is true for a legacy team sub, identified by slug rather than credit stop', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, @@ -753,7 +656,6 @@ describe('useBillingContext', () => { // spend gate folds billing_status into it. Coupling isTeamPlan to an active // subscription would blank the banner precisely when it is needed. it('stays true for a paused team plan, which the backend reports inactive', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: false, @@ -774,7 +676,6 @@ describe('useBillingContext', () => { }) it('stays true for a legacy team plan whose payment failed', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: false, @@ -791,7 +692,6 @@ describe('useBillingContext', () => { }) it('is false for a team workspace on a personal-tier plan', async () => { - mockTeamWorkspacesEnabled.value = true mockIsPersonal.value = false mockBillingStatus.value = { is_active: true, diff --git a/src/composables/billing/useBillingContext.ts b/src/composables/billing/useBillingContext.ts index ffb3d920f14..d9b90fa4a2a 100644 --- a/src/composables/billing/useBillingContext.ts +++ b/src/composables/billing/useBillingContext.ts @@ -228,9 +228,7 @@ function useBillingContextInternal(): BillingContext { error.value = null } - // type flips when the team-workspaces or consolidated-billing flag resolves - // from authenticated config, swapping the active backend. Reset then reinit - // on every workspace-id or type change. + // Reset and reinitialize when the active workspace or billing backend changes. watch( [() => store.activeWorkspace?.id, () => type.value], async ([newWorkspaceId]) => { diff --git a/src/composables/billing/useBillingRouting.test.ts b/src/composables/billing/useBillingRouting.test.ts index 5298b760d82..b6422991659 100644 --- a/src/composables/billing/useBillingRouting.test.ts +++ b/src/composables/billing/useBillingRouting.test.ts @@ -4,12 +4,9 @@ import type { BillingRail } from '@/platform/workspace/api/workspaceApi' import { useBillingRouting } from './useBillingRouting' -const { mockFlags, mockActiveWorkspace, mockActiveWorkspaceBillingRail } = +const { mockIsCloud, mockActiveWorkspace, mockActiveWorkspaceBillingRail } = vi.hoisted(() => ({ - mockFlags: { - teamWorkspacesEnabled: false, - consolidatedBillingEnabled: false - }, + mockIsCloud: { value: true }, mockActiveWorkspace: { value: null as { id: string; type: 'personal' | 'team' } | null }, @@ -18,8 +15,10 @@ const { mockFlags, mockActiveWorkspace, mockActiveWorkspaceBillingRail } = } })) -vi.mock('@/composables/useFeatureFlags', () => ({ - useFeatureFlags: () => ({ flags: mockFlags }) +vi.mock('@/platform/distribution/types', () => ({ + get isCloud() { + return mockIsCloud.value + } })) vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({ @@ -38,14 +37,13 @@ const team = { id: 'w-team', type: 'team' as const } describe('useBillingRouting', () => { beforeEach(() => { - mockFlags.teamWorkspacesEnabled = false - mockFlags.consolidatedBillingEnabled = false + mockIsCloud.value = true mockActiveWorkspace.value = personal mockActiveWorkspaceBillingRail.value = null }) - it('uses legacy billing when team workspaces are disabled', () => { - mockFlags.teamWorkspacesEnabled = false + it('uses legacy billing off Cloud', () => { + mockIsCloud.value = false mockActiveWorkspace.value = team const { type, shouldUseWorkspaceBilling } = useBillingRouting() @@ -54,19 +52,7 @@ describe('useBillingRouting', () => { expect(shouldUseWorkspaceBilling.value).toBe(false) }) - it('keeps personal on legacy when consolidated billing is disabled', () => { - mockFlags.teamWorkspacesEnabled = true - mockFlags.consolidatedBillingEnabled = false - mockActiveWorkspace.value = personal - - const { type } = useBillingRouting() - - expect(type.value).toBe('legacy') - }) - - it('moves personal to workspace billing when consolidated billing is enabled', () => { - mockFlags.teamWorkspacesEnabled = true - mockFlags.consolidatedBillingEnabled = true + it('uses workspace billing for a Cloud personal workspace', () => { mockActiveWorkspace.value = personal const { type, shouldUseWorkspaceBilling } = useBillingRouting() @@ -76,8 +62,6 @@ describe('useBillingRouting', () => { }) it('uses unified pricing while keeping legacy Stripe top-ups on Checkout', () => { - mockFlags.teamWorkspacesEnabled = true - mockFlags.consolidatedBillingEnabled = true mockActiveWorkspace.value = personal mockActiveWorkspaceBillingRail.value = 'legacy_stripe' @@ -90,8 +74,6 @@ describe('useBillingRouting', () => { }) it('uses workspace billing for migrated Stripe personal workspaces', () => { - mockFlags.teamWorkspacesEnabled = true - mockFlags.consolidatedBillingEnabled = true mockActiveWorkspace.value = personal mockActiveWorkspaceBillingRail.value = 'stripe' @@ -101,9 +83,7 @@ describe('useBillingRouting', () => { expect(shouldUseWorkspaceBilling.value).toBe(true) }) - it('uses workspace billing for team workspaces regardless of consolidated billing', () => { - mockFlags.teamWorkspacesEnabled = true - mockFlags.consolidatedBillingEnabled = false + it('uses workspace billing for team workspaces', () => { mockActiveWorkspace.value = team mockActiveWorkspaceBillingRail.value = 'legacy_stripe' @@ -113,21 +93,7 @@ describe('useBillingRouting', () => { expect(shouldUseWorkspaceBilling.value).toBe(true) }) - it('uses workspace billing for team workspaces with consolidated billing enabled', () => { - mockFlags.teamWorkspacesEnabled = true - mockFlags.consolidatedBillingEnabled = true - mockActiveWorkspace.value = team - mockActiveWorkspaceBillingRail.value = 'stripe' - - const { type, shouldUseWorkspaceBilling } = useBillingRouting() - - expect(type.value).toBe('workspace') - expect(shouldUseWorkspaceBilling.value).toBe(true) - }) - it('defaults to legacy while the workspace has not loaded', () => { - mockFlags.teamWorkspacesEnabled = true - mockFlags.consolidatedBillingEnabled = true mockActiveWorkspace.value = null const { type } = useBillingRouting() diff --git a/src/composables/billing/useBillingRouting.ts b/src/composables/billing/useBillingRouting.ts index 6a3cee5e84c..155ce553849 100644 --- a/src/composables/billing/useBillingRouting.ts +++ b/src/composables/billing/useBillingRouting.ts @@ -1,6 +1,6 @@ import { computed } from 'vue' -import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { isCloud } from '@/platform/distribution/types' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import type { BillingType } from './types' @@ -8,27 +8,20 @@ import type { BillingType } from './types' /** * Selects the billing backend for the active workspace: legacy user-scoped * (`/customers/*`) or workspace-scoped (`/api/billing/*`). Personal workspaces - * stay legacy until `consolidatedBillingEnabled`, and known legacy Stripe - * workspaces remain legacy after it is enabled. An unknown rail keeps the - * flag-based route so workspace status can load it. Team workspaces are always - * workspace-scoped. Pricing follows feature availability independently of the - * billing rail. The routing matrix is covered in useBillingRouting.test.ts. + * use workspace-scoped billing unless they are explicitly on the legacy Stripe + * rail. An unloaded workspace remains legacy during bootstrap. OSS always uses + * legacy billing. Pricing follows Cloud workspace availability independently + * of the billing rail. */ export function useBillingRouting() { - const { flags } = useFeatureFlags() const workspaceStore = useTeamWorkspaceStore() const shouldUseUnifiedPricing = computed(() => { - if (!flags.teamWorkspacesEnabled) return false - - const workspaceType = workspaceStore.activeWorkspace?.type - if (!workspaceType) return false - - return workspaceType === 'team' || flags.consolidatedBillingEnabled + return isCloud && workspaceStore.activeWorkspace?.type !== undefined }) const type = computed(() => { - if (!flags.teamWorkspacesEnabled) return 'legacy' + if (!isCloud) return 'legacy' // An unloaded workspace has no type yet; stay legacy so bootstrap never // eagerly routes to workspace billing. @@ -37,8 +30,7 @@ export function useBillingRouting() { if ( workspaceType === 'personal' && - (!flags.consolidatedBillingEnabled || - workspaceStore.activeWorkspaceBillingRail === 'legacy_stripe') + workspaceStore.activeWorkspaceBillingRail === 'legacy_stripe' ) { return 'legacy' } diff --git a/src/composables/billing/useLegacyBilling.ts b/src/composables/billing/useLegacyBilling.ts index d238d25b227..8e72acfe947 100644 --- a/src/composables/billing/useLegacyBilling.ts +++ b/src/composables/billing/useLegacyBilling.ts @@ -59,7 +59,7 @@ export function useLegacyBilling(): BillingState & BillingActions { duration: subscriptionDuration.value, planSlug: null, // Legacy doesn't use plan slugs renewalDate: legacySubscriptionStatus.value?.renewal_date ?? null, - endDate: legacySubscriptionStatus.value?.end_date ?? null, + endDate: legacySubscriptionStatus.value?.cancel_at ?? null, isCancelled: isCancelled.value, hasFunds: (authStore.balance?.amount_micros ?? 0) > 0 } diff --git a/src/composables/useFeatureFlags.test.ts b/src/composables/useFeatureFlags.test.ts index 8b7fabeba63..efe441cc356 100644 --- a/src/composables/useFeatureFlags.test.ts +++ b/src/composables/useFeatureFlags.test.ts @@ -8,8 +8,6 @@ import { import * as distributionTypes from '@/platform/distribution/types' import { cachedBillingControlEnabled, - cachedConsolidatedBillingEnabled, - cachedTeamWorkspacesEnabled, remoteConfig, remoteConfigState } from '@/platform/remoteConfig/remoteConfig' @@ -243,14 +241,6 @@ describe('useFeatureFlags', () => { expect(flags.supportsPreviewMetadata).toBe('overridden') }) - it('teamWorkspacesEnabled override bypasses isCloud and isAuthenticatedConfigLoaded guards', () => { - vi.mocked(distributionTypes).isCloud = false - localStorage.setItem('ff:team_workspaces_enabled', 'true') - - const { flags } = useFeatureFlags() - expect(flags.teamWorkspacesEnabled).toBe(true) - }) - it('billingControlEnabled override bypasses isCloud and isAuthenticatedConfigLoaded guards', () => { vi.mocked(distributionTypes).isCloud = false localStorage.setItem('ff:billing_control_enabled', 'true') @@ -259,20 +249,11 @@ describe('useFeatureFlags', () => { expect(flags.billingControlEnabled).toBe(true) }) - it('consolidatedBillingEnabled override bypasses isCloud and isAuthenticatedConfigLoaded guards', () => { - vi.mocked(distributionTypes).isCloud = false - localStorage.setItem('ff:consolidated_billing_enabled', 'true') - - const { flags } = useFeatureFlags() - expect(flags.consolidatedBillingEnabled).toBe(true) - }) - it('billingControlEnabled is false off-cloud even without an override', () => { vi.mocked(distributionTypes).isCloud = false const { flags } = useFeatureFlags() expect(flags.billingControlEnabled).toBe(false) - expect(flags.consolidatedBillingEnabled).toBe(false) }) }) @@ -281,8 +262,6 @@ describe('useFeatureFlags', () => { vi.mocked(distributionTypes).isCloud = true remoteConfigState.value = 'unloaded' remoteConfig.value = {} - cachedTeamWorkspacesEnabled.value = undefined - cachedConsolidatedBillingEnabled.value = undefined cachedBillingControlEnabled.value = undefined localStorage.clear() }) @@ -291,42 +270,30 @@ describe('useFeatureFlags', () => { vi.mocked(distributionTypes).isCloud = false remoteConfigState.value = 'unloaded' remoteConfig.value = {} - cachedTeamWorkspacesEnabled.value = undefined - cachedConsolidatedBillingEnabled.value = undefined cachedBillingControlEnabled.value = undefined localStorage.clear() }) it('returns the cached session value during the auth window', () => { - cachedTeamWorkspacesEnabled.value = false - cachedConsolidatedBillingEnabled.value = true cachedBillingControlEnabled.value = true const { flags } = useFeatureFlags() - expect(flags.teamWorkspacesEnabled).toBe(false) - expect(flags.consolidatedBillingEnabled).toBe(true) expect(flags.billingControlEnabled).toBe(true) }) it('defaults to false during the auth window when nothing is cached', () => { const { flags } = useFeatureFlags() - expect(flags.teamWorkspacesEnabled).toBe(false) - expect(flags.consolidatedBillingEnabled).toBe(false) expect(flags.billingControlEnabled).toBe(false) }) it('prefers authenticated remoteConfig over the server feature fallback', () => { remoteConfigState.value = 'authenticated' remoteConfig.value = { - team_workspaces_enabled: true, - consolidated_billing_enabled: true, billing_control_enabled: false } vi.mocked(api.getServerFeature).mockReturnValue(false) const { flags } = useFeatureFlags() - expect(flags.teamWorkspacesEnabled).toBe(true) - expect(flags.consolidatedBillingEnabled).toBe(true) expect(flags.billingControlEnabled).toBe(false) }) @@ -335,17 +302,12 @@ describe('useFeatureFlags', () => { remoteConfig.value = {} vi.mocked(api.getServerFeature).mockImplementation( (path, defaultValue) => { - if (path === ServerFeatureFlag.TEAM_WORKSPACES_ENABLED) return true - if (path === ServerFeatureFlag.CONSOLIDATED_BILLING_ENABLED) - return true if (path === ServerFeatureFlag.BILLING_CONTROL_ENABLED) return true return defaultValue } ) const { flags } = useFeatureFlags() - expect(flags.teamWorkspacesEnabled).toBe(true) - expect(flags.consolidatedBillingEnabled).toBe(true) expect(flags.billingControlEnabled).toBe(true) }) }) diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index 57f41ad183a..f0f36f9cd99 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -4,8 +4,6 @@ import type { Ref } from 'vue' import { isCloud, isNightly } from '@/platform/distribution/types' import { cachedBillingControlEnabled, - cachedConsolidatedBillingEnabled, - cachedTeamWorkspacesEnabled, isAuthenticatedConfigLoaded, remoteConfig } from '@/platform/remoteConfig/remoteConfig' @@ -24,7 +22,6 @@ export enum ServerFeatureFlag { PRIVATE_MODELS_ENABLED = 'private_models_enabled', ONBOARDING_SURVEY_ENABLED = 'onboarding_survey_enabled', LINEAR_TOGGLE_ENABLED = 'linear_toggle_enabled', - TEAM_WORKSPACES_ENABLED = 'team_workspaces_enabled', PARTNER_NODE_GOVERNANCE_ENABLED = 'partner_node_governance_enabled', USER_SECRETS_ENABLED = 'user_secrets_enabled', NODE_REPLACEMENTS = 'node_replacements', @@ -34,7 +31,6 @@ export enum ServerFeatureFlag { COMFYHUB_PROFILE_GATE_ENABLED = 'comfyhub_profile_gate_enabled', SHOW_SIGNIN_BUTTON = 'show_signin_button', UNIFIED_CLOUD_AUTH = 'unified_cloud_auth', - CONSOLIDATED_BILLING_ENABLED = 'consolidated_billing_enabled', BILLING_CONTROL_ENABLED = 'billing_control_enabled', FREE_TIER_JOB_ALLOWANCE_ENABLED = 'free_tier_job_allowance_enabled', CHURNKEY_APP_ID = 'churnkey_app_id', @@ -126,19 +122,6 @@ export function useFeatureFlags() { false ) }, - /** - * Whether team workspaces feature is enabled. - * IMPORTANT: Returns false until authenticated remote config is loaded. - * This ensures we never use workspace tokens when the feature is disabled, - * and prevents race conditions during initialization. - */ - get teamWorkspacesEnabled() { - return resolveAuthGatedFlag( - ServerFeatureFlag.TEAM_WORKSPACES_ENABLED, - remoteConfig.value.team_workspaces_enabled, - cachedTeamWorkspacesEnabled - ) - }, get partnerNodeGovernanceEnabled() { return resolveFlag( ServerFeatureFlag.PARTNER_NODE_GOVERNANCE_ENABLED, @@ -203,18 +186,6 @@ export function useFeatureFlags() { false ) }, - /** - * Whether personal workspaces use the consolidated (workspace-scoped) - * billing flow. While false (default), personal workspaces stay on the - * legacy per-user billing flow; team workspaces are unaffected. - */ - get consolidatedBillingEnabled() { - return resolveAuthGatedFlag( - ServerFeatureFlag.CONSOLIDATED_BILLING_ENABLED, - remoteConfig.value.consolidated_billing_enabled, - cachedConsolidatedBillingEnabled - ) - }, get billingControlEnabled() { return resolveAuthGatedFlag( ServerFeatureFlag.BILLING_CONTROL_ENABLED, diff --git a/src/composables/useUrlActionLoaders.test.ts b/src/composables/useUrlActionLoaders.test.ts index 9d99e620565..bb8304fb583 100644 --- a/src/composables/useUrlActionLoaders.test.ts +++ b/src/composables/useUrlActionLoaders.test.ts @@ -9,11 +9,6 @@ vi.mock('@/platform/distribution/types', () => ({ } })) -const mockFlags = vi.hoisted(() => ({ value: { teamWorkspacesEnabled: true } })) -vi.mock('@/composables/useFeatureFlags', () => ({ - useFeatureFlags: () => ({ flags: mockFlags.value }) -})) - const mocks = vi.hoisted(() => ({ loadInvite: vi.fn().mockResolvedValue(undefined), loadCreateWorkspace: vi.fn().mockResolvedValue(undefined), @@ -47,7 +42,6 @@ describe('useUrlActionLoaders', () => { beforeEach(() => { vi.clearAllMocks() mockIsCloud.value = true - mockFlags.value = { teamWorkspacesEnabled: true } }) it('does not instantiate or run any loader off cloud', async () => { @@ -64,7 +58,7 @@ describe('useUrlActionLoaders', () => { expect(mocks.loadPricingTable).not.toHaveBeenCalled() }) - it('runs all loaders on cloud when team workspaces are enabled', async () => { + it('runs all loaders on Cloud', async () => { const { runUrlActionLoaders } = useUrlActionLoaders() await runUrlActionLoaders() @@ -73,17 +67,6 @@ describe('useUrlActionLoaders', () => { expect(mocks.loadPricingTable).toHaveBeenCalledOnce() }) - it('runs the pricing loader but skips the flag-gated loaders when team workspaces are disabled', async () => { - mockFlags.value = { teamWorkspacesEnabled: false } - - const { runUrlActionLoaders } = useUrlActionLoaders() - await runUrlActionLoaders() - - expect(mocks.loadInvite).not.toHaveBeenCalled() - expect(mocks.loadCreateWorkspace).not.toHaveBeenCalled() - expect(mocks.loadPricingTable).toHaveBeenCalledOnce() - }) - it('isolates a pricing-loader failure so it does not abort the boot chain', async () => { mocks.loadPricingTable.mockRejectedValueOnce(new Error('boom')) diff --git a/src/composables/useUrlActionLoaders.ts b/src/composables/useUrlActionLoaders.ts index c27ab8351e1..dd243267012 100644 --- a/src/composables/useUrlActionLoaders.ts +++ b/src/composables/useUrlActionLoaders.ts @@ -1,4 +1,3 @@ -import { useFeatureFlags } from '@/composables/useFeatureFlags' import { usePricingTableUrlLoader } from '@/platform/cloud/subscription/composables/usePricingTableUrlLoader' import { isCloud } from '@/platform/distribution/types' import { useCreateWorkspaceUrlLoader } from '@/platform/workspace/composables/useCreateWorkspaceUrlLoader' @@ -11,7 +10,6 @@ import { useInviteUrlLoader } from '@/platform/workspace/composables/useInviteUr * from `onMounted` once the app is ready. */ export function useUrlActionLoaders() { - const { flags } = useFeatureFlags() const inviteUrlLoader = isCloud ? useInviteUrlLoader() : null const createWorkspaceUrlLoader = isCloud ? useCreateWorkspaceUrlLoader() @@ -20,13 +18,12 @@ export function useUrlActionLoaders() { async function runUrlActionLoaders() { // Accept workspace invite from URL if present (e.g., ?invite=TOKEN). - // WorkspaceAuthGate ensures flag state is resolved before the app mounts. - if (inviteUrlLoader && flags.teamWorkspacesEnabled) { + if (inviteUrlLoader) { await inviteUrlLoader.loadInviteFromUrl() } // Open create workspace dialog from URL if present (e.g., ?create_workspace=1). - if (createWorkspaceUrlLoader && flags.teamWorkspacesEnabled) { + if (createWorkspaceUrlLoader) { try { await createWorkspaceUrlLoader.loadCreateWorkspaceFromUrl() } catch (error) { @@ -38,7 +35,6 @@ export function useUrlActionLoaders() { } // Open the pricing table from URL if present (e.g., ?pricing=1 / ?pricing=team). - // Not gated on the team-workspaces flag: it also drives personal/legacy users. if (pricingTableUrlLoader) { try { await pricingTableUrlLoader.loadPricingTableFromUrl() diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 4ac2451e79d..35850eb2cc3 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -4606,6 +4606,9 @@ "switchFailed": "Failed to switch workspace. Please try again." }, "workspaceAuth": { + "initializationFailed": "Couldn't load your workspace", + "initializationFailedDetail": "Check your connection and try again.", + "retry": "Try again", "errors": { "notAuthenticated": "You must be logged in to access workspaces", "invalidFirebaseToken": "Authentication failed. Please try logging in again.", diff --git a/src/platform/auth/session/useSessionCookie.test.ts b/src/platform/auth/session/useSessionCookie.test.ts index f526ce62ed9..56c3aa383d1 100644 --- a/src/platform/auth/session/useSessionCookie.test.ts +++ b/src/platform/auth/session/useSessionCookie.test.ts @@ -5,19 +5,12 @@ const mockGetAuthHeader = vi.fn() const mockAuthState = vi.hoisted(() => ({ currentUser: { uid: 'user-a' } as { uid: string } | null })) -const mockFlags = vi.hoisted(() => ({ teamWorkspacesEnabled: true })) const originalFetch = globalThis.fetch vi.mock('@/platform/distribution/types', () => ({ isCloud: true })) -vi.mock('@/composables/useFeatureFlags', () => ({ - useFeatureFlags: () => ({ - flags: mockFlags - }) -})) - vi.mock('@/stores/authStore', () => ({ useAuthStore: () => ({ getIdToken: mockGetIdToken, @@ -41,7 +34,6 @@ describe('useSessionCookie', () => { mockGetIdToken.mockReset() mockGetAuthHeader.mockReset() mockAuthState.currentUser = { uid: 'user-a' } - mockFlags.teamWorkspacesEnabled = true globalThis.fetch = vi.fn() }) @@ -209,7 +201,6 @@ describe('useSessionCookie', () => { }) it('does not let strict Firebase creation join a weaker request', async () => { - mockFlags.teamWorkspacesEnabled = false mockGetAuthHeader.mockResolvedValue(null) mockGetIdToken.mockResolvedValue('firebase-id-token') vi.mocked(globalThis.fetch).mockResolvedValue( diff --git a/src/platform/auth/session/useSessionCookie.ts b/src/platform/auth/session/useSessionCookie.ts index 5e09e5da30b..75d11b1915d 100644 --- a/src/platform/auth/session/useSessionCookie.ts +++ b/src/platform/auth/session/useSessionCookie.ts @@ -1,4 +1,3 @@ -import { useFeatureFlags } from '@/composables/useFeatureFlags' import { isCloud } from '@/platform/distribution/types' import { api } from '@/scripts/api' import { useAuthStore } from '@/stores/authStore' @@ -41,10 +40,9 @@ export const useSessionCookie = () => { const getSessionHeaderOrThrow = async ( useFirebaseToken: boolean ): Promise> => { - const { flags } = useFeatureFlags() const authStore = useAuthStore() - if (useFirebaseToken || flags.teamWorkspacesEnabled) { + if (isCloud || useFirebaseToken) { const firebaseToken = await authStore.getIdToken() if (!firebaseToken) { throw new Error('No Firebase token available for session creation') @@ -60,14 +58,7 @@ export const useSessionCookie = () => { return authHeader } - /** - * Creates or refreshes the session cookie. - * Called after login and on token refresh. - * - * When team_workspaces_enabled is true, uses Firebase token directly - * (since getAuthHeader() returns workspace token which shouldn't be used for session creation). - * When disabled, uses getAuthHeader() for backward compatibility. - */ + /** Creates or refreshes the session cookie after login or token refresh. */ const performCreateSession = async ( expectedOwnerUid: string, useFirebaseToken: boolean @@ -91,6 +82,7 @@ export const useSessionCookie = () => { forceRefresh: boolean, useFirebaseToken = false ): Promise => { + const usesFirebaseToken = isCloud || useFirebaseToken if ( !forceRefresh && pendingSessionMutations === 0 && @@ -100,7 +92,7 @@ export const useSessionCookie = () => { } if ( inFlightCreateSession?.ownerUid === ownerUid && - (!useFirebaseToken || inFlightCreateSession.usesFirebaseToken) + (!usesFirebaseToken || inFlightCreateSession.usesFirebaseToken) ) { return inFlightCreateSession.promise } @@ -108,13 +100,13 @@ export const useSessionCookie = () => { pendingSessionMutations++ const request: InFlightCreateSession = { ownerUid, - usesFirebaseToken: useFirebaseToken, + usesFirebaseToken, promise: sessionMutationTail .then(async () => { if ((useAuthStore().currentUser?.uid ?? null) !== ownerUid) { throw new Error('Session identity changed before creation') } - await performCreateSession(ownerUid, useFirebaseToken) + await performCreateSession(ownerUid, usesFirebaseToken) confirmedSessionOwnerUid = ownerUid if ((useAuthStore().currentUser?.uid ?? null) !== ownerUid) { throw new Error('Session identity changed during creation') diff --git a/src/platform/cloud/subscription/composables/useSubscription.test.ts b/src/platform/cloud/subscription/composables/useSubscription.test.ts index dde6e8d6b1b..26ba9cbc8dc 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.test.ts @@ -15,11 +15,13 @@ const { mockUserId, mockIsCloud, mockAuthStoreInitialized, + mockGetBillingStatus, mockLocalStorage } = vi.hoisted(() => ({ mockIsLoggedIn: { value: false }, mockIsCloud: { value: true }, mockAuthStoreInitialized: { value: true }, + mockGetBillingStatus: vi.fn(), mockReportError: vi.fn(), mockAccessBillingPortal: vi.fn(), mockShowSubscriptionRequiredDialog: vi.fn(), @@ -134,6 +136,12 @@ vi.mock('@/platform/telemetry/utils/checkoutAttribution', () => ({ getCheckoutAttribution: mockGetCheckoutAttribution })) +vi.mock('@/platform/workspace/api/workspaceApi', () => ({ + workspaceApi: { + getBillingStatus: mockGetBillingStatus + } +})) + vi.mock('@/services/dialogService', () => ({ useDialogService: vi.fn(() => ({ showSubscriptionRequiredDialog: mockShowSubscriptionRequiredDialog @@ -181,6 +189,11 @@ describe('useSubscription', () => { mockUserId.value = 'user-123' mockIsCloud.value = true mockAuthStoreInitialized.value = true + mockGetBillingStatus.mockResolvedValue({ + is_active: false, + has_funds: false, + team_credit_stop: null + }) window.__CONFIG__ = { subscription_required: true } as typeof window.__CONFIG__ @@ -196,14 +209,11 @@ describe('useSubscription', () => { describe('computed properties', () => { it('should compute isActiveSubscription correctly when subscription is active', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_123', - renewal_date: '2025-11-16' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + renewal_date: '2025-11-16' + }) mockIsLoggedIn.value = true const { isActiveSubscription, fetchStatus } = useSubscriptionWithScope() @@ -213,14 +223,11 @@ describe('useSubscription', () => { }) it('should compute isActiveSubscription as false when subscription is inactive', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: false, - subscription_id: 'sub_123', - renewal_date: '2025-11-16' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: false, + has_funds: true, + renewal_date: '2025-11-16' + }) mockIsLoggedIn.value = true const { isActiveSubscription, fetchStatus } = useSubscriptionWithScope() @@ -230,14 +237,11 @@ describe('useSubscription', () => { }) it('should format renewal date correctly', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_123', - renewal_date: '2025-11-16T12:00:00Z' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + renewal_date: '2025-11-16T12:00:00Z' + }) mockIsLoggedIn.value = true const { formattedRenewalDate, fetchStatus } = useSubscriptionWithScope() @@ -256,15 +260,12 @@ describe('useSubscription', () => { }) it('should return subscription tier from status', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_123', - subscription_tier: 'CREATOR', - renewal_date: '2025-11-16T12:00:00Z' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + subscription_tier: 'CREATOR', + renewal_date: '2025-11-16T12:00:00Z' + }) mockIsLoggedIn.value = true const { subscriptionTier, fetchStatus } = useSubscriptionWithScope() @@ -284,36 +285,25 @@ describe('useSubscription', () => { it('should fetch subscription status successfully', async () => { const mockStatus = { is_active: true, - subscription_id: 'sub_123', - renewal_date: '2025-11-16' + has_funds: true, + renewal_date: '2025-11-16', + team_credit_stop: null } - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => mockStatus - } as Response) + mockGetBillingStatus.mockResolvedValue(mockStatus) mockIsLoggedIn.value = true const { fetchStatus } = useSubscriptionWithScope() await fetchStatus() - expect(global.fetch).toHaveBeenCalledWith( - expect.stringContaining('/customers/cloud-subscription-status'), - expect.objectContaining({ - headers: expect.objectContaining({ - Authorization: 'Bearer test-token', - 'Content-Type': 'application/json' - }) - }) - ) + expect(mockGetBillingStatus).toHaveBeenCalledOnce() }) it('should handle fetch errors gracefully', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: false, - json: async () => ({ message: 'Subscription not found' }) - } as Response) + mockGetBillingStatus.mockRejectedValue( + new Error('Subscription not found') + ) const { fetchStatus } = useSubscriptionWithScope() @@ -321,38 +311,35 @@ describe('useSubscription', () => { }) it('coalesces concurrent callers into one fetch', async () => { - let resolveFetch: (value: Response) => void = () => {} - vi.mocked(global.fetch).mockReturnValue( - new Promise((resolve) => { - resolveFetch = resolve + let resolveStatus: (value: { + is_active: boolean + has_funds: boolean + }) => void = () => {} + mockGetBillingStatus.mockReturnValue( + new Promise((resolve) => { + resolveStatus = resolve }) ) const { fetchStatus } = useSubscriptionWithScope() const first = fetchStatus() const second = fetchStatus() - resolveFetch({ - ok: true, - json: async () => ({ is_active: true }) - } as Response) + resolveStatus({ is_active: true, has_funds: true }) await Promise.all([first, second]) - expect(global.fetch).toHaveBeenCalledTimes(1) + expect(mockGetBillingStatus).toHaveBeenCalledTimes(1) }) it('does not downgrade known-good status on a failed fetch', async () => { - vi.mocked(global.fetch).mockResolvedValueOnce({ - ok: true, - json: async () => ({ is_active: true, subscription_id: 'sub_1' }) - } as Response) + mockGetBillingStatus.mockResolvedValueOnce({ + is_active: true, + has_funds: true + }) const { fetchStatus, isActiveSubscription } = useSubscriptionWithScope() await fetchStatus() expect(isActiveSubscription.value).toBe(true) - vi.mocked(global.fetch).mockResolvedValueOnce({ - ok: false, - json: async () => ({ message: 'Invalid token' }) - } as Response) + mockGetBillingStatus.mockRejectedValueOnce(new Error('Invalid token')) await fetchStatus().catch(() => {}) expect(isActiveSubscription.value).toBe(true) @@ -432,16 +419,13 @@ describe('useSubscription', () => { }) ) - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_123', - subscription_tier: 'CREATOR', - subscription_duration: 'ANNUAL', - renewal_date: '2025-11-16' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + subscription_tier: 'CREATOR', + subscription_duration: 'ANNUAL', + renewal_date: '2025-11-16' + }) mockIsLoggedIn.value = true useSubscriptionWithScope() @@ -480,16 +464,13 @@ describe('useSubscription', () => { }) ) - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_123', - subscription_tier: 'PRO', - subscription_duration: 'MONTHLY', - renewal_date: '2025-11-16' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + subscription_tier: 'PRO', + subscription_duration: 'MONTHLY', + renewal_date: '2025-11-16' + }) mockIsLoggedIn.value = true useSubscriptionWithScope() @@ -510,25 +491,14 @@ describe('useSubscription', () => { }) }) - it('rechecks pending checkout attempts when the document becomes visible', async () => { - mockIsLoggedIn.value = true - - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: false, - subscription_id: '', - renewal_date: '' - }) - } as Response) - - useSubscriptionWithScope() - - await vi.waitFor(() => { - expect(global.fetch).toHaveBeenCalledTimes(1) + it('rechecks pending checkout attempts on status refresh', async () => { + mockGetBillingStatus.mockResolvedValue({ + is_active: false, + has_funds: false, + renewal_date: '' }) - vi.mocked(global.fetch).mockClear() + const { fetchStatus } = useSubscriptionWithScope() localStorage.setItem( PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY, JSON.stringify({ @@ -540,10 +510,10 @@ describe('useSubscription', () => { }) ) - document.dispatchEvent(new Event('visibilitychange')) + await fetchStatus() await vi.waitFor(() => { - expect(global.fetch).toHaveBeenCalledTimes(1) + expect(mockGetBillingStatus).toHaveBeenCalledTimes(1) }) }) @@ -596,14 +566,11 @@ describe('useSubscription', () => { describe('requireActiveSubscription', () => { it('should not show dialog when subscription is active', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_123', - renewal_date: '2025-11-16' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + renewal_date: '2025-11-16' + }) const { requireActiveSubscription } = useSubscriptionWithScope() @@ -613,14 +580,11 @@ describe('useSubscription', () => { }) it('should show dialog when subscription is inactive', async () => { - vi.mocked(global.fetch).mockResolvedValue({ - ok: true, - json: async () => ({ - is_active: false, - subscription_id: 'sub_123', - renewal_date: '2025-11-16' - }) - } as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: false, + has_funds: true, + renewal_date: '2025-11-16' + }) const { requireActiveSubscription } = useSubscriptionWithScope() @@ -649,6 +613,16 @@ describe('useSubscription', () => { expect(isActiveSubscription.value).toBe(true) }) + + it('does not perform explicit subscription status reads outside Cloud', async () => { + mockIsCloud.value = false + const { fetchStatus } = useSubscriptionWithScope() + + await fetchStatus() + + expect(mockGetBillingStatus).not.toHaveBeenCalled() + expect(global.fetch).not.toHaveBeenCalled() + }) }) describe('action handlers', () => { @@ -705,27 +679,22 @@ describe('useSubscription', () => { mockIsLoggedIn.value = true mockAccessBillingPortal.mockResolvedValueOnce(false) - const activeResponse = { - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_active', - renewal_date: '2025-11-16' - }) - } - - vi.mocked(global.fetch).mockResolvedValue(activeResponse as Response) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + renewal_date: '2025-11-16' + }) try { const { fetchStatus, manageSubscription } = useSubscriptionWithScope() await fetchStatus() - vi.mocked(global.fetch).mockClear() + mockGetBillingStatus.mockClear() await manageSubscription() await vi.advanceTimersByTimeAsync(5000) - expect(global.fetch).not.toHaveBeenCalled() + expect(mockGetBillingStatus).not.toHaveBeenCalled() expect( mockTelemetry.trackMonthlySubscriptionCancelled ).not.toHaveBeenCalled() @@ -738,28 +707,22 @@ describe('useSubscription', () => { vi.useFakeTimers() mockIsLoggedIn.value = true - const activeResponse = { - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_active', - renewal_date: '2025-11-16' - }) + const activeStatus = { + is_active: true, + has_funds: true, + renewal_date: '2025-11-16' } - const cancelledResponse = { - ok: true, - json: async () => ({ - is_active: false, - subscription_id: 'sub_cancelled', - renewal_date: '2025-11-16', - end_date: '2025-12-01' - }) + const cancelledStatus = { + is_active: false, + has_funds: true, + renewal_date: '2025-11-16', + cancel_at: '2025-12-01' } - vi.mocked(global.fetch) - .mockResolvedValueOnce(activeResponse as Response) - .mockResolvedValueOnce(cancelledResponse as Response) + mockGetBillingStatus + .mockResolvedValueOnce(activeStatus) + .mockResolvedValueOnce(cancelledStatus) try { const { fetchStatus, manageSubscription } = useSubscriptionWithScope() @@ -781,28 +744,22 @@ describe('useSubscription', () => { vi.useFakeTimers() mockIsLoggedIn.value = true - const activeResponse = { - ok: true, - json: async () => ({ - is_active: true, - subscription_id: 'sub_active', - renewal_date: '2025-11-16' - }) + const activeStatus = { + is_active: true, + has_funds: true, + renewal_date: '2025-11-16' } - const cancelledResponse = { - ok: true, - json: async () => ({ - is_active: false, - subscription_id: 'sub_cancelled', - renewal_date: '2025-11-16', - end_date: '2025-12-01' - }) + const cancelledStatus = { + is_active: false, + has_funds: true, + renewal_date: '2025-11-16', + cancel_at: '2025-12-01' } - vi.mocked(global.fetch) - .mockResolvedValueOnce(activeResponse as Response) - .mockResolvedValueOnce(cancelledResponse as Response) + mockGetBillingStatus + .mockResolvedValueOnce(activeStatus) + .mockResolvedValueOnce(cancelledStatus) try { const { fetchStatus, manageSubscription } = useSubscriptionWithScope() diff --git a/src/platform/cloud/subscription/composables/useSubscription.ts b/src/platform/cloud/subscription/composables/useSubscription.ts index 0312d94eed5..50af11b5d31 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.ts @@ -17,6 +17,8 @@ import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { SubscriptionDialogOptions } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import type { CheckoutAttributionMetadata } from '@/platform/telemetry/types' +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' +import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { AuthStoreError, useAuthStore } from '@/stores/authStore' import { useDialogService } from '@/services/dialogService' import { TIER_TO_KEY } from '@/platform/cloud/subscription/constants/tierPricing' @@ -35,14 +37,10 @@ type CloudSubscriptionCheckoutResponse = NonNullable< operations['createCloudSubscriptionCheckout']['responses']['201']['content']['application/json'] > -export type CloudSubscriptionStatusResponse = NonNullable< - operations['GetCloudSubscriptionStatus']['responses']['200']['content']['application/json'] -> - const PENDING_SUBSCRIPTION_CHECKOUT_RETRY_DELAYS_MS = [3000, 10000, 30000] function useSubscriptionInternal() { - const subscriptionStatus = ref(null) + const subscriptionStatus = ref(null) const telemetry = useTelemetry() const isInitialized = ref(false) @@ -62,7 +60,7 @@ function useSubscriptionInternal() { const { isLoggedIn } = useCurrentUser() const isCancelled = computed(() => { - return !!subscriptionStatus.value?.end_date + return !!subscriptionStatus.value?.cancel_at }) const formattedRenewalDate = computed(() => { @@ -78,9 +76,9 @@ function useSubscriptionInternal() { }) const formattedEndDate = computed(() => { - if (!subscriptionStatus.value?.end_date) return '' + if (!subscriptionStatus.value?.cancel_at) return '' - const endDate = new Date(subscriptionStatus.value.end_date) + const endDate = new Date(subscriptionStatus.value.cancel_at) return endDate.toLocaleDateString('en-US', { month: 'short', @@ -169,7 +167,7 @@ function useSubscriptionInternal() { } const syncPendingSubscriptionSuccess = ( - statusData: CloudSubscriptionStatusResponse + statusData: BillingStatusResponse ) => { const metadata = consumePendingSubscriptionCheckoutSuccess(statusData) @@ -314,10 +312,9 @@ function useSubscriptionInternal() { } // Coalesce concurrent callers so an auth/session-rotation burst mints one fetch. - let inFlightStatusFetch: Promise | null = - null + let inFlightStatusFetch: Promise | null = null - async function fetchSubscriptionStatus(): Promise { + async function fetchSubscriptionStatus(): Promise { if (inFlightStatusFetch) return inFlightStatusFetch inFlightStatusFetch = performFetchSubscriptionStatus().finally(() => { inFlightStatusFetch = null @@ -325,27 +322,10 @@ function useSubscriptionInternal() { return inFlightStatusFetch } - async function performFetchSubscriptionStatus(): Promise { - const headers = await buildAuthHeaders() - - const response = await fetchWithUnifiedRemint( - buildApiUrl('/customers/cloud-subscription-status'), - { - headers - }, - isCloud && flags.unifiedCloudAuthEnabled - ) - - if (!response.ok) { - const errorData = await response.json() - throw new AuthStoreError( - t('toastMessages.failedToFetchSubscription', { - error: errorData.message - }) - ) - } + async function performFetchSubscriptionStatus(): Promise { + if (!isCloud) return null - const statusData = await response.json() + const statusData = await workspaceApi.getBillingStatus() subscriptionStatus.value = statusData syncPendingSubscriptionSuccess(statusData) diff --git a/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.test.ts b/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.test.ts index a44564801d9..09c3c7b4c3d 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.test.ts @@ -2,9 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computed, effectScope, ref } from 'vue' import type { EffectScope } from 'vue' -import type { CloudSubscriptionStatusResponse } from '@/platform/cloud/subscription/composables/useSubscription' import { useSubscriptionCancellationWatcher } from '@/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher' import type { TelemetryDispatcher } from '@/platform/telemetry/types' +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' describe('useSubscriptionCancellationWatcher', () => { const trackMonthlySubscriptionCancelled = vi.fn() @@ -15,15 +15,13 @@ describe('useSubscriptionCancellationWatcher', () => { trackMonthlySubscriptionCancelled } - const baseStatus: CloudSubscriptionStatusResponse = { + const baseStatus: BillingStatusResponse = { is_active: true, - subscription_id: 'sub_123', + has_funds: true, renewal_date: '2025-11-16' } - const subscriptionStatus = ref( - baseStatus - ) + const subscriptionStatus = ref(baseStatus) const isActive = ref(true) const isActiveSubscription = computed(() => isActive.value) @@ -68,9 +66,9 @@ describe('useSubscriptionCancellationWatcher', () => { isActive.value = false subscriptionStatus.value = { is_active: false, - subscription_id: 'sub_cancelled', + has_funds: true, renewal_date: '2025-11-16', - end_date: '2025-12-01' + cancel_at: '2025-12-01' } } }) @@ -101,7 +99,7 @@ describe('useSubscriptionCancellationWatcher', () => { subscriptionStatus.value = { ...baseStatus, is_active: false, - end_date: '2025-12-01' + cancel_at: '2025-12-01' } }) diff --git a/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.ts b/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.ts index 01e16606937..d67ba020c11 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionCancellationWatcher.ts @@ -3,17 +3,16 @@ import type { ComputedRef, Ref } from 'vue' import { defaultWindow, useEventListener, useTimeoutFn } from '@vueuse/core' import type { TelemetryDispatcher } from '@/platform/telemetry/types' - -import type { CloudSubscriptionStatusResponse } from './useSubscription' +import type { BillingStatusResponse } from '@/platform/workspace/api/workspaceApi' const MAX_CANCELLATION_ATTEMPTS = 4 const CANCELLATION_BASE_DELAY_MS = 5000 const CANCELLATION_BACKOFF_MULTIPLIER = 3 // 5s, 15s, 45s, 135s intervals type CancellationWatcherOptions = { - fetchStatus: () => Promise + fetchStatus: () => Promise isActiveSubscription: ComputedRef - subscriptionStatus: Ref + subscriptionStatus: Ref telemetry: Pick< TelemetryDispatcher, 'trackMonthlySubscriptionCancelled' diff --git a/src/platform/remoteConfig/refreshRemoteConfig.ts b/src/platform/remoteConfig/refreshRemoteConfig.ts index ba5533764dc..0744b6686e1 100644 --- a/src/platform/remoteConfig/refreshRemoteConfig.ts +++ b/src/platform/remoteConfig/refreshRemoteConfig.ts @@ -1,7 +1,5 @@ import { cachedBillingControlEnabled, - cachedConsolidatedBillingEnabled, - cachedTeamWorkspacesEnabled, remoteConfig, remoteConfigState } from './remoteConfig' @@ -58,12 +56,6 @@ export async function refreshRemoteConfig( remoteConfig.value = config remoteConfigState.value = useAuth ? 'authenticated' : 'anonymous' if (useAuth) { - cachedTeamWorkspacesEnabled.value = Boolean( - config.team_workspaces_enabled - ) - cachedConsolidatedBillingEnabled.value = Boolean( - config.consolidated_billing_enabled - ) cachedBillingControlEnabled.value = Boolean( config.billing_control_enabled ) diff --git a/src/platform/remoteConfig/remoteConfig.ts b/src/platform/remoteConfig/remoteConfig.ts index cf119203087..d333a1f2330 100644 --- a/src/platform/remoteConfig/remoteConfig.ts +++ b/src/platform/remoteConfig/remoteConfig.ts @@ -32,10 +32,7 @@ type RemoteConfigState = 'unloaded' | 'anonymous' | 'authenticated' | 'error' */ export const remoteConfigState = ref('unloaded') -/** - * Whether the authenticated config has been loaded. - * Use this to gate access to user-specific feature flags like teamWorkspacesEnabled. - */ +/** Whether the authenticated config has been loaded. */ export const isAuthenticatedConfigLoaded = computed( () => remoteConfigState.value === 'authenticated' ) @@ -55,16 +52,6 @@ export function configValueOrDefault( return configValue || defaultValue } -export const cachedTeamWorkspacesEnabled = useStorage( - 'team_workspaces_enabled' satisfies `${ServerFeatureFlag.TEAM_WORKSPACES_ENABLED}`, - undefined -) - -export const cachedConsolidatedBillingEnabled = useStorage( - 'consolidated_billing_enabled' satisfies `${ServerFeatureFlag.CONSOLIDATED_BILLING_ENABLED}`, - undefined -) - export const cachedBillingControlEnabled = useStorage( 'billing_control_enabled' satisfies `${ServerFeatureFlag.BILLING_CONTROL_ENABLED}`, undefined diff --git a/src/platform/remoteConfig/types.ts b/src/platform/remoteConfig/types.ts index 8b6109744bb..1100a0470a8 100644 --- a/src/platform/remoteConfig/types.ts +++ b/src/platform/remoteConfig/types.ts @@ -106,7 +106,6 @@ export type RemoteConfig = { /** Full hosted (external) survey URL embedded in the Nodes Manager modal on Cloud. */ manager_survey_url?: string linear_toggle_enabled?: boolean - team_workspaces_enabled?: boolean partner_node_governance_enabled?: boolean user_secrets_enabled?: boolean node_library_essentials_enabled?: boolean @@ -121,7 +120,6 @@ export type RemoteConfig = { comfyhub_upload_enabled?: boolean comfyhub_profile_gate_enabled?: boolean unified_cloud_auth?: boolean - consolidated_billing_enabled?: boolean billing_control_enabled?: boolean churnkey_app_id?: string sentry_dsn?: string diff --git a/src/platform/settings/composables/useSettingUI.test.ts b/src/platform/settings/composables/useSettingUI.test.ts index 8f1cd7ecfaa..3bc95745b6f 100644 --- a/src/platform/settings/composables/useSettingUI.test.ts +++ b/src/platform/settings/composables/useSettingUI.test.ts @@ -16,7 +16,6 @@ const env = vi.hoisted(() => { isCloud: false, isDesktop: false, isLoggedIn: false, - teamWorkspacesEnabled: false, billingControlEnabled: false, authenticatedConfigLoaded: false, partnerNodeGovernanceEnabled: false, @@ -51,9 +50,6 @@ vi.mock('@/composables/billing/useBillingContext', () => ({ vi.mock('@/composables/useFeatureFlags', () => ({ useFeatureFlags: () => ({ flags: { - get teamWorkspacesEnabled() { - return env.state.teamWorkspacesEnabled - }, get billingControlEnabled() { return env.state.billingControlEnabled }, @@ -133,7 +129,6 @@ describe('useSettingUI', () => { isCloud: false, isDesktop: false, isLoggedIn: false, - teamWorkspacesEnabled: false, billingControlEnabled: false, authenticatedConfigLoaded: false, partnerNodeGovernanceEnabled: false, @@ -199,6 +194,15 @@ describe('useSettingUI', () => { expect(defaultCategory.value).toBe(settingCategories.value[0]) }) + it('hides the empty Workspace navigation group for logged-out Cloud users', () => { + env.state.isCloud = true + env.state.isLoggedIn = false + + const { navGroups } = useSettingUI() + + expect(navGroups.value.map(({ title }) => title)).not.toContain('Workspace') + }) + it('gives defaultPanel precedence over scrollToSettingId', () => { const { defaultCategory } = useSettingUI('about', 'Comfy.Locale') expect(defaultCategory.value.key).toBe('about') @@ -209,7 +213,6 @@ describe('useSettingUI', () => { Object.assign(env.state, { isCloud: true, isLoggedIn: true, - teamWorkspacesEnabled: true, authenticatedConfigLoaded: true, isActiveSubscription: true, billingType: 'workspace' @@ -287,7 +290,6 @@ describe('useSettingUI', () => { Object.assign(env.state, { isCloud: true, isLoggedIn: true, - teamWorkspacesEnabled: true, billingControlEnabled: true, authenticatedConfigLoaded: true, partnerNodeGovernanceEnabled: true, @@ -338,11 +340,11 @@ describe('useSettingUI', () => { expect(navKeys(navGroups.value)).not.toContain('workspace-allowlist') }) - it('keeps the legacy plan panel in the legacy layout', () => { - env.state.teamWorkspacesEnabled = false + it('keeps OSS account navigation on the legacy layout', () => { + env.state.isCloud = false const { navGroups } = useSettingUI() - expect(navKeys(navGroups.value)).toContain('subscription') + expect(navKeys(navGroups.value)).toContain('credits') expect(navKeys(navGroups.value)).not.toContain('workspace') }) }) diff --git a/src/platform/settings/composables/useSettingUI.ts b/src/platform/settings/composables/useSettingUI.ts index 60bd2103cab..86d1d68cf81 100644 --- a/src/platform/settings/composables/useSettingUI.ts +++ b/src/platform/settings/composables/useSettingUI.ts @@ -61,10 +61,6 @@ export function useSettingUI( const { isActiveSubscription, type: billingType } = useBillingContext() const { workspaceRole } = useWorkspaceUI() - const teamWorkspacesEnabled = computed( - () => isCloud && flags.teamWorkspacesEnabled - ) - const settingRoot = computed(() => { const root = buildTree( Object.values(settingStore.settingsById).filter( @@ -228,9 +224,7 @@ export function useSettingUI( props: { section: 'allowlist' } } - const shouldShowWorkspacePanel = computed( - () => teamWorkspacesEnabled.value && isLoggedIn.value - ) + const shouldShowWorkspacePanel = computed(() => isCloud && isLoggedIn.value) const shouldShowWorkspaceAllowlist = computed( () => shouldShowWorkspacePanel.value && @@ -348,7 +342,7 @@ export function useSettingUI( ) }) - // Sidebar structure when team workspaces is enabled + // Cloud workspace sidebar structure const workspaceMenuTreeNodes = computed(() => [ // Workspace settings translateCategory({ @@ -394,7 +388,7 @@ export function useSettingUI( : []) ]) - // Sidebar structure when team workspaces is disabled (legacy) + // OSS legacy sidebar structure const legacyMenuTreeNodes = computed(() => [ // Account settings - show different panels based on distribution and auth state { @@ -432,29 +426,29 @@ export function useSettingUI( ]) const groupedMenuTreeNodes = computed(() => - teamWorkspacesEnabled.value - ? workspaceMenuTreeNodes.value - : legacyMenuTreeNodes.value + isCloud ? workspaceMenuTreeNodes.value : legacyMenuTreeNodes.value ) const navGroups = computed(() => - groupedMenuTreeNodes.value.map((group) => ({ - title: - (group as SettingTreeNode & { translatedLabel?: string }) - .translatedLabel ?? group.label, - items: (group.children ?? []).map((child) => ({ - id: child.key, - label: - (child as SettingTreeNode & { translatedLabel?: string }) - .translatedLabel ?? child.label, - icon: - child.key === 'workspace' && billingControlsEnabled.value - ? CATEGORY_ICONS.PlanCredits - : (CATEGORY_ICONS[child.key] ?? - CATEGORY_ICONS[child.label] ?? - 'icon-[lucide--plug]') + groupedMenuTreeNodes.value + .filter((group) => group.children?.length) + .map((group) => ({ + title: + (group as SettingTreeNode & { translatedLabel?: string }) + .translatedLabel ?? group.label, + items: (group.children ?? []).map((child) => ({ + id: child.key, + label: + (child as SettingTreeNode & { translatedLabel?: string }) + .translatedLabel ?? child.label, + icon: + child.key === 'workspace' && billingControlsEnabled.value + ? CATEGORY_ICONS.PlanCredits + : (CATEGORY_ICONS[child.key] ?? + CATEGORY_ICONS[child.label] ?? + 'icon-[lucide--plug]') + })) })) - })) ) function findCategoryByKey(key: string): SettingTreeNode | null { @@ -480,7 +474,6 @@ export function useSettingUI( groupedMenuTreeNodes, settingCategories, navGroups, - teamWorkspacesEnabled, findCategoryByKey, findPanelByKey } diff --git a/src/platform/settings/composables/useSettingsDialog.test.ts b/src/platform/settings/composables/useSettingsDialog.test.ts index a3030709ce3..6d2892f3a51 100644 --- a/src/platform/settings/composables/useSettingsDialog.test.ts +++ b/src/platform/settings/composables/useSettingsDialog.test.ts @@ -7,23 +7,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const showDialog = vi.hoisted(() => vi.fn()) -const teamWorkspacesFlag = vi.hoisted(() => ({ value: false })) const isCloudRef = vi.hoisted(() => ({ value: false })) vi.mock('@/stores/dialogStore', () => ({ useDialogStore: () => ({ showDialog, closeDialog: vi.fn() }) })) -vi.mock('@/composables/useFeatureFlags', () => ({ - useFeatureFlags: () => ({ - flags: { - get teamWorkspacesEnabled() { - return teamWorkspacesFlag.value - } - } - }) -})) - vi.mock('@/platform/distribution/types', () => ({ get isCloud() { return isCloudRef.value @@ -49,7 +38,6 @@ import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDi describe('useSettingsDialog', () => { beforeEach(() => { showDialog.mockReset() - teamWorkspacesFlag.value = false isCloudRef.value = false }) @@ -78,9 +66,8 @@ describe('useSettingsDialog', () => { expect(args.dialogComponentProps.overlayClass).toBeUndefined() }) - it("show() sets overlayClass 'p-8' when isCloud && teamWorkspacesEnabled", () => { + it("show() sets overlayClass 'p-8' on Cloud", () => { isCloudRef.value = true - teamWorkspacesFlag.value = true useSettingsDialog().show() const [args] = showDialog.mock.calls[0] diff --git a/src/platform/settings/composables/useSettingsDialog.ts b/src/platform/settings/composables/useSettingsDialog.ts index cdc257893e8..c39d7b58b89 100644 --- a/src/platform/settings/composables/useSettingsDialog.ts +++ b/src/platform/settings/composables/useSettingsDialog.ts @@ -1,4 +1,3 @@ -import { useFeatureFlags } from '@/composables/useFeatureFlags' import { isCloud } from '@/platform/distribution/types' import { useDialogService } from '@/services/dialogService' import { useDialogStore } from '@/stores/dialogStore' @@ -15,14 +14,12 @@ const SETTINGS_CONTENT_CLASS = export function useSettingsDialog() { const dialogService = useDialogService() const dialogStore = useDialogStore() - const { flags } = useFeatureFlags() function hide() { dialogStore.closeDialog({ key: DIALOG_KEY }) } function show(panel?: SettingPanelType, settingId?: string) { - const isWorkspaceMode = isCloud && flags.teamWorkspacesEnabled dialogService.showLayoutDialog({ key: DIALOG_KEY, component: SettingDialog, @@ -46,7 +43,7 @@ export function useSettingsDialog() { dismissOnFocusOutside: false, size: 'full', contentClass: SETTINGS_CONTENT_CLASS, - overlayClass: isWorkspaceMode ? 'p-8' : undefined + overlayClass: isCloud ? 'p-8' : undefined } }) } diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index e52fde46ab6..0254f243ceb 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -1,8 +1,11 @@ import { render, screen } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vitest' import { ref } from 'vue' import { createI18n } from 'vue-i18n' +import enMessages from '@/locales/en/main.json' with { type: 'json' } + import WorkspaceAuthGate from './WorkspaceAuthGate.vue' async function flushPromises() { @@ -40,14 +43,10 @@ vi.mock('@/platform/remoteConfig/remoteConfig', () => ({ remoteConfigState: mockRemoteConfigState })) -const mockTeamWorkspacesEnabled = vi.hoisted(() => ({ value: false })) const mockUnifiedCloudAuthEnabled = vi.hoisted(() => ({ value: false })) vi.mock('@/composables/useFeatureFlags', () => ({ useFeatureFlags: () => ({ flags: { - get teamWorkspacesEnabled() { - return mockTeamWorkspacesEnabled.value - }, get unifiedCloudAuthEnabled() { return mockUnifiedCloudAuthEnabled.value } @@ -110,7 +109,6 @@ describe('WorkspaceAuthGate', () => { mockIsCloud.value = true mockIsInitialized.value = false mockCurrentUser.value = null - mockTeamWorkspacesEnabled.value = false mockUnifiedCloudAuthEnabled.value = false mockRemoteConfigState.value = 'authenticated' mockWorkspaceStoreInitState.value = 'uninitialized' @@ -123,7 +121,11 @@ describe('WorkspaceAuthGate', () => { mockGetUnifiedToken.mockReturnValue('cloud-jwt') }) - const i18n = createI18n({ legacy: false }) + const i18n = createI18n({ + legacy: false, + locale: 'en', + messages: { en: enMessages } + }) const mountComponent = () => render(WorkspaceAuthGate, { @@ -182,16 +184,6 @@ describe('WorkspaceAuthGate', () => { expect(mockRefreshRemoteConfig).toHaveBeenCalledWith({ useAuth: true }) }) - it('renders slot when teamWorkspacesEnabled is false', async () => { - mockTeamWorkspacesEnabled.value = false - - mountComponent() - await flushPromises() - - expect(screen.getByTestId('slot-content')).toBeInTheDocument() - expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() - }) - it('mints unified auth after refreshing authenticated flags', async () => { mockRefreshRemoteConfig.mockImplementation(async () => { mockUnifiedCloudAuthEnabled.value = true @@ -204,9 +196,7 @@ describe('WorkspaceAuthGate', () => { expect(screen.getByTestId('slot-content')).toBeInTheDocument() }) - it('initializes workspace store when teamWorkspacesEnabled is true', async () => { - mockTeamWorkspacesEnabled.value = true - + it('initializes the workspace store', async () => { mountComponent() await flushPromises() @@ -215,7 +205,6 @@ describe('WorkspaceAuthGate', () => { }) it('calls resumePendingPricingFlow after successful workspace init', async () => { - mockTeamWorkspacesEnabled.value = true mockWorkspaceStoreInitState.value = 'ready' mountComponent() @@ -225,7 +214,6 @@ describe('WorkspaceAuthGate', () => { }) it('skips workspace init when store is already initialized', async () => { - mockTeamWorkspacesEnabled.value = true mockWorkspaceStoreInitState.value = 'ready' mountComponent() @@ -242,14 +230,19 @@ describe('WorkspaceAuthGate', () => { mockCurrentUser.value = { uid: 'user-123' } }) - it('keeps the app gated when remote config refresh fails', async () => { + it('shows a recoverable error when remote config refresh fails', async () => { const error = new Error('Network error') mockRefreshRemoteConfig.mockRejectedValue(error) mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() + expect( + screen.getByRole('button', { name: 'Try again' }) + ).toBeInTheDocument() expect(mockCaptureException).toHaveBeenCalledWith(error, { tags: { error_type: 'workspace_auth_gate_initialization_failure' @@ -257,7 +250,7 @@ describe('WorkspaceAuthGate', () => { }) }) - it('keeps the app gated when remote config refresh times out', async () => { + it('shows a recoverable error when remote config refresh times out', async () => { vi.useFakeTimers() try { // Never-resolving promise simulates a hanging request @@ -268,38 +261,46 @@ describe('WorkspaceAuthGate', () => { // Slot not yet rendered before timeout expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.queryByText("Couldn't load your workspace") + ).not.toBeInTheDocument() // Advance past the 10 second timeout await vi.advanceTimersByTimeAsync(10_001) - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() } finally { vi.useRealTimers() } }) - it('keeps the app gated when authenticated config is unavailable', async () => { + it('shows a recoverable error when authenticated config is unavailable', async () => { mockRemoteConfigState.value = 'error' mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() }) - it('keeps the app gated when unified auth initialization fails', async () => { + it('shows a recoverable error when unified auth initialization fails', async () => { mockUnifiedCloudAuthEnabled.value = true mockMintAtLogin.mockResolvedValue(false) mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() }) - it('keeps the app gated when workspace store initialization fails', async () => { - mockTeamWorkspacesEnabled.value = true + it('shows a recoverable error when workspace store initialization fails', async () => { mockWorkspaceStoreInitialize.mockRejectedValue( new Error('Workspace init failed') ) @@ -307,28 +308,52 @@ describe('WorkspaceAuthGate', () => { mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() }) - it('keeps the app gated when workspace setup clears unified auth', async () => { + it('shows a recoverable error when workspace setup clears unified auth', async () => { mockUnifiedCloudAuthEnabled.value = true - mockTeamWorkspacesEnabled.value = true mockGetUnifiedToken.mockReturnValue(undefined) mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() }) - it('keeps the app gated without a ready workspace context', async () => { - mockTeamWorkspacesEnabled.value = true + it('shows a recoverable error without a ready workspace context', async () => { mockWorkspaceStoreInitState.value = 'loading' mountComponent() await flushPromises() - expect(screen.queryByTestId('slot-content')).not.toBeInTheDocument() + expect( + screen.getByText("Couldn't load your workspace") + ).toBeInTheDocument() + }) + + it('renders the app after retrying a failed initialization', async () => { + const user = userEvent.setup() + mockWorkspaceStoreInitialize + .mockImplementationOnce(async () => { + mockWorkspaceStoreInitState.value = 'error' + throw new Error('Workspace init failed') + }) + .mockImplementationOnce(async () => { + mockWorkspaceStoreInitState.value = 'ready' + }) + + mountComponent() + await flushPromises() + await user.click(screen.getByRole('button', { name: 'Try again' })) + await flushPromises() + + expect(screen.getByTestId('slot-content')).toBeInTheDocument() + expect(mockWorkspaceStoreInitialize).toHaveBeenCalledTimes(2) }) }) }) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index d1bf54388d8..e8165d08e5c 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -1,19 +1,40 @@