diff --git a/.env_example b/.env_example index 025bfba1f1e..d3849d484bf 100644 --- a/.env_example +++ b/.env_example @@ -44,6 +44,8 @@ ALGOLIA_API_KEY=684d998c36b67a9a9fce8fc2d8860579 # Override staging comfy-api / comfy-platform base URLs. # VITE_STAGING_API_BASE_URL=https://stagingapi.comfy.org # VITE_STAGING_PLATFORM_BASE_URL=https://stagingplatform.comfy.org +# VITE_STRIPE_PUBLISHABLE_KEY=pk_test_... +# VITE_STRIPE_PAYMENT_METHOD_CONFIGURATION_ID=pmc_... # Sentry ENV vars replace with real ones for debugging # SENTRY_AUTH_TOKEN=private-token # get from sentry diff --git a/browser_tests/tests/dialogs/checkoutRecovery.spec.ts b/browser_tests/tests/dialogs/checkoutRecovery.spec.ts new file mode 100644 index 00000000000..b311fe82b20 --- /dev/null +++ b/browser_tests/tests/dialogs/checkoutRecovery.spec.ts @@ -0,0 +1,278 @@ +import { expect } from '@playwright/test' +import type { Page, Request } from '@playwright/test' +import type { + BillingOpStatusResponse, + BillingPlansResponse, + BillingStatusResponse, + ErrorResponse, + Plan, + PreviewSubscribeResponse +} from '@comfyorg/ingest-types' + +import type { RemoteConfig } from '@/platform/remoteConfig/types' +import type { PendingSubscriptionCheckout } from '@/platform/workspace/utils/pendingSubscriptionCheckout' + +import { + cloudAppExpect, + cloudAppFixture as test, + waitForCloudApp +} from '@e2e/fixtures/cloudAppFixture' +import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' +import { bootCloud, mockCloudBoot } from '@e2e/fixtures/utils/cloudBootMocks' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { mockWorkspace, workspace } from '@e2e/fixtures/utils/workspaceMocks' + +/** + * A redirect checkout persists its pending billing operation in sessionStorage + * before leaving the app. On the next boot `resumePendingPricingFlow()` + * reconciles that operation: a terminal failure reopens checkout for the + * persisted selection, success stays silent, and an entry for another user or + * workspace is dropped without reconciliation. Drives a raw `page` against + * fully mocked endpoints, like the pricing deep-link spec. + */ +const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' + +const PENDING_CHECKOUT_STORAGE_KEY = 'comfy:pending-subscription-checkout' +const RECOVERY_OPERATION_ID = 'op-e2e-recover' + +const BOOT_FEATURES = { + billing_control_enabled: true +} satisfies RemoteConfig +// Disable the experimental Asset API: with it on (cloud default) the unmocked +// asset endpoints 403 and workflow restore throws uncaught, aborting the +// GraphCanvas onMounted chain before the recovery loader. +const BOOT_SETTINGS = { + 'Comfy.Assets.UseAssetAPI': false, + 'Comfy.TutorialCompleted': true +} + +// ownerUid matches the mocked Firebase uid (CloudAuthHelper) and workspaceId +// the personal workspace the boot mocks resolve as active. +const PENDING_CREATOR_CHECKOUT = { + operationId: RECOVERY_OPERATION_ID, + workspaceId: workspace('personal', 'owner').id, + ownerUid: 'test-user-e2e', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'yearly' + } +} satisfies Omit + +const CREATOR_ANNUAL_PLAN = { + slug: 'creator-annual', + tier: 'CREATOR', + duration: 'ANNUAL', + price_cents: 33_600, + credits_cents: 7_400, + max_seats: 5, + availability: { available: true }, + seat_summary: { + seat_count: 1, + total_cost_cents: 33_600, + total_credits_cents: 7_400 + } +} satisfies Plan + +const LEGACY_ACTIVE_STANDARD_STATUS = { + is_active: true, + subscription_status: 'active', + subscription_tier: 'STANDARD', + subscription_duration: 'ANNUAL', + plan_slug: 'standard-annual', + billing_status: 'paid', + has_funds: true, + renewal_date: '2099-02-20T00:00:00Z', + team_credit_stop: null, + max_seats: 1, + occupied_seats: 1, + billing_rail: 'legacy_stripe' +} satisfies BillingStatusResponse & { billing_rail: 'legacy_stripe' } + +const NEW_CREATOR_SUBSCRIPTION = { + allowed: true, + transition_type: 'new_subscription', + effective_at: '2026-07-21T00:00:00Z', + is_immediate: true, + cost_today_cents: 33_600, + cost_next_period_cents: 33_600, + credits_today_cents: 7_400, + credits_next_period_cents: 7_400, + new_plan: CREATOR_ANNUAL_PLAN +} satisfies PreviewSubscribeResponse + +const FAILED_RECOVERY_OPERATION = { + id: RECOVERY_OPERATION_ID, + status: 'failed', + error_message: 'Payment was not completed', + started_at: '2026-07-20T00:00:00Z', + completed_at: '2026-07-20T00:00:01Z' +} satisfies BillingOpStatusResponse + +const SUCCEEDED_RECOVERY_OPERATION = { + id: RECOVERY_OPERATION_ID, + status: 'succeeded', + started_at: '2026-07-20T00:00:00Z', + completed_at: '2026-07-20T00:00:01Z' +} satisfies BillingOpStatusResponse + +// The recovery loader runs at the tail of GraphCanvas onMounted, so the boot +// chain must not throw before it: a missing settings subpath, prompt exec_info, +// or queue status each abort that chain. +async function mockGraphBootExtras(page: Page) { + await page.route('**/api/settings/**', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({})) + }) + await page.route('**/api/prompt', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ exec_info: { queue_remaining: 0 } })) + }) + await page.route('**/api/queue', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + return route.fulfill(jsonRoute({ queue_running: [], queue_pending: [] })) + }) +} + +async function setupCloudApp(page: Page) { + await mockCloudBoot(page, { + features: BOOT_FEATURES, + settings: BOOT_SETTINGS + }) + await mockGraphBootExtras(page) + await mockBilling(page) + await mockWorkspace(page, workspace('personal', 'owner'), []) + await bootCloud(page) +} + +// sessionStorage must be seeded before any app code runs; attemptedAt is +// stamped in the init script so the entry is always fresher than the 24h cap. +async function seedPendingCheckout( + page: Page, + entry: Omit +) { + await page.addInitScript( + ({ key, seeded }) => { + sessionStorage.setItem( + key, + JSON.stringify({ ...seeded, attemptedAt: Date.now() - 60_000 }) + ) + }, + { key: PENDING_CHECKOUT_STORAGE_KEY, seeded: entry } + ) +} + +function readPendingCheckout(page: Page) { + return page.evaluate( + (key) => sessionStorage.getItem(key), + PENDING_CHECKOUT_STORAGE_KEY + ) +} + +function trackBillingOpRequests(page: Page) { + const operationPollRequests: Request[] = [] + page.on('request', (request) => { + if (request.url().includes('/api/billing/ops/')) { + operationPollRequests.push(request) + } + }) + return operationPollRequests +} + +const confirmPaymentHeading = (page: Page) => + page.getByRole('heading', { name: 'Confirm your payment' }) + +test.describe('Redirect checkout recovery', { tag: '@cloud' }, () => { + test('reopens checkout for the attempted plan when reconciliation fails', async ({ + page + }) => { + const subscribeRequests: Request[] = [] + const operationPollRequests: Request[] = [] + await seedPendingCheckout(page, PENDING_CREATOR_CHECKOUT) + await setupCloudApp(page) + await page.route('**/api/billing/status', (route) => + route.fulfill(jsonRoute(LEGACY_ACTIVE_STANDARD_STATUS)) + ) + await page.route('**/api/billing/plans', (route) => + route.fulfill( + jsonRoute({ + plans: [CREATOR_ANNUAL_PLAN] + } satisfies BillingPlansResponse) + ) + ) + await page.route('**/api/billing/preview-subscribe', (route) => + route.fulfill(jsonRoute(NEW_CREATOR_SUBSCRIPTION)) + ) + await page.route('**/api/billing/subscribe', (route) => { + subscribeRequests.push(route.request()) + return route.fulfill({ + ...jsonRoute({ + code: 'unexpected_subscribe', + message: 'Recovered checkouts must not auto-subscribe' + } satisfies ErrorResponse), + status: 500 + }) + }) + await page.route(`**/api/billing/ops/${RECOVERY_OPERATION_ID}`, (route) => { + operationPollRequests.push(route.request()) + return route.fulfill(jsonRoute(FAILED_RECOVERY_OPERATION)) + }) + + await page.goto(APP_URL) + + await cloudAppExpect(confirmPaymentHeading(page)).toBeVisible() + const checkoutDialog = page.getByRole('dialog') + await expect( + checkoutDialog.getByRole('button', { name: 'Subscribe to Creator' }) + ).toBeVisible() + await expect( + checkoutDialog.getByText('$336 Billed yearly').filter({ visible: true }) + ).toBeVisible() + expect(operationPollRequests.length).toBeGreaterThan(0) + expect(subscribeRequests).toHaveLength(0) + await expect.poll(() => readPendingCheckout(page)).toBeNull() + }) + + test('stays silent when reconciliation succeeds', async ({ page }) => { + const operationPollRequests: Request[] = [] + await seedPendingCheckout(page, PENDING_CREATOR_CHECKOUT) + await setupCloudApp(page) + await page.route(`**/api/billing/ops/${RECOVERY_OPERATION_ID}`, (route) => { + operationPollRequests.push(route.request()) + return route.fulfill(jsonRoute(SUCCEEDED_RECOVERY_OPERATION)) + }) + + await page.goto(APP_URL) + + await waitForCloudApp(page) + await cloudAppExpect + .poll(() => operationPollRequests.length) + .toBeGreaterThan(0) + await expect.poll(() => readPendingCheckout(page)).toBeNull() + await expect(confirmPaymentHeading(page)).toBeHidden() + await expect( + page.getByRole('heading', { name: 'Choose a Plan' }) + ).toBeHidden() + }) + + test('drops an entry for another user without reconciling', async ({ + page + }) => { + await seedPendingCheckout(page, { + ...PENDING_CREATOR_CHECKOUT, + ownerUid: 'someone-else' + }) + await setupCloudApp(page) + const operationPollRequests = trackBillingOpRequests(page) + + await page.goto(APP_URL) + + await waitForCloudApp(page) + await cloudAppExpect.poll(() => readPendingCheckout(page)).toBeNull() + expect(operationPollRequests).toHaveLength(0) + await expect(confirmPaymentHeading(page)).toBeHidden() + await expect( + page.getByRole('heading', { name: 'Choose a Plan' }) + ).toBeHidden() + }) +}) diff --git a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts index 6280c9e5bda..b8ba7916a52 100644 --- a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts +++ b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts @@ -644,7 +644,7 @@ test.describe('Pricing table deep link', { tag: '@cloud' }, () => { await expect.poll(() => operationPollRequests.length).toBeGreaterThan(0) await expect(backButton).toBeDisabled() - await page.clock.fastForward(5 * 60_000 + 1) + await page.clock.fastForward(23 * 60 * 60_000 + 1) await expect(backButton).toBeEnabled() await expect( diff --git a/package.json b/package.json index a9d037603aa..357cc8e59bb 100644 --- a/package.json +++ b/package.json @@ -102,6 +102,7 @@ "@primevue/themes": "catalog:", "@sentry/vue": "catalog:", "@sparkjsdev/spark": "catalog:", + "@stripe/stripe-js": "catalog:", "@tanstack/vue-virtual": "catalog:", "@tiptap/core": "catalog:", "@tiptap/extension-link": "catalog:", diff --git a/packages/ingest-types/src/index.ts b/packages/ingest-types/src/index.ts index 27d40003c06..4eee2d42087 100644 --- a/packages/ingest-types/src/index.ts +++ b/packages/ingest-types/src/index.ts @@ -30,6 +30,11 @@ export type { AgentCreateThreadErrors, AgentCreateThreadResponse, AgentCreateThreadResponses, + AgentDeleteSkillData, + AgentDeleteSkillError, + AgentDeleteSkillErrors, + AgentDeleteSkillResponse, + AgentDeleteSkillResponses, AgentDraftSnapshot, AgentError, AgentGetDraftData, @@ -42,6 +47,11 @@ export type { AgentGetMessagesErrors, AgentGetMessagesResponse, AgentGetMessagesResponses, + AgentListSkillsData, + AgentListSkillsError, + AgentListSkillsErrors, + AgentListSkillsResponse, + AgentListSkillsResponses, AgentListThreadsData, AgentListThreadsError, AgentListThreadsErrors, @@ -54,6 +64,14 @@ export type { AgentPostMessageRequest, AgentPostMessageResponse, AgentPostMessageResponses, + AgentPublishSkillData, + AgentPublishSkillError, + AgentPublishSkillErrors, + AgentPublishSkillResponse, + AgentPublishSkillResponses, + AgentSkill, + AgentSkillListResponse, + AgentSkillPublishRequest, AgentThreadCreated, AgentThreadCreateRequest, AgentThreadListResponse, @@ -68,13 +86,21 @@ export type { AssetTagHistogramResponse, AssetUpdated, AssetWritable, + BillingAddress, BillingBalanceResponse, + BillingCapabilities, + BillingCapabilitiesResponse, + BillingCapabilityRolloutDefaults, + BillingCapabilityScope, + BillingCompanyDetailsResponse, + BillingCompanyDetailsUpdateRequest, BillingEvent, BillingEventsResponse, BillingOpStatusResponse, BillingPlansResponse, BillingStatus, BillingStatusResponse, + BillingTaxId, BulkRevokeApiKeysResponse, BulkRevokeWorkspaceMemberApiKeysData, BulkRevokeWorkspaceMemberApiKeysError, @@ -210,6 +236,7 @@ export type { CreateWorkspaceResponse, CreateWorkspaceResponses, CredentialOption, + CurrentWorkspaceResponse, DeleteAssetData, DeleteAssetError, DeleteAssetErrors, @@ -318,6 +345,16 @@ export type { GetBillingBalanceErrors, GetBillingBalanceResponse, GetBillingBalanceResponses, + GetBillingCapabilitiesData, + GetBillingCapabilitiesError, + GetBillingCapabilitiesErrors, + GetBillingCapabilitiesResponse, + GetBillingCapabilitiesResponses, + GetBillingCompanyDetailsData, + GetBillingCompanyDetailsError, + GetBillingCompanyDetailsErrors, + GetBillingCompanyDetailsResponse, + GetBillingCompanyDetailsResponses, GetBillingEventsData, GetBillingEventsError, GetBillingEventsErrors, @@ -348,6 +385,11 @@ export type { GetChurnkeyAuthErrors, GetChurnkeyAuthResponse, GetChurnkeyAuthResponses, + GetCurrentWorkspaceData, + GetCurrentWorkspaceError, + GetCurrentWorkspaceErrors, + GetCurrentWorkspaceResponse, + GetCurrentWorkspaceResponses, GetCustomNodeProxyData, GetCustomNodeProxyErrors, GetCustomNodeProxyResponses, @@ -703,6 +745,11 @@ export type { ListJobsResponse, ListJobsResponses, ListMembersResponse, + ListSavedPaymentMethodsData, + ListSavedPaymentMethodsError, + ListSavedPaymentMethodsErrors, + ListSavedPaymentMethodsResponse, + ListSavedPaymentMethodsResponses, ListSecretProvidersData, ListSecretProvidersError, ListSecretProvidersErrors, @@ -895,6 +942,7 @@ export type { RevokeWorkspaceInviteErrors, RevokeWorkspaceInviteResponse, RevokeWorkspaceInviteResponses, + SavedPaymentMethod, SecretListResponse, SecretProvider, SecretProvidersResponse, @@ -916,6 +964,7 @@ export type { SubscribeResponses, SubscribeToLogsData, SubscribeToLogsResponses, + SubscriptionDiscount, SubscriptionDuration, SubscriptionTier, SystemStatsResponse, @@ -933,6 +982,11 @@ export type { UpdateAssetErrors, UpdateAssetResponse, UpdateAssetResponses, + UpdateBillingCompanyDetailsData, + UpdateBillingCompanyDetailsError, + UpdateBillingCompanyDetailsErrors, + UpdateBillingCompanyDetailsResponse, + UpdateBillingCompanyDetailsResponses, UpdateHubProfileData, UpdateHubProfileError, UpdateHubProfileErrors, diff --git a/packages/ingest-types/src/types.gen.ts b/packages/ingest-types/src/types.gen.ts index 7b1f1b8dba3..cbcf44bfb21 100644 --- a/packages/ingest-types/src/types.gen.ts +++ b/packages/ingest-types/src/types.gen.ts @@ -33,6 +33,7 @@ export type SubscriptionTier = | 'PRO' | 'FOUNDERS_EDITION' | 'TEAM' + | 'ENTERPRISE' /** * Abbreviated workspace metadata used in list responses. @@ -746,6 +747,22 @@ export type SystemStatsResponse = { */ export type SubscriptionDuration = 'MONTHLY' | 'ANNUAL' +export type SubscriptionDiscount = { + /** + * What this discount removed from the amount due today. + */ + amount_off_cents?: number + code: string + kind: 'plan' | 'promotion' + /** + * Customer-facing display name of the underlying coupon. `code` can + * be an internal identifier (e.g. team_commitment_7_5); render this + * when present. + * + */ + name?: string +} + /** * Response after successfully subscribing to a billing plan. */ @@ -799,6 +816,13 @@ export type SubscribeRequest = { * */ confirm_reactivation?: boolean + /** + * Stripe ConfirmationToken created from deferred Payment Element + * details. For an initial subscription, the backend creates the exact + * invoice PaymentIntent and confirms it with this token. + * + */ + confirmation_token?: string /** * Client-provided key to prevent duplicate operations. * If a billing op with this key already exists, returns the existing op instead of creating a new one. @@ -809,6 +833,12 @@ export type SubscribeRequest = { * Target plan slug to subscribe to */ plan_slug: string + /** + * Optional customer-facing Stripe promotion code. The backend + * resolves and validates it, then stacks it with plan discounts. + * + */ + promotion_code?: string /** * Echoes PreviewSubscribeResponse.proration_at from the preview the * caller consented to. When present, the charge is prorated to this @@ -821,12 +851,31 @@ export type SubscribeRequest = { * */ proration_at?: string + /** + * Opaque quote id returned by PreviewSubscribeResponse. + */ + quote_id?: string + /** + * Quote version returned by PreviewSubscribeResponse. + */ + quote_version?: number /** * URL to redirect after payment method is added successfully. - * Required if workspace has no payment method on file. + * Required if the workspace has no payment method on file, when + * confirmation_token is provided, or when a selected saved payment + * method is redirect-based (any non-card type). Redirect-based flows + * require an absolute HTTPS URL; plain HTTP is accepted only for + * loopback hosts during local development. * */ return_url?: string + /** + * Optional saved payment method selected for this subscription. It + * must be attached to the current workspace's Stripe customer. + * Mutually exclusive with confirmation_token. + * + */ + saved_payment_method_id?: string /** * Selected team credit-stop preset id (e.g. "team_700") for the * per-credit Team plan. Required when subscribing to a per-credit Team @@ -921,6 +970,23 @@ export type SecretListResponse = { data: Array } +export type SavedPaymentMethod = { + /** + * Card brand. Present only for card payment methods. + */ + brand?: string + id: string + /** + * Exactly one item is the default when the returned list is non-empty. + */ + is_default: boolean + /** + * Masked card suffix. Present only for card payment methods. + */ + last4?: string + type: string +} + /** * Response after accepting a resubscribe request. */ @@ -1232,6 +1298,7 @@ export type PreviewSubscribeResponse = { * Whether this subscription change is allowed */ allowed: boolean + amount_due_cents?: number /** * Amount that will be charged at next billing period in cents */ @@ -1248,7 +1315,9 @@ export type PreviewSubscribeResponse = { * Credits granted today in cents (prorated for mid-period upgrades) */ credits_today_cents: number + currency?: string current_plan?: PreviewPlanInfo + discounts?: Array /** * When the change takes effect */ @@ -1258,6 +1327,20 @@ export type PreviewSubscribeResponse = { */ is_immediate: boolean new_plan: PreviewPlanInfo + /** + * The Stripe payment method configuration governing which payment + * methods the embedded checkout offers for this environment. Mount + * Stripe Elements with `paymentMethodConfiguration` set to this id + * instead of hardcoding payment method types. Present on every + * successful preview while embedded checkout is enabled and absent + * from legacy previews. + * + */ + payment_method_configuration_id?: string + /** + * Normalized promotion code accepted by Stripe. + */ + promotion_code?: string /** * The instant cost_today_cents was priced at (Stripe-native transitions * only; absent for other billing rails). Echo this back as proration_at @@ -1267,10 +1350,34 @@ export type PreviewSubscribeResponse = { * */ proration_at?: string + /** + * Opaque short-lived quote identifier to echo on Subscribe. + */ + quote_id?: string + /** + * Quote contract version to echo on Subscribe. + */ + quote_version?: number /** * Reason why the change is not allowed (only present if allowed=false) */ reason?: string + renewal_amount_cents?: number + /** + * The next recurring charge and target-plan period end. Current servers + * always return this later than effective_at and following the target + * plan's billing interval. Optional in the schema for older clients. + * + */ + renewal_at?: string + /** + * Whether this previewed change requires explicit reactivation + * consent. Computed from the persisted subscription and a short-lived + * cache of Stripe lifecycle state. The subscribe enforcement path + * performs its own uncached Stripe lifecycle read. + * + */ + requires_reactivation_confirmation?: boolean /** * Type of subscription transition */ @@ -1336,6 +1443,10 @@ export type PreviewSubscribeRequest = { * Target plan slug to preview subscribing to */ plan_slug: string + /** + * Optional Stripe promotion code to validate and include in the exact quote. + */ + promotion_code?: string /** * Selected per-credit Team plan stop to preview. */ @@ -3146,6 +3257,23 @@ export type DeleteSessionResponse = { success: boolean } +/** + * The workspace bound to the presented credential, plus how that credential authenticated. Same shape as Workspace with the caller's role and the auth method added, and without created_at (callers of this endpoint want identity, not provenance). + */ +export type CurrentWorkspaceResponse = { + /** + * How this request authenticated. Known values are firebase, cookie, comfy_api_key, comfy_admin_key, cloud_api_key and cloud_jwt; treat it as an open string so a new auth method is not a breaking change. + */ + auth_method: string + id: string + name: string + /** + * The requesting user's role in this workspace. Omitted (absent from the object, never an explicit null) when the credential carries no resolvable user membership. + */ + role?: 'owner' | 'member' + type: 'personal' | 'team' +} + /** * Request body for creating a new workspace. */ @@ -3423,6 +3551,23 @@ export type BulkRevokeApiKeysResponse = { revoked_count: number } +/** + * A tax identifier for a company Stripe customer. Stripe validates the + * type/value combination synchronously and verifies VAT/ABN-style IDs + * asynchronously. + * + */ +export type BillingTaxId = { + /** + * Stripe tax ID type, e.g. `eu_vat`, `us_ein`, `au_abn`. See + * https://docs.stripe.com/api/tax_ids/object#tax_id_object-type + * for the full list. + * + */ + type: string + value: string +} + /** * Current billing and subscription status for a workspace. */ @@ -3432,7 +3577,8 @@ export type BillingStatusResponse = { * customer. Today this is a Stripe-hosted payment page for an invoice * needing authentication (SCA/3DS); * send the customer there to complete payment. Mirrors the field of - * the same name on BillingOpStatusResponse. + * the same name on BillingOpStatusResponse. This bearer capability is + * returned only to workspace billing managers. * */ action_url?: string @@ -3461,6 +3607,16 @@ export type BillingStatusResponse = { * Current workspace members plus non-expired pending invites, used against max_seats. 0 when billing is disabled. */ occupied_seats: number + /** + * Present when a pending operation supports embedded Stripe + * authentication. It may be returned alongside a hosted payment page + * when both recovery methods are available. This bearer + * capability is returned only to workspace billing managers. Pass + * directly to Stripe.js; do not log or + * persist it in client storage. + * + */ + payment_intent_client_secret?: string /** * The workspace's in-flight billing operation, when one exists. Lets a * client recover a payment it has lost the local reference to — a @@ -3532,30 +3688,84 @@ export type BillingOpStatusResponse = { * Present while status is "pending" and the operation cannot proceed * without the customer. Today this is a Stripe-hosted payment page for * a subscription whose first invoice needs authentication (SCA/3DS); - * send the customer there to complete payment. Absent otherwise. + * send the customer there to complete payment. This bearer capability is + * returned only to workspace billing managers. Absent otherwise. * */ action_url?: string + /** + * State derived from the PaymentIntent attached to this operation's + * exact stored Stripe invoice. Absent when the operation has no + * correlated PaymentIntent. + * + */ + authentication_state?: + | 'requires_action' + | 'processing' + | 'failed_retryable' + | 'succeeded' + | 'reconciliation_needed' /** * When the operation completed (success or failure) */ completed_at?: string /** - * Error message if status is failed + * Coarse classification of why the correlated PaymentIntent's last + * payment attempt failed, derived at read time from the provider's + * machine-readable error and decline codes — never from provider + * message text or payment-method details. Present only when the + * intent has recorded a failed attempt and the operation is either + * still pending with authentication_state failed_retryable or has + * terminally failed. generic means the attempt failed for a reason + * outside this vocabulary. + * + */ + decline_reason?: + | 'card_declined' + | 'insufficient_funds' + | 'expired_card' + | 'incorrect_cvc' + | 'authentication_required' + | 'authentication_failed' + | 'processing_error' + | 'generic' + /** + * PII-safe failure code or generic failure message */ error_message?: string /** * Unique identifier for the billing operation */ id: string + /** + * Stripe PaymentIntent client secret for completing requires_action. + * This bearer capability is returned only to workspace billing managers + * and is absent otherwise. + * + */ + payment_intent_client_secret?: string + /** + * Typed next action for a failed operation. Absent for pending and succeeded operations. + */ + recovery_action?: + | 'retry' + | 'replace_payment_method' + | 'authenticate_payment' + | 'contact_support' + /** + * Whether the customer can recover by starting a new billing operation after performing recovery_action. + */ + retryable?: boolean /** * When the operation was initiated */ started_at: string /** - * Current status of the operation + * Current status of the operation. reconciliation_needed is terminal + * for client polling but requires support reconciliation. + * */ - status: 'pending' | 'succeeded' | 'failed' + status: 'pending' | 'succeeded' | 'failed' | 'reconciliation_needed' } /** @@ -3605,6 +3815,104 @@ export type BillingEvent = { } } +/** + * Fields to set on the workspace's Stripe customer. Every group is + * optional; omit a group to leave that part of the customer unchanged. + * + */ +export type BillingCompanyDetailsUpdateRequest = { + address?: BillingAddress + /** + * Legal or trading name to show on invoices. + */ + company_name?: string + tax_id?: BillingTaxId +} + +/** + * A billing address for a company Stripe customer. city and postal_code + * are optional because some countries (e.g. Hong Kong, the UAE, Panama) + * have no postal code and are not collected for them; Stripe validates + * what a given country actually requires. + * + */ +export type BillingAddress = { + city?: string + /** + * Two-letter ISO 3166-1 country code. + */ + country: string + line1: string + line2?: string + postal_code?: string + state?: string +} + +/** + * Company billing details on file for the workspace's Stripe customer. + * A field is absent until the workspace sets it via PATCH + * /api/billing/company-details. + * + */ +export type BillingCompanyDetailsResponse = { + address?: BillingAddress + company_name?: string + tax_id?: BillingTaxId +} + +export type BillingCapabilityScope = { + user_id: string + workspace_id: string +} + +/** + * Identifies capability values currently using safe rollout defaults + * instead of deterministic policy results. A true value is UI guidance, + * not evidence that the corresponding write will succeed. + * + */ +export type BillingCapabilityRolloutDefaults = { + can_downgrade_to_personal: boolean + can_subscribe_self_serve: boolean + can_top_up: boolean +} + +/** + * Effective billing UI guidance for one authenticated user and workspace. + */ +export type BillingCapabilitiesResponse = { + capabilities: BillingCapabilities + /** + * Time after which the client must refetch this snapshot. + */ + expires_at: string + resolved_for: BillingCapabilityScope + /** + * JavaScript-safe, time-sortable revision for this snapshot. It + * increases monotonically within a serving process. Clients should + * invalidate on a different X-Capability-Revision value and use + * expires_at as the cross-instance freshness bound. + * + */ + revision: number + rollout_defaults_applied: BillingCapabilityRolloutDefaults +} + +/** + * Conservative UI guidance. These values do not authorize billing writes; + * each write endpoint independently enforces its permission policy. + * + */ +export type BillingCapabilities = { + can_cancel: boolean + can_change_seats: boolean + can_downgrade_to_personal: boolean + can_invite_members: boolean + can_reactivate: boolean + can_subscribe_self_serve: boolean + can_top_up: boolean +} + /** * Current credit balance and usage details for a workspace. */ @@ -3839,6 +4147,69 @@ export type AgentThreadCreateRequest = { workflow_id?: string } +/** + * A user-authored skill pack to create or replace. Plain JSON — a pack body is small enough that a signed-URL upload would be pure overhead. + */ +export type AgentSkillPublishRequest = { + /** + * Accepted only so an `always: true` copied out of a SKILL.md frontmatter is refused with an explanation instead of silently dropped. User packs are on-demand only, so true is rejected. + */ + always?: boolean + /** + * The full instruction text, injected only when the pack is loaded. Capped per pack and, together with the caller's other packs, in total; the exact byte limits are deployment configuration and are named in the rejection message when exceeded. + */ + body: string + /** + * One line saying when the agent should load this pack. It is what every prompt carries for an unloaded pack, so it is a trigger description, not a title. Single-line: control characters, including CR and LF, are refused. maxLength is counted in code points, as JSON Schema defines it, and the service counts the same way. + */ + description: string + /** + * The pack's flat identifier and the load_skill argument: letters, digits, '.', '_' and '-'. Publishing a name already held by the caller replaces that pack. A name matching a built-in always-on pack is refused; a name matching a built-in on-demand pack is accepted, and is the name consumption will resolve to the user's pack. Must contain at least one character that is not a dot: "." and ".." are path segments a normalizing client rewrites. + */ + name: string +} + +/** + * The caller's skill packs, ordered by name. + */ +export type AgentSkillListResponse = { + skills: Array +} + +/** + * One of the caller's user-authored skill packs. + */ +export type AgentSkill = { + /** + * The full instruction text. + */ + body: string + /** + * Lowercase hex sha256 of body, with no algorithm prefix. Stamped on every write, so a client can tell whether the stored pack matches the body it last sent. + */ + body_hash: string + /** + * RFC3339 timestamp of when the pack was first published. + */ + created_at: string + /** + * One-line trigger description the agent selects the pack from. + */ + description: string + /** + * Server-assigned pack ID. + */ + id: string + /** + * The pack's flat identifier and the load_skill argument. + */ + name: string + /** + * RFC3339 timestamp of the pack's most recent publish. + */ + updated_at: string +} + /** * A user turn posted to the agent. */ @@ -4318,6 +4689,160 @@ export type AgentGetDraftResponses = { export type AgentGetDraftResponse = AgentGetDraftResponses[keyof AgentGetDraftResponses] +export type AgentListSkillsData = { + body?: never + path?: never + query?: never + url: '/api/agent/skills' +} + +export type AgentListSkillsErrors = { + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * The caller is not enrolled in the cohort gate fronting these CRUD routes: the agent-skill-packs flag, or the agent-in-app-experience flag gating the whole /api/agent surface. Both default off and fail closed (a missing evaluation context resolves to false), and both answer 404 rather than 403 so the surface is invisible when off. Ingest-raised, so the body is the standard ErrorResponse shape. + */ + 404: ErrorResponse + /** + * Internal server error (ingest-raised failures use the standard ErrorResponse shape instead) + */ + 500: AgentError + /** + * Agent service unavailable + */ + 502: ErrorResponse + /** + * The agent proxy is not configured to forward safely (a non-local agent service URL with no shared machine-to-machine secret), so ingest refuses rather than sending unverifiable identity headers. + */ + 503: ErrorResponse +} + +export type AgentListSkillsError = + AgentListSkillsErrors[keyof AgentListSkillsErrors] + +export type AgentListSkillsResponses = { + /** + * The caller's skill packs. + */ + 200: AgentSkillListResponse +} + +export type AgentListSkillsResponse = + AgentListSkillsResponses[keyof AgentListSkillsResponses] + +export type AgentPublishSkillData = { + body: AgentSkillPublishRequest + path?: never + query?: never + url: '/api/agent/skills' +} + +export type AgentPublishSkillErrors = { + /** + * The pack was rejected by publish-time validation (name shape, empty description or body, control characters in either, body over the per-pack size cap, always:true, a reserved always-on name, or comfy-cli shell syntax in the body). The message names what to change. + */ + 400: AgentError + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * The caller is not enrolled in the cohort gate fronting these CRUD routes: the agent-skill-packs flag, or the agent-in-app-experience flag gating the whole /api/agent surface. Both default off and fail closed (a missing evaluation context resolves to false), and both answer 404 rather than 403 so the surface is invisible when off. Ingest-raised, so the body is the standard ErrorResponse shape. + */ + 404: ErrorResponse + /** + * A per-user budget is full — the pack count, or the combined size of the caller's packs. Nothing about this pack can be edited to make it fit; another pack has to be deleted first. + */ + 409: AgentError + /** + * Request body over ingest's transport-level cap (AGENT_SKILL_REQUEST_BODY_LIMIT), which is set well above the per-pack size cap so an over-size pack gets the actionable 400 above instead. Reaching this means the request itself is outsized. + */ + 413: ErrorResponse + /** + * Internal server error (ingest-raised failures use the standard ErrorResponse shape instead) + */ + 500: AgentError + /** + * Agent service unavailable + */ + 502: ErrorResponse + /** + * The agent proxy is not configured to forward safely (a non-local agent service URL with no shared machine-to-machine secret), so ingest refuses rather than sending unverifiable identity headers. + */ + 503: ErrorResponse +} + +export type AgentPublishSkillError = + AgentPublishSkillErrors[keyof AgentPublishSkillErrors] + +export type AgentPublishSkillResponses = { + /** + * An existing pack of the same name was replaced. + */ + 200: AgentSkill + /** + * A new pack was created. + */ + 201: AgentSkill +} + +export type AgentPublishSkillResponse = + AgentPublishSkillResponses[keyof AgentPublishSkillResponses] + +export type AgentDeleteSkillData = { + body?: never + path: { + /** + * The pack's name. + */ + name: string + } + query?: never + url: '/api/agent/skills/{name}' +} + +export type AgentDeleteSkillErrors = { + /** + * The name is not a valid pack name. + */ + 400: ErrorResponse + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * The caller holds no pack with that name, or the caller is not enrolled in the cohort gate fronting these CRUD routes (the agent-skill-packs flag, or the agent-in-app-experience flag gating the whole /api/agent surface). Both flags default off and fail closed, and both answer 404 rather than 403 so the surface is invisible when off. The schema below is the agent-raised no-such-pack body; the gate-off 404 is ingest-raised and uses the standard ErrorResponse shape instead. + */ + 404: AgentError + /** + * Internal server error (ingest-raised failures use the standard ErrorResponse shape instead) + */ + 500: AgentError + /** + * Agent service unavailable + */ + 502: ErrorResponse + /** + * The agent proxy is not configured to forward safely (a non-local agent service URL with no shared machine-to-machine secret), so ingest refuses rather than sending unverifiable identity headers. + */ + 503: ErrorResponse +} + +export type AgentDeleteSkillError = + AgentDeleteSkillErrors[keyof AgentDeleteSkillErrors] + +export type AgentDeleteSkillResponses = { + /** + * The pack was deleted. + */ + 204: void +} + +export type AgentDeleteSkillResponse = + AgentDeleteSkillResponses[keyof AgentDeleteSkillResponses] + export type AgentListThreadsData = { body?: never path?: never @@ -5953,6 +6478,45 @@ export type GetBillingBalanceResponses = { export type GetBillingBalanceResponse = GetBillingBalanceResponses[keyof GetBillingBalanceResponses] +export type GetBillingCapabilitiesData = { + body?: never + path?: never + query?: never + url: '/api/billing/capabilities' +} + +export type GetBillingCapabilitiesErrors = { + /** + * Workspace or user context required + */ + 401: ErrorResponse + /** + * Actor is not a member of the authenticated workspace + */ + 403: ErrorResponse + /** + * Workspace not found + */ + 404: ErrorResponse + /** + * Billing service unavailable or returned an invalid response + */ + 502: ErrorResponse +} + +export type GetBillingCapabilitiesError = + GetBillingCapabilitiesErrors[keyof GetBillingCapabilitiesErrors] + +export type GetBillingCapabilitiesResponses = { + /** + * Effective billing capabilities + */ + 200: BillingCapabilitiesResponse +} + +export type GetBillingCapabilitiesResponse = + GetBillingCapabilitiesResponses[keyof GetBillingCapabilitiesResponses] + export type GetChurnkeyAuthData = { body?: never path?: never @@ -5992,6 +6556,76 @@ export type GetChurnkeyAuthResponses = { export type GetChurnkeyAuthResponse = GetChurnkeyAuthResponses[keyof GetChurnkeyAuthResponses] +export type GetBillingCompanyDetailsData = { + body?: never + path?: never + query?: never + url: '/api/billing/company-details' +} + +export type GetBillingCompanyDetailsErrors = { + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * Workspace owner role required + */ + 403: ErrorResponse + /** + * Internal server error + */ + 500: ErrorResponse +} + +export type GetBillingCompanyDetailsError = + GetBillingCompanyDetailsErrors[keyof GetBillingCompanyDetailsErrors] + +export type GetBillingCompanyDetailsResponses = { + /** + * Success + */ + 200: BillingCompanyDetailsResponse +} + +export type GetBillingCompanyDetailsResponse = + GetBillingCompanyDetailsResponses[keyof GetBillingCompanyDetailsResponses] + +export type UpdateBillingCompanyDetailsData = { + body: BillingCompanyDetailsUpdateRequest + path?: never + query?: never + url: '/api/billing/company-details' +} + +export type UpdateBillingCompanyDetailsErrors = { + /** + * Bad request (e.g., missing address fields or an invalid tax ID) + */ + 400: ErrorResponse + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * Internal server error + */ + 500: ErrorResponse +} + +export type UpdateBillingCompanyDetailsError = + UpdateBillingCompanyDetailsErrors[keyof UpdateBillingCompanyDetailsErrors] + +export type UpdateBillingCompanyDetailsResponses = { + /** + * Success + */ + 200: BillingCompanyDetailsResponse +} + +export type UpdateBillingCompanyDetailsResponse = + UpdateBillingCompanyDetailsResponses[keyof UpdateBillingCompanyDetailsResponses] + export type GetBillingEventsData = { body?: never path?: never @@ -6100,6 +6734,45 @@ export type GetBillingOpStatusResponses = { export type GetBillingOpStatusResponse = GetBillingOpStatusResponses[keyof GetBillingOpStatusResponses] +export type ListSavedPaymentMethodsData = { + body?: never + path?: never + query?: never + url: '/api/billing/payment-methods' +} + +export type ListSavedPaymentMethodsErrors = { + /** + * Billing is disabled + */ + 400: ErrorResponse + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * Workspace owner role required + */ + 403: ErrorResponse + /** + * Internal server error + */ + 500: ErrorResponse +} + +export type ListSavedPaymentMethodsError = + ListSavedPaymentMethodsErrors[keyof ListSavedPaymentMethodsErrors] + +export type ListSavedPaymentMethodsResponses = { + /** + * Saved payment methods + */ + 200: Array +} + +export type ListSavedPaymentMethodsResponse = + ListSavedPaymentMethodsResponses[keyof ListSavedPaymentMethodsResponses] + export type GetPaymentPortalData = { body?: PaymentPortalRequest path?: never @@ -6182,6 +6855,10 @@ export type PreviewSubscribeErrors = { * Unauthorized */ 401: ErrorResponse + /** + * Workspace owner role required + */ + 403: ErrorResponse /** * Internal server error */ @@ -6614,25 +7291,7 @@ export type GetFeaturesResponses = { * Whether the server supports preview metadata */ supports_preview_metadata?: boolean - [key: string]: - | unknown - | { - /** - * Total free jobs granted for the current period - */ - allowance: number - /** - * Free jobs remaining (allowance - used, floored at 0) - */ - remaining: number - /** - * Free jobs consumed so far - */ - used: number - } - | number - | boolean - | undefined + [key: string]: unknown } } @@ -10901,6 +11560,41 @@ export type UpdateWorkspaceResponses = { export type UpdateWorkspaceResponse = UpdateWorkspaceResponses[keyof UpdateWorkspaceResponses] +export type GetCurrentWorkspaceData = { + body?: never + path?: never + query?: never + url: '/api/workspaces/current' +} + +export type GetCurrentWorkspaceErrors = { + /** + * Unauthorized + */ + 401: ErrorResponse + /** + * No workspace resolves for this credential — it carries no workspace binding, the workspace was deleted, or the credential's user is no longer a member. Deliberately not 401: the credential itself is valid, so clients must not discard it or re-authenticate. + */ + 404: ErrorResponse + /** + * Internal server error + */ + 500: ErrorResponse +} + +export type GetCurrentWorkspaceError = + GetCurrentWorkspaceErrors[keyof GetCurrentWorkspaceErrors] + +export type GetCurrentWorkspaceResponses = { + /** + * The credential's workspace + */ + 200: CurrentWorkspaceResponse +} + +export type GetCurrentWorkspaceResponse = + GetCurrentWorkspaceResponses[keyof GetCurrentWorkspaceResponses] + export type GetStaticExtensionsData = { body?: never path: { diff --git a/packages/ingest-types/src/zod.gen.ts b/packages/ingest-types/src/zod.gen.ts index a4504755451..384ee8f9919 100644 --- a/packages/ingest-types/src/zod.gen.ts +++ b/packages/ingest-types/src/zod.gen.ts @@ -11,7 +11,8 @@ export const zSubscriptionTier = z.enum([ 'CREATOR', 'PRO', 'FOUNDERS_EDITION', - 'TEAM' + 'TEAM', + 'ENTERPRISE' ]) /** @@ -480,6 +481,21 @@ export const zSystemStatsResponse = z.object({ */ export const zSubscriptionDuration = z.enum(['MONTHLY', 'ANNUAL']) +export const zSubscriptionDiscount = z.object({ + amount_off_cents: z.coerce + .bigint() + .min(BigInt('-9223372036854775808'), { + message: 'Invalid value: Expected int64 to be >= -9223372036854775808' + }) + .max(BigInt('9223372036854775807'), { + message: 'Invalid value: Expected int64 to be <= 9223372036854775807' + }) + .optional(), + code: z.string(), + kind: z.enum(['plan', 'promotion']), + name: z.string().optional() +}) + /** * Response after successfully subscribing to a billing plan. */ @@ -497,10 +513,15 @@ export const zSubscribeRequest = z.object({ billing_cycle: z.enum(['monthly', 'yearly']).optional(), cancel_url: z.string().optional(), confirm_reactivation: z.boolean().optional(), + confirmation_token: z.string().optional(), idempotency_key: z.string().optional(), plan_slug: z.string(), + promotion_code: z.string().optional(), proration_at: z.string().datetime().optional(), + quote_id: z.string().optional(), + quote_version: z.number().int().optional(), return_url: z.string().optional(), + saved_payment_method_id: z.string().regex(/^pm_/).optional(), team_credit_stop_id: z.string().optional() }) @@ -549,6 +570,17 @@ export const zSecretListResponse = z.object({ data: z.array(zSecretResponse) }) +export const zSavedPaymentMethod = z.object({ + brand: z.string().optional(), + id: z.string().regex(/^pm_/), + is_default: z.boolean(), + last4: z + .string() + .regex(/^[0-9]{4}$/) + .optional(), + type: z.string() +}) + /** * Response after accepting a resubscribe request. */ @@ -763,6 +795,15 @@ export const zPreviewPlanInfo = z.object({ */ export const zPreviewSubscribeResponse = z.object({ allowed: z.boolean(), + amount_due_cents: z.coerce + .bigint() + .min(BigInt('-9223372036854775808'), { + message: 'Invalid value: Expected int64 to be >= -9223372036854775808' + }) + .max(BigInt('9223372036854775807'), { + message: 'Invalid value: Expected int64 to be <= 9223372036854775807' + }) + .optional(), cost_next_period_cents: z.coerce .bigint() .min(BigInt('-9223372036854775808'), { @@ -795,12 +836,29 @@ export const zPreviewSubscribeResponse = z.object({ .max(BigInt('9223372036854775807'), { message: 'Invalid value: Expected int64 to be <= 9223372036854775807' }), + currency: z.string().optional(), current_plan: zPreviewPlanInfo.optional(), + discounts: z.array(zSubscriptionDiscount).optional(), effective_at: z.string().datetime(), is_immediate: z.boolean(), new_plan: zPreviewPlanInfo, + payment_method_configuration_id: z.string().optional(), + promotion_code: z.string().optional(), proration_at: z.string().datetime().optional(), + quote_id: z.string().optional(), + quote_version: z.number().int().optional(), reason: z.string().optional(), + renewal_amount_cents: z.coerce + .bigint() + .min(BigInt('-9223372036854775808'), { + message: 'Invalid value: Expected int64 to be >= -9223372036854775808' + }) + .max(BigInt('9223372036854775807'), { + message: 'Invalid value: Expected int64 to be <= 9223372036854775807' + }) + .optional(), + renewal_at: z.string().datetime().optional(), + requires_reactivation_confirmation: z.boolean().optional(), transition_type: z.enum([ 'new_subscription', 'upgrade', @@ -814,6 +872,7 @@ export const zPreviewSubscribeResponse = z.object({ */ export const zPreviewSubscribeRequest = z.object({ plan_slug: z.string(), + promotion_code: z.string().optional(), team_credit_stop_id: z.string().optional() }) @@ -1887,6 +1946,17 @@ export const zDeleteSessionResponse = z.object({ success: z.boolean() }) +/** + * The workspace bound to the presented credential, plus how that credential authenticated. Same shape as Workspace with the caller's role and the auth method added, and without created_at (callers of this endpoint want identity, not provenance). + */ +export const zCurrentWorkspaceResponse = z.object({ + auth_method: z.string(), + id: z.string(), + name: z.string(), + role: z.enum(['owner', 'member']).optional(), + type: z.enum(['personal', 'team']) +}) + /** * Request body for creating a new workspace. */ @@ -1978,7 +2048,10 @@ export const zCreateSessionResponse = z.object({ * Request body for creating a new user secret. */ export const zCreateSecretRequest = z.object({ - credential_type: z.enum(['api_key', 'gcp_service_account']).optional(), + credential_type: z + .enum(['api_key', 'gcp_service_account']) + .optional() + .default('api_key'), name: z.string().min(1).max(255), provider: z.string().max(64).optional(), secret_value: z.string().min(1) @@ -2038,6 +2111,17 @@ export const zBulkRevokeApiKeysResponse = z.object({ revoked_count: z.number().int().gte(0) }) +/** + * A tax identifier for a company Stripe customer. Stripe validates the + * type/value combination synchronously and verifies VAT/ABN-style IDs + * asynchronously. + * + */ +export const zBillingTaxId = z.object({ + type: z.string(), + value: z.string() +}) + /** * Payment lifecycle status */ @@ -2062,6 +2146,7 @@ export const zBillingStatusResponse = z.object({ is_active: z.boolean(), max_seats: z.number().int(), occupied_seats: z.number().int(), + payment_intent_client_secret: z.string().optional(), pending_billing_op_id: z.string().optional(), pending_billing_op_type: z.enum(['subscription', 'topup']).optional(), plan_slug: z.string().optional(), @@ -2086,11 +2171,42 @@ export const zBillingPlansResponse = z.object({ */ export const zBillingOpStatusResponse = z.object({ action_url: z.string().optional(), + authentication_state: z + .enum([ + 'requires_action', + 'processing', + 'failed_retryable', + 'succeeded', + 'reconciliation_needed' + ]) + .optional(), completed_at: z.string().datetime().optional(), + decline_reason: z + .enum([ + 'card_declined', + 'insufficient_funds', + 'expired_card', + 'incorrect_cvc', + 'authentication_required', + 'authentication_failed', + 'processing_error', + 'generic' + ]) + .optional(), error_message: z.string().optional(), id: z.string(), + payment_intent_client_secret: z.string().optional(), + recovery_action: z + .enum([ + 'retry', + 'replace_payment_method', + 'authenticate_payment', + 'contact_support' + ]) + .optional(), + retryable: z.boolean().optional(), started_at: z.string().datetime(), - status: z.enum(['pending', 'succeeded', 'failed']) + status: z.enum(['pending', 'succeeded', 'failed', 'reconciliation_needed']) }) /** @@ -2114,6 +2230,93 @@ export const zBillingEventsResponse = z.object({ totalPages: z.number().int() }) +/** + * A billing address for a company Stripe customer. city and postal_code + * are optional because some countries (e.g. Hong Kong, the UAE, Panama) + * have no postal code and are not collected for them; Stripe validates + * what a given country actually requires. + * + */ +export const zBillingAddress = z.object({ + city: z.string().optional(), + country: z.string(), + line1: z.string(), + line2: z.string().optional(), + postal_code: z.string().optional(), + state: z.string().optional() +}) + +/** + * Fields to set on the workspace's Stripe customer. Every group is + * optional; omit a group to leave that part of the customer unchanged. + * + */ +export const zBillingCompanyDetailsUpdateRequest = z.object({ + address: zBillingAddress.optional(), + company_name: z.string().optional(), + tax_id: zBillingTaxId.optional() +}) + +/** + * Company billing details on file for the workspace's Stripe customer. + * A field is absent until the workspace sets it via PATCH + * /api/billing/company-details. + * + */ +export const zBillingCompanyDetailsResponse = z.object({ + address: zBillingAddress.optional(), + company_name: z.string().optional(), + tax_id: zBillingTaxId.optional() +}) + +export const zBillingCapabilityScope = z.object({ + user_id: z.string(), + workspace_id: z.string() +}) + +/** + * Identifies capability values currently using safe rollout defaults + * instead of deterministic policy results. A true value is UI guidance, + * not evidence that the corresponding write will succeed. + * + */ +export const zBillingCapabilityRolloutDefaults = z.object({ + can_downgrade_to_personal: z.boolean(), + can_subscribe_self_serve: z.boolean(), + can_top_up: z.boolean() +}) + +/** + * Conservative UI guidance. These values do not authorize billing writes; + * each write endpoint independently enforces its permission policy. + * + */ +export const zBillingCapabilities = z.object({ + can_cancel: z.boolean(), + can_change_seats: z.boolean(), + can_downgrade_to_personal: z.boolean(), + can_invite_members: z.boolean(), + can_reactivate: z.boolean(), + can_subscribe_self_serve: z.boolean(), + can_top_up: z.boolean() +}) + +/** + * Effective billing UI guidance for one authenticated user and workspace. + */ +export const zBillingCapabilitiesResponse = z.object({ + capabilities: zBillingCapabilities, + expires_at: z.string().datetime(), + resolved_for: zBillingCapabilityScope, + revision: z.coerce + .bigint() + .min(BigInt('-9223372036854775808'), { + message: 'Invalid value: Expected int64 to be >= -9223372036854775808' + }) + .lte(BigInt(9007199254740991)), + rollout_defaults_applied: zBillingCapabilityRolloutDefaults +}) + /** * Current credit balance and usage details for a workspace. */ @@ -2236,6 +2439,39 @@ export const zAgentThreadCreateRequest = z.object({ workflow_id: z.string().optional() }) +/** + * A user-authored skill pack to create or replace. Plain JSON — a pack body is small enough that a signed-URL upload would be pure overhead. + */ +export const zAgentSkillPublishRequest = z.object({ + always: z.boolean().optional().default(false), + body: z.string(), + description: z.string().max(1024), + name: z + .string() + .max(64) + .regex(/^[A-Za-z0-9._-]*[A-Za-z0-9_-][A-Za-z0-9._-]*$/) +}) + +/** + * One of the caller's user-authored skill packs. + */ +export const zAgentSkill = z.object({ + body: z.string(), + body_hash: z.string(), + created_at: z.string(), + description: z.string(), + id: z.string(), + name: z.string(), + updated_at: z.string() +}) + +/** + * The caller's skill packs, ordered by name. + */ +export const zAgentSkillListResponse = z.object({ + skills: z.array(zAgentSkill) +}) + /** * A user turn posted to the agent. */ @@ -2374,47 +2610,25 @@ export const zAssetCreatedWritable = zAssetWritable.and( }) ) -export const zGetJwksData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * JWKS response */ export const zGetJwksResponse = zJwksResponse -export const zGetOAuthAuthorizationServerData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Authorization-server metadata */ export const zGetOAuthAuthorizationServerResponse = zOAuthAuthorizationServerMetadata -export const zGetOAuthProtectedResourceData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Protected-resource metadata */ export const zGetOAuthProtectedResourceResponse = zOAuthProtectedResourceMetadata -export const zGetOAuthProtectedResourceByPathData = z.object({ - body: z.never().optional(), - path: z.object({ - resourcePath: z.string().regex(/^[a-zA-Z0-9._-]+$/) - }), - query: z.never().optional() +export const zGetOAuthProtectedResourceByPathPath = z.object({ + resourcePath: z.string().regex(/^[a-zA-Z0-9._-]+$/) }) /** @@ -2423,28 +2637,16 @@ export const zGetOAuthProtectedResourceByPathData = z.object({ export const zGetOAuthProtectedResourceByPathResponse = zOAuthProtectedResourceMetadata -export const zGetCustomNodeProxyData = z.object({ - body: z.never().optional(), - path: z.object({ - path: z.string() - }), - query: z.never().optional() +export const zGetCustomNodeProxyPath = z.object({ + path: z.string() }) -export const zPostCustomNodeProxyData = z.object({ - body: z.never().optional(), - path: z.object({ - path: z.string() - }), - query: z.never().optional() +export const zPostCustomNodeProxyPath = z.object({ + path: z.string() }) -export const zAgentGetDraftData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - workflow_id: z.string() - }) +export const zAgentGetDraftQuery = z.object({ + workflow_id: z.string() }) /** @@ -2452,15 +2654,33 @@ export const zAgentGetDraftData = z.object({ */ export const zAgentGetDraftResponse = zAgentDraftSnapshot -export const zAgentListThreadsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - limit: z.number().int().gte(1).lte(100).optional().default(20), - after: z.string().optional() - }) - .optional() +/** + * The caller's skill packs. + */ +export const zAgentListSkillsResponse = zAgentSkillListResponse + +export const zAgentPublishSkillBody = zAgentSkillPublishRequest + +/** + * An existing pack of the same name was replaced. + */ +export const zAgentPublishSkillResponse = zAgentSkill + +export const zAgentDeleteSkillPath = z.object({ + name: z + .string() + .max(64) + .regex(/^[A-Za-z0-9._-]*[A-Za-z0-9_-][A-Za-z0-9._-]*$/) +}) + +/** + * The pack was deleted. + */ +export const zAgentDeleteSkillResponse = z.void() + +export const zAgentListThreadsQuery = z.object({ + limit: z.number().int().gte(1).lte(100).optional().default(20), + after: z.string().optional() }) /** @@ -2468,24 +2688,18 @@ export const zAgentListThreadsData = z.object({ */ export const zAgentListThreadsResponse = zAgentThreadListResponse -export const zAgentCreateThreadData = z.object({ - body: zAgentThreadCreateRequest.optional(), - path: z.never().optional(), - query: z.never().optional() -}) +export const zAgentCreateThreadBody = zAgentThreadCreateRequest /** * Thread created */ export const zAgentCreateThreadResponse = zAgentThreadCreated -export const zAgentAnswerAskData = z.object({ - body: zAgentAnswerRequest, - path: z.object({ - id: z.string(), - ask_id: z.string() - }), - query: z.never().optional() +export const zAgentAnswerAskBody = zAgentAnswerRequest + +export const zAgentAnswerAskPath = z.object({ + id: z.string(), + ask_id: z.string() }) /** @@ -2493,12 +2707,8 @@ export const zAgentAnswerAskData = z.object({ */ export const zAgentAnswerAskResponse = zAgentAnswerAccepted -export const zAgentGetMessagesData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zAgentGetMessagesPath = z.object({ + id: z.string() }) /** @@ -2506,12 +2716,10 @@ export const zAgentGetMessagesData = z.object({ */ export const zAgentGetMessagesResponse = z.array(zAgentMessage) -export const zAgentPostMessageData = z.object({ - body: zAgentPostMessageRequest, - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zAgentPostMessageBody = zAgentPostMessageRequest + +export const zAgentPostMessagePath = z.object({ + id: z.string() }) /** @@ -2519,13 +2727,9 @@ export const zAgentPostMessageData = z.object({ */ export const zAgentPostMessageResponse = zAgentTurnAccepted -export const zAgentCancelMessageData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string(), - message_id: z.string() - }), - query: z.never().optional() +export const zAgentCancelMessagePath = z.object({ + id: z.string(), + message_id: z.string() }) /** @@ -2533,29 +2737,24 @@ export const zAgentCancelMessageData = z.object({ */ export const zAgentCancelMessageResponse = zAgentCancelAccepted -export const zListAssetsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - include_tags: z.array(z.string()).optional(), - exclude_tags: z.array(z.string()).optional(), - tags_all: z.array(z.string()).optional(), - tags_any: z.array(z.string()).optional(), - tags_none: z.array(z.string()).optional(), - name_contains: z.string().optional(), - metadata_filter: z.string().optional(), - limit: z.number().int().gte(1).lte(500).optional().default(20), - offset: z.number().int().gte(0).optional().default(0), - sort: z - .enum(['name', 'created_at', 'updated_at', 'size', 'last_access_time']) - .optional(), - order: z.enum(['asc', 'desc']).optional(), - include_public: z.boolean().optional().default(true), - hash: z.string().optional(), - after: z.string().optional() - }) +export const zListAssetsQuery = z.object({ + include_tags: z.array(z.string()).optional(), + exclude_tags: z.array(z.string()).optional(), + tags_all: z.array(z.string()).optional(), + tags_any: z.array(z.string()).optional(), + tags_none: z.array(z.string()).optional(), + name_contains: z.string().optional(), + metadata_filter: z.string().optional(), + limit: z.number().int().gte(1).lte(500).optional().default(20), + offset: z.number().int().gte(0).optional().default(0), + sort: z + .enum(['name', 'created_at', 'updated_at', 'size', 'last_access_time']) .optional() + .default('created_at'), + order: z.enum(['asc', 'desc']).optional().default('desc'), + include_public: z.boolean().optional().default(true), + hash: z.string().optional(), + after: z.string().optional() }) /** @@ -2563,22 +2762,18 @@ export const zListAssetsData = z.object({ */ export const zListAssetsResponse2 = zListAssetsResponse -export const zCreateAssetData = z.object({ - body: z.object({ - file: z.string(), - hash: z - .string() - .regex(/^(blake3|sha256):[a-f0-9]{64}$/) - .optional(), - id: z.string().uuid().optional(), - mime_type: z.string().optional(), - name: z.string().optional(), - preview_id: z.string().uuid().optional(), - tags: z.string().optional(), - user_metadata: z.string().optional() - }), - path: z.never().optional(), - query: z.never().optional() +export const zCreateAssetBody = z.object({ + file: z.string(), + hash: z + .string() + .regex(/^(blake3|sha256):[a-f0-9]{64}$/) + .optional(), + id: z.string().uuid().optional(), + mime_type: z.string().optional(), + name: z.string().optional(), + preview_id: z.string().uuid().optional(), + tags: z.string().optional(), + user_metadata: z.string().optional() }) /** @@ -2588,12 +2783,8 @@ export const zCreateAssetData = z.object({ */ export const zCreateAssetResponse = zAssetCreated -export const zDeleteAssetData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zDeleteAssetPath = z.object({ + id: z.string().uuid() }) /** @@ -2601,12 +2792,8 @@ export const zDeleteAssetData = z.object({ */ export const zDeleteAssetResponse = z.void() -export const zGetAssetByIdData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zGetAssetByIdPath = z.object({ + id: z.string().uuid() }) /** @@ -2614,17 +2801,15 @@ export const zGetAssetByIdData = z.object({ */ export const zGetAssetByIdResponse = zAsset -export const zUpdateAssetData = z.object({ - body: z.object({ - mime_type: z.string().optional(), - name: z.string().optional(), - preview_id: z.string().uuid().optional(), - user_metadata: z.record(z.unknown()).optional() - }), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zUpdateAssetBody = z.object({ + mime_type: z.string().optional(), + name: z.string().optional(), + preview_id: z.string().uuid().optional(), + user_metadata: z.record(z.unknown()).optional() +}) + +export const zUpdateAssetPath = z.object({ + id: z.string().uuid() }) /** @@ -2632,16 +2817,12 @@ export const zUpdateAssetData = z.object({ */ export const zUpdateAssetResponse = zAssetUpdated -export const zGetAssetContentData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z - .object({ - disposition: z.enum(['inline', 'attachment']).optional() - }) - .optional() +export const zGetAssetContentPath = z.object({ + id: z.string() +}) + +export const zGetAssetContentQuery = z.object({ + disposition: z.enum(['inline', 'attachment']).optional().default('attachment') }) /** @@ -2649,14 +2830,12 @@ export const zGetAssetContentData = z.object({ */ export const zGetAssetContentResponse = z.string() -export const zRemoveAssetTagsData = z.object({ - body: z.object({ - tags: z.array(z.string()).min(1) - }), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zRemoveAssetTagsBody = z.object({ + tags: z.array(z.string()).min(1) +}) + +export const zRemoveAssetTagsPath = z.object({ + id: z.string().uuid() }) /** @@ -2664,14 +2843,12 @@ export const zRemoveAssetTagsData = z.object({ */ export const zRemoveAssetTagsResponse = zTagsModificationResponse -export const zAddAssetTagsData = z.object({ - body: z.object({ - tags: z.array(z.string()).min(1) - }), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zAddAssetTagsBody = z.object({ + tags: z.array(z.string()).min(1) +}) + +export const zAddAssetTagsPath = z.object({ + id: z.string().uuid() }) /** @@ -2679,15 +2856,11 @@ export const zAddAssetTagsData = z.object({ */ export const zAddAssetTagsResponse = zTagsModificationResponse -export const zCreateAssetDownloadData = z.object({ - body: z.object({ - preview_id: z.string().uuid().optional(), - source_url: z.string().url(), - tags: z.array(z.string()).optional(), - user_metadata: z.record(z.unknown()).optional() - }), - path: z.never().optional(), - query: z.never().optional() +export const zCreateAssetDownloadBody = z.object({ + preview_id: z.string().uuid().optional(), + source_url: z.string().url(), + tags: z.array(z.string()).optional(), + user_metadata: z.record(z.unknown()).optional() }) export const zCreateAssetDownloadResponse = z.union([ @@ -2695,18 +2868,15 @@ export const zCreateAssetDownloadResponse = z.union([ zAssetDownloadResponse ]) -export const zCreateAssetExportData = z.object({ - body: z.object({ - asset_ids: z.array(z.string()).optional(), - include_previews: z.boolean().optional().default(false), - job_asset_name_filters: z.record(z.array(z.string()).min(1)).optional(), - job_ids: z.array(z.string()).optional(), - naming_strategy: z - .enum(['group_by_job_id', 'preserve', 'asset_id', 'group_by_job_time']) - .optional() - }), - path: z.never().optional(), - query: z.never().optional() +export const zCreateAssetExportBody = z.object({ + asset_ids: z.array(z.string()).optional(), + include_previews: z.boolean().optional().default(false), + job_asset_name_filters: z.record(z.array(z.string()).min(1)).optional(), + job_ids: z.array(z.string()).optional(), + naming_strategy: z + .enum(['group_by_job_id', 'preserve', 'asset_id', 'group_by_job_time']) + .optional() + .default('group_by_job_time') }) /** @@ -2714,12 +2884,8 @@ export const zCreateAssetExportData = z.object({ */ export const zCreateAssetExportResponse = zAssetDownloadResponse -export const zDownloadExportData = z.object({ - body: z.never().optional(), - path: z.object({ - exportName: z.string().regex(/^[a-zA-Z0-9_-]+\.zip$/) - }), - query: z.never().optional() +export const zDownloadExportPath = z.object({ + exportName: z.string().regex(/^[a-zA-Z0-9_-]+\.zip$/) }) /** @@ -2727,16 +2893,12 @@ export const zDownloadExportData = z.object({ */ export const zDownloadExportResponse = zExportDownloadUrlResponse -export const zCreateAssetFromHashData = z.object({ - body: z.object({ - hash: z.string().regex(/^blake3:[a-f0-9]{64}$/), - mime_type: z.string().optional(), - name: z.string().optional(), - tags: z.array(z.string()).min(1), - user_metadata: z.record(z.unknown()).optional() - }), - path: z.never().optional(), - query: z.never().optional() +export const zCreateAssetFromHashBody = z.object({ + hash: z.string().regex(/^blake3:[a-f0-9]{64}$/), + mime_type: z.string().optional(), + name: z.string().optional(), + tags: z.array(z.string()).min(1), + user_metadata: z.record(z.unknown()).optional() }) /** @@ -2746,42 +2908,24 @@ export const zCreateAssetFromHashData = z.object({ */ export const zCreateAssetFromHashResponse = zAssetCreated -export const zPostAssetsFromWorkflowData = z.object({ - body: zWorkflowApiAssetsRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zPostAssetsFromWorkflowBody = zWorkflowApiAssetsRequest /** * Success */ export const zPostAssetsFromWorkflowResponse = zWorkflowApiAssetsResponse -export const zCheckAssetByHashData = z.object({ - body: z.never().optional(), - path: z.object({ - hash: z.string().regex(/^blake3:[a-f0-9]{64}$/) - }), - query: z.never().optional() +export const zCheckAssetByHashPath = z.object({ + hash: z.string().regex(/^blake3:[a-f0-9]{64}$/) }) -export const zImportPublishedAssetsData = z.object({ - body: zImportPublishedAssetsRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zImportPublishedAssetsBody = zImportPublishedAssetsRequest /** * Successfully imported assets */ export const zImportPublishedAssetsResponse2 = zImportPublishedAssetsResponse -export const zPruneAssetsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Prune result */ @@ -2790,12 +2934,8 @@ export const zPruneAssetsResponse = z.object({ status: z.string().optional() }) -export const zGetRemoteAssetMetadataData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - url: z.string().url() - }) +export const zGetRemoteAssetMetadataQuery = z.object({ + url: z.string().url() }) /** @@ -2803,14 +2943,8 @@ export const zGetRemoteAssetMetadataData = z.object({ */ export const zGetRemoteAssetMetadataResponse = zAssetMetadataResponse -export const zSeedAssetsData = z.object({ - body: z - .object({ - roots: z.array(z.string()).optional() - }) - .optional(), - path: z.never().optional(), - query: z.never().optional() +export const zSeedAssetsBody = z.object({ + roots: z.array(z.string()).optional() }) /** @@ -2820,12 +2954,6 @@ export const zSeedAssetsResponse = z.object({ status: z.string().optional() }) -export const zCancelAssetSeedData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Scan cancelled */ @@ -2833,33 +2961,21 @@ export const zCancelAssetSeedResponse = z.object({ status: z.string().optional() }) -export const zGetAssetSeedStatusData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Scan progress details (files scanned, total, status, etc.) */ export const zGetAssetSeedStatusResponse = z.record(z.unknown()) -export const zGetAssetTagHistogramData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - include_tags: z.array(z.string()).optional(), - exclude_tags: z.array(z.string()).optional(), - tags_all: z.array(z.string()).optional(), - tags_any: z.array(z.string()).optional(), - tags_none: z.array(z.string()).optional(), - name_contains: z.string().optional(), - metadata_filter: z.string().optional(), - limit: z.number().int().gte(1).lte(1000).optional().default(100), - include_public: z.boolean().optional().default(true) - }) - .optional() +export const zGetAssetTagHistogramQuery = z.object({ + include_tags: z.array(z.string()).optional(), + exclude_tags: z.array(z.string()).optional(), + tags_all: z.array(z.string()).optional(), + tags_any: z.array(z.string()).optional(), + tags_none: z.array(z.string()).optional(), + name_contains: z.string().optional(), + metadata_filter: z.string().optional(), + limit: z.number().int().gte(1).lte(1000).optional().default(100), + include_public: z.boolean().optional().default(true) }) /** @@ -2867,22 +2983,14 @@ export const zGetAssetTagHistogramData = z.object({ */ export const zGetAssetTagHistogramResponse = zAssetTagHistogramResponse -export const zCreateDesktopLoginCodeData = z.object({ - body: zDesktopLoginCodeCreateRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateDesktopLoginCodeBody = zDesktopLoginCodeCreateRequest /** * Login code created */ export const zCreateDesktopLoginCodeResponse = zDesktopLoginCodeCreateResponse -export const zExchangeDesktopLoginCodeData = z.object({ - body: zDesktopLoginCodeExchangeRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zExchangeDesktopLoginCodeBody = zDesktopLoginCodeExchangeRequest /** * Pending (not yet redeemed) or complete with a custom token @@ -2890,86 +2998,67 @@ export const zExchangeDesktopLoginCodeData = z.object({ export const zExchangeDesktopLoginCodeResponse = zDesktopLoginCodeExchangeResponse -export const zRedeemDesktopLoginCodeData = z.object({ - body: zDesktopLoginCodeRedeemRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zRedeemDesktopLoginCodeBody = zDesktopLoginCodeRedeemRequest /** * Code redeemed (or already redeemed by the same user) */ export const zRedeemDesktopLoginCodeResponse = zDesktopLoginCodeRedeemResponse -export const zDeleteSessionData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Session deleted successfully */ export const zDeleteSessionResponse2 = zDeleteSessionResponse -export const zCreateSessionData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Session created successfully */ export const zCreateSessionResponse2 = zCreateSessionResponse -export const zExchangeTokenData = z.object({ - body: zExchangeTokenRequest.optional(), - path: z.never().optional(), - query: z.never().optional() -}) +export const zExchangeTokenBody = zExchangeTokenRequest /** * Token exchanged successfully */ export const zExchangeTokenResponse2 = zExchangeTokenResponse -export const zGetBillingBalanceData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Credit balance */ export const zGetBillingBalanceResponse = zBillingBalanceResponse -export const zGetChurnkeyAuthData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) +/** + * Effective billing capabilities + */ +export const zGetBillingCapabilitiesResponse = zBillingCapabilitiesResponse /** * Success */ export const zGetChurnkeyAuthResponse = zChurnkeyAuthResponse -export const zGetBillingEventsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - page: z.number().int().gte(1).optional().default(1), - limit: z.number().int().gte(1).lte(100).optional().default(20), - scope: z.enum(['self', 'workspace', 'user']).optional(), - user_id: z.string().optional(), - filter: z.string().optional(), - start_date: z.string().datetime().optional(), - end_date: z.string().datetime().optional() - }) - .optional() +/** + * Success + */ +export const zGetBillingCompanyDetailsResponse = zBillingCompanyDetailsResponse + +export const zUpdateBillingCompanyDetailsBody = + zBillingCompanyDetailsUpdateRequest + +/** + * Success + */ +export const zUpdateBillingCompanyDetailsResponse = + zBillingCompanyDetailsResponse + +export const zGetBillingEventsQuery = z.object({ + page: z.number().int().gte(1).optional().default(1), + limit: z.number().int().gte(1).lte(100).optional().default(20), + scope: z.enum(['self', 'workspace', 'user']).optional().default('self'), + user_id: z.string().optional(), + filter: z.string().optional(), + start_date: z.string().datetime().optional(), + end_date: z.string().datetime().optional() }) /** @@ -2977,12 +3066,8 @@ export const zGetBillingEventsData = z.object({ */ export const zGetBillingEventsResponse = zBillingEventsResponse -export const zGetBillingOpStatusData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zGetBillingOpStatusPath = z.object({ + id: z.string() }) /** @@ -2990,106 +3075,72 @@ export const zGetBillingOpStatusData = z.object({ */ export const zGetBillingOpStatusResponse = zBillingOpStatusResponse -export const zGetPaymentPortalData = z.object({ - body: zPaymentPortalRequest.optional(), - path: z.never().optional(), - query: z.never().optional() -}) +/** + * Saved payment methods + */ +export const zListSavedPaymentMethodsResponse = z.array(zSavedPaymentMethod) + +export const zGetPaymentPortalBody = zPaymentPortalRequest /** * Success */ export const zGetPaymentPortalResponse = zPaymentPortalResponse -export const zGetBillingPlansData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Available plans with pricing */ export const zGetBillingPlansResponse = zBillingPlansResponse -export const zPreviewSubscribeData = z.object({ - body: zPreviewSubscribeRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zPreviewSubscribeBody = zPreviewSubscribeRequest /** * Subscription preview */ export const zPreviewSubscribeResponse2 = zPreviewSubscribeResponse -export const zGetBillingStatusData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Billing status */ export const zGetBillingStatusResponse = zBillingStatusResponse -export const zSubscribeData = z.object({ - body: zSubscribeRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zSubscribeBody = zSubscribeRequest /** * Subscription created or payment method needed */ export const zSubscribeResponse2 = zSubscribeResponse -export const zCancelSubscriptionData = z.object({ - body: zCancelSubscriptionRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCancelSubscriptionBody = zCancelSubscriptionRequest /** * Subscription cancellation scheduled */ export const zCancelSubscriptionResponse2 = zCancelSubscriptionResponse -export const zResubscribeData = z.object({ - body: zResubscribeRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zResubscribeBody = zResubscribeRequest /** * Subscription resumed successfully */ export const zResubscribeResponse2 = zResubscribeResponse -export const zCreateTopupData = z.object({ - body: zCreateTopupRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateTopupBody = zCreateTopupRequest /** * Top-up initiated successfully */ export const zCreateTopupResponse2 = zCreateTopupResponse -export const zGetBillingUsageTimeSeriesData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - group_by: z.enum(['model', 'endpoint', 'product']).optional(), - granularity: z.enum(['hour', 'day', 'month']).optional(), - starting_on: z.string().datetime().optional(), - ending_before: z.string().datetime().optional(), - months: z.number().int().gte(1).lte(24).optional().default(6) - }) +export const zGetBillingUsageTimeSeriesQuery = z.object({ + group_by: z + .enum(['model', 'endpoint', 'product']) .optional() + .default('model'), + granularity: z.enum(['hour', 'day', 'month']).optional().default('month'), + starting_on: z.string().datetime().optional(), + ending_before: z.string().datetime().optional(), + months: z.number().int().gte(1).lte(24).optional().default(6) }) /** @@ -3097,34 +3148,18 @@ export const zGetBillingUsageTimeSeriesData = z.object({ */ export const zGetBillingUsageTimeSeriesResponse = zUsageTimeSeries -export const zGetEmbeddingsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Embedding names */ export const zGetEmbeddingsResponse = z.array(z.string()) -export const zGetModelFoldersData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success - List of model folders */ export const zGetModelFoldersResponse = z.array(zModelFolder) -export const zGetModelsInFolderData = z.object({ - body: z.never().optional(), - path: z.object({ - folder: z.string() - }), - query: z.never().optional() +export const zGetModelsInFolderPath = z.object({ + folder: z.string() }) /** @@ -3132,34 +3167,14 @@ export const zGetModelsInFolderData = z.object({ */ export const zGetModelsInFolderResponse = z.array(zModelFile) -export const zGetModelPreviewData = z.object({ - body: z.never().optional(), - path: z.object({ - folder: z.string(), - path_index: z.number().int(), - filename: z.string() - }), - query: z.never().optional() -}) - -export const zGetNodeInfoSchemaData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - -export const zGetNodeByIdData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zGetModelPreviewPath = z.object({ + folder: z.string(), + path_index: z.number().int(), + filename: z.string() }) -export const zGetExtensionsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() +export const zGetNodeByIdPath = z.object({ + id: z.string() }) /** @@ -3167,12 +3182,6 @@ export const zGetExtensionsData = z.object({ */ export const zGetExtensionsResponse = z.array(z.string()) -export const zGetFeaturesData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success */ @@ -3188,23 +3197,15 @@ export const zGetFeaturesResponse = z.object({ supports_preview_metadata: z.boolean().optional() }) -export const zSubmitFeedbackData = z.object({ - body: zFeedbackRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zSubmitFeedbackBody = zFeedbackRequest /** * Feedback submitted successfully */ export const zSubmitFeedbackResponse = zFeedbackResponse -export const zGetMaskLayersData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - filename: z.string() - }) +export const zGetMaskLayersQuery = z.object({ + filename: z.string() }) /** @@ -3217,21 +3218,9 @@ export const zGetMaskLayersResponse = z.object({ painted_masked: z.string().nullish() }) -export const zFreeMemoryData = z.object({ - body: z - .object({ - free_memory: z.boolean().optional(), - unload_models: z.boolean().optional() - }) - .optional(), - path: z.never().optional(), - query: z.never().optional() -}) - -export const zGetGlobalSubgraphsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() +export const zFreeMemoryBody = z.object({ + free_memory: z.boolean().optional(), + unload_models: z.boolean().optional() }) /** @@ -3239,12 +3228,8 @@ export const zGetGlobalSubgraphsData = z.object({ */ export const zGetGlobalSubgraphsResponse = z.record(zGlobalSubgraphInfo) -export const zGetGlobalSubgraphData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zGetGlobalSubgraphPath = z.object({ + id: z.string() }) /** @@ -3252,35 +3237,15 @@ export const zGetGlobalSubgraphData = z.object({ */ export const zGetGlobalSubgraphResponse = zGlobalSubgraphData -export const zGetLegacyHistoryData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - -export const zManageHistoryData = z.object({ - body: zHistoryManageRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zManageHistoryBody = zHistoryManageRequest -export const zGetLegacyHistoryByIdData = z.object({ - body: z.never().optional(), - path: z.object({ - prompt_id: z.string() - }), - query: z.never().optional() +export const zGetLegacyHistoryByIdPath = z.object({ + prompt_id: z.string() }) -export const zGetHistoryData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - max_items: z.number().int().optional(), - offset: z.number().int().optional().default(0) - }) - .optional() +export const zGetHistoryQuery = z.object({ + max_items: z.number().int().optional(), + offset: z.number().int().optional().default(0) }) /** @@ -3288,12 +3253,8 @@ export const zGetHistoryData = z.object({ */ export const zGetHistoryResponse = zHistoryResponse -export const zGetHistoryForPromptData = z.object({ - body: z.never().optional(), - path: z.object({ - prompt_id: z.string() - }), - query: z.never().optional() +export const zGetHistoryForPromptPath = z.object({ + prompt_id: z.string() }) /** @@ -3301,25 +3262,15 @@ export const zGetHistoryForPromptData = z.object({ */ export const zGetHistoryForPromptResponse = zHistoryDetailResponse -export const zCreateHubAssetUploadUrlData = z.object({ - body: zHubAssetUploadUrlRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateHubAssetUploadUrlBody = zHubAssetUploadUrlRequest /** * Presigned upload URL and token */ export const zCreateHubAssetUploadUrlResponse = zHubAssetUploadUrlResponse -export const zListHubLabelsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - type: z.enum(['tag', 'model', 'custom_node']).optional() - }) - .optional() +export const zListHubLabelsQuery = z.object({ + type: z.enum(['tag', 'model', 'custom_node']).optional() }) /** @@ -3327,23 +3278,15 @@ export const zListHubLabelsData = z.object({ */ export const zListHubLabelsResponse = zHubLabelListResponse -export const zCreateHubProfileData = z.object({ - body: zCreateHubProfileRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateHubProfileBody = zCreateHubProfileRequest /** * Hub profile created */ export const zCreateHubProfileResponse = zHubProfile -export const zGetHubProfileByUsernameData = z.object({ - body: z.never().optional(), - path: z.object({ - username: z.string() - }), - query: z.never().optional() +export const zGetHubProfileByUsernamePath = z.object({ + username: z.string() }) /** @@ -3351,12 +3294,10 @@ export const zGetHubProfileByUsernameData = z.object({ */ export const zGetHubProfileByUsernameResponse = zHubProfile -export const zUpdateHubProfileData = z.object({ - body: zUpdateHubProfileRequest, - path: z.object({ - username: z.string() - }), - query: z.never().optional() +export const zUpdateHubProfileBody = zUpdateHubProfileRequest + +export const zUpdateHubProfilePath = z.object({ + username: z.string() }) /** @@ -3364,12 +3305,8 @@ export const zUpdateHubProfileData = z.object({ */ export const zUpdateHubProfileResponse = zHubProfile -export const zCheckHubUsernameData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - username: z.string() - }) +export const zCheckHubUsernameQuery = z.object({ + username: z.string() }) /** @@ -3377,31 +3314,19 @@ export const zCheckHubUsernameData = z.object({ */ export const zCheckHubUsernameResponse = zHubUsernameCheckResponse -export const zGetMyHubProfileData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Hub profile */ export const zGetMyHubProfileResponse = zHubProfile -export const zListHubWorkflowsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - cursor: z.string().optional(), - limit: z.number().int().gte(1).lte(100).optional().default(20), - search: z.string().optional(), - tag: z.string().optional(), - username: z.string().optional(), - detail: z.boolean().optional().default(false), - status: z.array(zHubWorkflowStatus).optional() - }) - .optional() +export const zListHubWorkflowsQuery = z.object({ + cursor: z.string().optional(), + limit: z.number().int().gte(1).lte(100).optional().default(20), + search: z.string().optional(), + tag: z.string().optional(), + username: z.string().optional(), + detail: z.boolean().optional().default(false), + status: z.array(zHubWorkflowStatus).optional() }) /** @@ -3409,23 +3334,15 @@ export const zListHubWorkflowsData = z.object({ */ export const zListHubWorkflowsResponse = zHubWorkflowListResponse -export const zPublishHubWorkflowData = z.object({ - body: zPublishHubWorkflowRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zPublishHubWorkflowBody = zPublishHubWorkflowRequest /** * Workflow published to hub */ export const zPublishHubWorkflowResponse = zHubWorkflowDetail -export const zDeleteHubWorkflowData = z.object({ - body: z.never().optional(), - path: z.object({ - share_id: z.string() - }), - query: z.never().optional() +export const zDeleteHubWorkflowPath = z.object({ + share_id: z.string() }) /** @@ -3433,12 +3350,8 @@ export const zDeleteHubWorkflowData = z.object({ */ export const zDeleteHubWorkflowResponse = z.void() -export const zGetHubWorkflowData = z.object({ - body: z.never().optional(), - path: z.object({ - share_id: z.string() - }), - query: z.never().optional() +export const zGetHubWorkflowPath = z.object({ + share_id: z.string() }) /** @@ -3446,14 +3359,8 @@ export const zGetHubWorkflowData = z.object({ */ export const zGetHubWorkflowResponse = zHubWorkflowDetail -export const zListHubWorkflowIndexData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - status: z.array(zHubWorkflowStatus).optional() - }) - .optional() +export const zListHubWorkflowIndexQuery = z.object({ + status: z.array(zHubWorkflowStatus).optional() }) /** @@ -3461,40 +3368,20 @@ export const zListHubWorkflowIndexData = z.object({ */ export const zListHubWorkflowIndexResponse = z.array(zHubWorkflowTemplateEntry) -export const zGetI18nData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Nested map of locale to translation key-value pairs */ export const zGetI18nResponse = z.record(z.unknown()) -export const zCreateInputUploadUrlData = z.object({ - body: zInputUploadUrlRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateInputUploadUrlBody = zInputUploadUrlRequest /** * Upload grant minted */ export const zCreateInputUploadUrlResponse = zUploadGrantResponse -export const zInterruptJobData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - -export const zAcceptWorkspaceInviteData = z.object({ - body: z.never().optional(), - path: z.object({ - token: z.string() - }), - query: z.never().optional() +export const zAcceptWorkspaceInvitePath = z.object({ + token: z.string() }) /** @@ -3502,28 +3389,16 @@ export const zAcceptWorkspaceInviteData = z.object({ */ export const zAcceptWorkspaceInviteResponse = zAcceptInviteResponse -export const zGetLegacyJobByIdData = z.object({ - body: z.never().optional(), - path: z.object({ - job_id: z.string() - }), - query: z.never().optional() +export const zGetLegacyJobByIdPath = z.object({ + job_id: z.string() }) -export const zGetLegacyJobOutputsData = z.object({ - body: z.never().optional(), - path: z.object({ - job_id: z.string() - }), - query: z.never().optional() +export const zGetLegacyJobOutputsPath = z.object({ + job_id: z.string() }) -export const zGetJobStatusData = z.object({ - body: z.never().optional(), - path: z.object({ - job_id: z.string().uuid() - }), - query: z.never().optional() +export const zGetJobStatusPath = z.object({ + job_id: z.string().uuid() }) /** @@ -3531,21 +3406,18 @@ export const zGetJobStatusData = z.object({ */ export const zGetJobStatusResponse = zJobStatusResponse -export const zListJobsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - status: z.string().optional(), - workflow_id: z.string().optional(), - output_type: z.enum(['image', 'video', 'audio', '3d']).optional(), - sort_by: z.enum(['create_time', 'execution_time']).optional(), - sort_order: z.enum(['asc', 'desc']).optional(), - after: z.string().optional(), - offset: z.number().int().gte(0).optional().default(0), - limit: z.number().int().gte(1).lte(1000).optional().default(100) - }) +export const zListJobsQuery = z.object({ + status: z.string().optional(), + workflow_id: z.string().optional(), + output_type: z.enum(['image', 'video', 'audio', '3d']).optional(), + sort_by: z + .enum(['create_time', 'execution_time']) .optional() + .default('create_time'), + sort_order: z.enum(['asc', 'desc']).optional().default('desc'), + after: z.string().optional(), + offset: z.number().int().gte(0).optional().default(0), + limit: z.number().int().gte(1).lte(1000).optional().default(100) }) /** @@ -3553,16 +3425,12 @@ export const zListJobsData = z.object({ */ export const zListJobsResponse = zJobsListResponse -export const zGetJobDetailData = z.object({ - body: z.never().optional(), - path: z.object({ - job_id: z.string().uuid() - }), - query: z - .object({ - short_link: z.enum(['ephemeral_tool_chain', 'default']).optional() - }) - .optional() +export const zGetJobDetailPath = z.object({ + job_id: z.string().uuid() +}) + +export const zGetJobDetailQuery = z.object({ + short_link: z.enum(['ephemeral_tool_chain', 'default']).optional() }) /** @@ -3570,17 +3438,13 @@ export const zGetJobDetailData = z.object({ */ export const zGetJobDetailResponse = zJobDetailResponse -export const zGetJobAssetsData = z.object({ - body: z.never().optional(), - path: z.object({ - job_id: z.string().uuid() - }), - query: z - .object({ - limit: z.number().int().gte(1).lte(500).optional().default(20), - offset: z.number().int().gte(0).optional().default(0) - }) - .optional() +export const zGetJobAssetsPath = z.object({ + job_id: z.string().uuid() +}) + +export const zGetJobAssetsQuery = z.object({ + limit: z.number().int().gte(1).lte(500).optional().default(20), + offset: z.number().int().gte(0).optional().default(0) }) /** @@ -3588,12 +3452,8 @@ export const zGetJobAssetsData = z.object({ */ export const zGetJobAssetsResponse = zJobAssetsResponse -export const zCancelJobData = z.object({ - body: z.never().optional(), - path: z.object({ - job_id: z.string().uuid() - }), - query: z.never().optional() +export const zCancelJobPath = z.object({ + job_id: z.string().uuid() }) /** @@ -3601,35 +3461,15 @@ export const zCancelJobData = z.object({ */ export const zCancelJobResponse = zJobCancelResponse -export const zCancelJobsData = z.object({ - body: zJobsCancelRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCancelJobsBody = zJobsCancelRequest /** * Success - cancel requests dispatched (or jobs were already terminal) */ export const zCancelJobsResponse = zJobsCancelResponse -export const zGetLegacyModelsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - -export const zGetLegacyModelsByFolderData = z.object({ - body: z.never().optional(), - path: z.object({ - folder: z.string() - }), - query: z.never().optional() -}) - -export const zGetNodeReplacementsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() +export const zGetLegacyModelsByFolderPath = z.object({ + folder: z.string() }) /** @@ -3637,29 +3477,13 @@ export const zGetNodeReplacementsData = z.object({ */ export const zGetNodeReplacementsResponse = z.record(z.unknown()) -export const zGetNodeInfoData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success */ export const zGetNodeInfoResponse = z.record(zNodeInfo) -export const zGetLegacyObjectInfoByNodeClassData = z.object({ - body: z.never().optional(), - path: z.object({ - node_class: z.string() - }), - query: z.never().optional() -}) - -export const zGetPromptInfoData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() +export const zGetLegacyObjectInfoByNodeClassPath = z.object({ + node_class: z.string() }) /** @@ -3667,29 +3491,15 @@ export const zGetPromptInfoData = z.object({ */ export const zGetPromptInfoResponse = zPromptInfo -export const zExecutePromptData = z.object({ - body: zPromptRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zExecutePromptBody = zPromptRequest /** * Success - Prompt accepted */ export const zExecutePromptResponse = zPromptResponse -export const zGetLegacyPromptByIdData = z.object({ - body: z.never().optional(), - path: z.object({ - prompt_id: z.string() - }), - query: z.never().optional() -}) - -export const zGetProvidersData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() +export const zGetLegacyPromptByIdPath = z.object({ + prompt_id: z.string() }) /** @@ -3697,56 +3507,32 @@ export const zGetProvidersData = z.object({ */ export const zGetProvidersResponse = zProviderCatalogResponse -export const zGetQueueInfoData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success */ export const zGetQueueInfoResponse = zQueueInfo -export const zManageQueueData = z.object({ - body: zQueueManageRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zManageQueueBody = zQueueManageRequest /** * Success */ export const zManageQueueResponse = zQueueManageResponse -export const zListSecretsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success */ export const zListSecretsResponse = zSecretListResponse -export const zCreateSecretData = z.object({ - body: zCreateSecretRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateSecretBody = zCreateSecretRequest /** * Secret created successfully */ export const zCreateSecretResponse = zSecretResponse -export const zDeleteSecretData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zDeleteSecretPath = z.object({ + id: z.string().uuid() }) /** @@ -3754,12 +3540,8 @@ export const zDeleteSecretData = z.object({ */ export const zDeleteSecretResponse = z.void() -export const zGetSecretData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zGetSecretPath = z.object({ + id: z.string().uuid() }) /** @@ -3767,12 +3549,10 @@ export const zGetSecretData = z.object({ */ export const zGetSecretResponse = zSecretResponse -export const zUpdateSecretData = z.object({ - body: zUpdateSecretRequest, - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zUpdateSecretBody = zUpdateSecretRequest + +export const zUpdateSecretPath = z.object({ + id: z.string().uuid() }) /** @@ -3780,45 +3560,28 @@ export const zUpdateSecretData = z.object({ */ export const zUpdateSecretResponse = zSecretResponse -export const zListSecretProvidersData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success */ export const zListSecretProvidersResponse = zSecretProvidersResponse -export const zGetAllSettingsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * User settings as key-value pairs */ export const zGetAllSettingsResponse = z.record(z.unknown()) -export const zUpdateMultipleSettingsData = z.object({ - body: z.record(z.unknown()), - path: z.never().optional(), - query: z.never().optional() -}) +/** + * Settings to update as key-value pairs + */ +export const zUpdateMultipleSettingsBody = z.record(z.unknown()) /** * Updated user settings */ export const zUpdateMultipleSettingsResponse = z.record(z.unknown()) -export const zGetSettingByIdData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zGetSettingByIdPath = z.object({ + id: z.string() }) /** @@ -3828,12 +3591,13 @@ export const zGetSettingByIdResponse = z.object({ value: z.unknown().optional() }) -export const zUpdateSettingByIdData = z.object({ - body: z.unknown(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +/** + * New value for the setting + */ +export const zUpdateSettingByIdBody = z.unknown() + +export const zUpdateSettingByIdPath = z.object({ + id: z.string() }) /** @@ -3843,30 +3607,18 @@ export const zUpdateSettingByIdResponse = z.object({ value: z.unknown().optional() }) -export const zGetSystemStatsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success */ export const zGetSystemStatsResponse = zSystemStatsResponse -export const zListTagsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - prefix: z.string().optional(), - limit: z.number().int().gte(1).lte(1000).optional().default(100), - offset: z.number().int().gte(0).optional().default(0), - order: z.enum(['count_desc', 'name_asc']).optional(), - include_zero: z.boolean().optional().default(false), - include_public: z.boolean().optional().default(true) - }) - .optional() +export const zListTagsQuery = z.object({ + prefix: z.string().optional(), + limit: z.number().int().gte(1).lte(1000).optional().default(100), + offset: z.number().int().gte(0).optional().default(0), + order: z.enum(['count_desc', 'name_asc']).optional().default('count_desc'), + include_zero: z.boolean().optional().default(false), + include_public: z.boolean().optional().default(true) }) /** @@ -3874,21 +3626,15 @@ export const zListTagsData = z.object({ */ export const zListTagsResponse2 = zListTagsResponse -export const zListTasksData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - task_name: z.string().optional(), - idempotency_key: z.string().optional(), - status: z.string().optional(), - created_after: z.string().datetime().optional(), - created_before: z.string().datetime().optional(), - sort_order: z.enum(['asc', 'desc']).optional(), - offset: z.number().int().gte(0).optional().default(0), - limit: z.number().int().gte(1).lte(100).optional().default(20) - }) - .optional() +export const zListTasksQuery = z.object({ + task_name: z.string().optional(), + idempotency_key: z.string().optional(), + status: z.string().optional(), + created_after: z.string().datetime().optional(), + created_before: z.string().datetime().optional(), + sort_order: z.enum(['asc', 'desc']).optional().default('desc'), + offset: z.number().int().gte(0).optional().default(0), + limit: z.number().int().gte(1).lte(100).optional().default(20) }) /** @@ -3896,12 +3642,8 @@ export const zListTasksData = z.object({ */ export const zListTasksResponse = zTasksListResponse -export const zGetTaskData = z.object({ - body: z.never().optional(), - path: z.object({ - task_id: z.string().uuid() - }), - query: z.never().optional() +export const zGetTaskPath = z.object({ + task_id: z.string().uuid() }) /** @@ -3909,15 +3651,11 @@ export const zGetTaskData = z.object({ */ export const zGetTaskResponse = zTaskResponse -export const zUploadImageData = z.object({ - body: z.object({ - image: z.string(), - overwrite: z.string().optional(), - subfolder: z.string().optional(), - type: z.string().optional() - }), - path: z.never().optional(), - query: z.never().optional() +export const zUploadImageBody = z.object({ + image: z.string(), + overwrite: z.string().optional(), + subfolder: z.string().optional(), + type: z.string().optional() }) /** @@ -3929,13 +3667,9 @@ export const zUploadImageResponse = z.object({ type: z.string().optional() }) -export const zUploadMaskData = z.object({ - body: z.object({ - image: z.string(), - original_ref: z.string() - }), - path: z.never().optional(), - query: z.never().optional() +export const zUploadMaskBody = z.object({ + image: z.string(), + original_ref: z.string() }) /** @@ -3947,12 +3681,10 @@ export const zUploadMaskResponse = z.object({ type: z.string().optional() }) -export const zUploadGrantPutData = z.object({ - body: z.string(), - path: z.object({ - upload_id: z.string() - }), - query: z.never().optional() +export const zUploadGrantPutBody = z.string() + +export const zUploadGrantPutPath = z.object({ + upload_id: z.string() }) export const zUploadGrantPutResponse = z.union([ @@ -3960,28 +3692,16 @@ export const zUploadGrantPutResponse = z.union([ zWorkflowResponse ]) -export const zGetUserData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Success */ export const zGetUserResponse = zUserResponse -export const zGetUserdataData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - dir: z.string().optional(), - recurse: z.boolean().optional().default(false), - split: z.boolean().optional().default(false), - full_info: z.boolean().optional().default(false) - }) - .optional() +export const zGetUserdataQuery = z.object({ + dir: z.string().optional(), + recurse: z.boolean().optional().default(false), + split: z.boolean().optional().default(false), + full_info: z.boolean().optional().default(false) }) /** @@ -3989,12 +3709,8 @@ export const zGetUserdataData = z.object({ */ export const zGetUserdataResponse = zGetUserDataResponseFull -export const zDeleteUserdataFileData = z.object({ - body: z.never().optional(), - path: z.object({ - file: z.string() - }), - query: z.never().optional() +export const zDeleteUserdataFilePath = z.object({ + file: z.string() }) /** @@ -4002,12 +3718,8 @@ export const zDeleteUserdataFileData = z.object({ */ export const zDeleteUserdataFileResponse = z.void() -export const zGetUserdataFileData = z.object({ - body: z.never().optional(), - path: z.object({ - file: z.string() - }), - query: z.never().optional() +export const zGetUserdataFilePath = z.object({ + file: z.string() }) /** @@ -4015,17 +3727,15 @@ export const zGetUserdataFileData = z.object({ */ export const zGetUserdataFileResponse = z.string() -export const zPostUserdataFileData = z.object({ - body: z.string(), - path: z.object({ - file: z.string() - }), - query: z - .object({ - overwrite: z.enum(['true', 'false']).optional(), - full_info: z.enum(['true', 'false']).optional() - }) - .optional() +export const zPostUserdataFileBody = z.string() + +export const zPostUserdataFilePath = z.object({ + file: z.string() +}) + +export const zPostUserdataFileQuery = z.object({ + overwrite: z.enum(['true', 'false']).optional().default('true'), + full_info: z.enum(['true', 'false']).optional().default('false') }) /** @@ -4033,17 +3743,13 @@ export const zPostUserdataFileData = z.object({ */ export const zPostUserdataFileResponse = zUserDataResponseFull -export const zMoveUserdataFileData = z.object({ - body: z.never().optional(), - path: z.object({ - file: z.string(), - dest: z.string() - }), - query: z - .object({ - overwrite: z.enum(['true', 'false']).optional() - }) - .optional() +export const zMoveUserdataFilePath = z.object({ + file: z.string(), + dest: z.string() +}) + +export const zMoveUserdataFileQuery = z.object({ + overwrite: z.enum(['true', 'false']).optional().default('true') }) /** @@ -4051,12 +3757,8 @@ export const zMoveUserdataFileData = z.object({ */ export const zMoveUserdataFileResponse = zUserDataResponseFull -export const zGetUserdataFilePublishData = z.object({ - body: z.never().optional(), - path: z.object({ - file: z.string() - }), - query: z.never().optional() +export const zGetUserdataFilePublishPath = z.object({ + file: z.string() }) /** @@ -4064,12 +3766,10 @@ export const zGetUserdataFilePublishData = z.object({ */ export const zGetUserdataFilePublishResponse = zWorkflowPublishInfo -export const zPostUserdataFilePublishData = z.object({ - body: zPublishWorkflowAssetsRequest, - path: z.object({ - file: z.string() - }), - query: z.never().optional() +export const zPostUserdataFilePublishBody = zPublishWorkflowAssetsRequest + +export const zPostUserdataFilePublishPath = z.object({ + file: z.string() }) /** @@ -4077,12 +3777,6 @@ export const zPostUserdataFilePublishData = z.object({ */ export const zPostUserdataFilePublishResponse = zWorkflowPublishInfo -export const zGetUsersInfoData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Userdata storage information */ @@ -4091,18 +3785,8 @@ export const zGetUsersInfoResponse = z.object({ storage: z.string() }) -export const zGetLegacyUserdataV2Data = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - -export const zGetVhsQueryVideoData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - filename: z.string() - }) +export const zGetVhsQueryVideoQuery = z.object({ + filename: z.string() }) /** @@ -4117,41 +3801,29 @@ export const zGetVhsQueryVideoResponse = z.object({ }) }) -export const zGetVhsViewAudioData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - filename: z.string(), - type: z.string().optional(), - subfolder: z.string().optional() - }) +export const zGetVhsViewAudioQuery = z.object({ + filename: z.string(), + type: z.string().optional(), + subfolder: z.string().optional() }) -export const zGetVhsViewVideoData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - filename: z.string(), - type: z.string().optional(), - subfolder: z.string().optional() - }) +export const zGetVhsViewVideoQuery = z.object({ + filename: z.string(), + type: z.string().optional(), + subfolder: z.string().optional() }) -export const zViewFileData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - filename: z.string(), - subfolder: z.string().optional(), - type: z.string().optional(), - fullpath: z.string().optional(), - format: z.string().optional(), - frame_rate: z.number().int().optional(), - workflow: z.string().optional(), - timestamp: z.number().int().optional(), - channel: z.string().optional(), - res: z.number().int().gte(64).lte(1024).optional() - }) +export const zViewFileQuery = z.object({ + filename: z.string(), + subfolder: z.string().optional(), + type: z.string().optional(), + fullpath: z.string().optional(), + format: z.string().optional(), + frame_rate: z.number().int().optional(), + workflow: z.string().optional(), + timestamp: z.number().int().optional(), + channel: z.string().optional(), + res: z.number().int().gte(64).lte(1024).optional() }) /** @@ -4159,26 +3831,12 @@ export const zViewFileData = z.object({ */ export const zViewFileResponse = z.string() -export const zGetLegacyViewMetadataData = z.object({ - body: z.never().optional(), - path: z.object({ - folder_name: z.string() - }), - query: z.never().optional() -}) - -export const zGetApiViewVideoAliasData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - filename: z.string() - }) +export const zGetLegacyViewMetadataPath = z.object({ + folder_name: z.string() }) -export const zGetWorkflowTemplatesData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() +export const zGetApiViewVideoAliasQuery = z.object({ + filename: z.string() }) /** @@ -4186,19 +3844,16 @@ export const zGetWorkflowTemplatesData = z.object({ */ export const zGetWorkflowTemplatesResponse = z.record(z.unknown()) -export const zListWorkflowsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - limit: z.number().int().lte(100).optional().default(20), - offset: z.number().int().optional().default(0), - name: z.string().optional(), - default_view: z.enum(['workflow', 'app']).optional(), - sort: z.enum(['create_time', 'update_time', 'name']).optional(), - order: z.enum(['asc', 'desc']).optional() - }) +export const zListWorkflowsQuery = z.object({ + limit: z.number().int().lte(100).optional().default(20), + offset: z.number().int().optional().default(0), + name: z.string().optional(), + default_view: z.enum(['workflow', 'app']).optional(), + sort: z + .enum(['create_time', 'update_time', 'name']) .optional() + .default('create_time'), + order: z.enum(['asc', 'desc']).optional().default('desc') }) /** @@ -4206,23 +3861,15 @@ export const zListWorkflowsData = z.object({ */ export const zListWorkflowsResponse = zWorkflowListResponse -export const zCreateWorkflowData = z.object({ - body: zCreateWorkflowRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateWorkflowBody = zCreateWorkflowRequest /** * Workflow created successfully */ export const zCreateWorkflowResponse = zWorkflowResponse -export const zDeleteWorkflowData = z.object({ - body: z.never().optional(), - path: z.object({ - workflow_id: z.string() - }), - query: z.never().optional() +export const zDeleteWorkflowPath = z.object({ + workflow_id: z.string() }) /** @@ -4230,12 +3877,8 @@ export const zDeleteWorkflowData = z.object({ */ export const zDeleteWorkflowResponse = z.void() -export const zGetWorkflowData = z.object({ - body: z.never().optional(), - path: z.object({ - workflow_id: z.string() - }), - query: z.never().optional() +export const zGetWorkflowPath = z.object({ + workflow_id: z.string() }) /** @@ -4243,12 +3886,10 @@ export const zGetWorkflowData = z.object({ */ export const zGetWorkflowResponse = zWorkflowResponse -export const zUpdateWorkflowData = z.object({ - body: zUpdateWorkflowRequest, - path: z.object({ - workflow_id: z.string() - }), - query: z.never().optional() +export const zUpdateWorkflowBody = zUpdateWorkflowRequest + +export const zUpdateWorkflowPath = z.object({ + workflow_id: z.string() }) /** @@ -4256,12 +3897,8 @@ export const zUpdateWorkflowData = z.object({ */ export const zUpdateWorkflowResponse = zWorkflowResponse -export const zGetWorkflowContentData = z.object({ - body: z.never().optional(), - path: z.object({ - workflow_id: z.string() - }), - query: z.never().optional() +export const zGetWorkflowContentPath = z.object({ + workflow_id: z.string() }) /** @@ -4269,12 +3906,10 @@ export const zGetWorkflowContentData = z.object({ */ export const zGetWorkflowContentResponse = zWorkflowVersionContentResponse -export const zForkWorkflowData = z.object({ - body: zForkWorkflowRequest, - path: z.object({ - workflow_id: z.string() - }), - query: z.never().optional() +export const zForkWorkflowBody = zForkWorkflowRequest + +export const zForkWorkflowPath = z.object({ + workflow_id: z.string() }) /** @@ -4282,12 +3917,10 @@ export const zForkWorkflowData = z.object({ */ export const zForkWorkflowResponse = zWorkflowResponse -export const zCreateWorkflowVersionData = z.object({ - body: zCreateWorkflowVersionRequest, - path: z.object({ - workflow_id: z.string() - }), - query: z.never().optional() +export const zCreateWorkflowVersionBody = zCreateWorkflowVersionRequest + +export const zCreateWorkflowVersionPath = z.object({ + workflow_id: z.string() }) /** @@ -4295,12 +3928,8 @@ export const zCreateWorkflowVersionData = z.object({ */ export const zCreateWorkflowVersionResponse = zWorkflowVersionResponse -export const zGetPublishedWorkflowData = z.object({ - body: z.never().optional(), - path: z.object({ - share_id: z.string() - }), - query: z.never().optional() +export const zGetPublishedWorkflowPath = z.object({ + share_id: z.string() }) /** @@ -4308,25 +3937,15 @@ export const zGetPublishedWorkflowData = z.object({ */ export const zGetPublishedWorkflowResponse = zPublishedWorkflowDetail -export const zCreateWorkflowUploadUrlData = z.object({ - body: zWorkflowUploadUrlRequest.optional(), - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateWorkflowUploadUrlBody = zWorkflowUploadUrlRequest /** * Upload grant minted */ export const zCreateWorkflowUploadUrlResponse = zUploadGrantResponse -export const zListWorkspaceApiKeysData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - include_revoked: z.boolean().optional().default(false) - }) - .optional() +export const zListWorkspaceApiKeysQuery = z.object({ + include_revoked: z.boolean().optional().default(false) }) /** @@ -4334,23 +3953,15 @@ export const zListWorkspaceApiKeysData = z.object({ */ export const zListWorkspaceApiKeysResponse2 = zListWorkspaceApiKeysResponse -export const zCreateWorkspaceApiKeyData = z.object({ - body: zCreateWorkspaceApiKeyRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateWorkspaceApiKeyBody = zCreateWorkspaceApiKeyRequest /** * API key created (plaintext returned once) */ export const zCreateWorkspaceApiKeyResponse2 = zCreateWorkspaceApiKeyResponse -export const zRevokeWorkspaceApiKeyData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string().uuid() - }), - query: z.never().optional() +export const zRevokeWorkspaceApiKeyPath = z.object({ + id: z.string().uuid() }) /** @@ -4358,34 +3969,20 @@ export const zRevokeWorkspaceApiKeyData = z.object({ */ export const zRevokeWorkspaceApiKeyResponse = z.void() -export const zListWorkspaceInvitesData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * List of pending invites */ export const zListWorkspaceInvitesResponse = zListInvitesResponse -export const zCreateWorkspaceInviteData = z.object({ - body: zCreateInviteRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateWorkspaceInviteBody = zCreateInviteRequest /** * Invite created */ export const zCreateWorkspaceInviteResponse = zPendingInvite -export const zRevokeWorkspaceInviteData = z.object({ - body: z.never().optional(), - path: z.object({ - inviteId: z.string() - }), - query: z.never().optional() +export const zRevokeWorkspaceInvitePath = z.object({ + inviteId: z.string() }) /** @@ -4393,12 +3990,8 @@ export const zRevokeWorkspaceInviteData = z.object({ */ export const zRevokeWorkspaceInviteResponse = z.void() -export const zResendWorkspaceInviteData = z.object({ - body: z.never().optional(), - path: z.object({ - inviteId: z.string() - }), - query: z.never().optional() +export const zResendWorkspaceInvitePath = z.object({ + inviteId: z.string() }) /** @@ -4406,26 +3999,14 @@ export const zResendWorkspaceInviteData = z.object({ */ export const zResendWorkspaceInviteResponse = zPendingInvite -export const zLeaveWorkspaceData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Successfully left workspace */ export const zLeaveWorkspaceResponse = z.void() -export const zListWorkspaceMembersData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - offset: z.number().int().gte(0).optional().default(0), - limit: z.number().int().gte(1).lte(100).optional().default(20) - }) - .optional() +export const zListWorkspaceMembersQuery = z.object({ + offset: z.number().int().gte(0).optional().default(0), + limit: z.number().int().gte(1).lte(100).optional().default(20) }) /** @@ -4433,12 +4014,8 @@ export const zListWorkspaceMembersData = z.object({ */ export const zListWorkspaceMembersResponse = zListMembersResponse -export const zBulkRevokeWorkspaceMemberApiKeysData = z.object({ - body: z.never().optional(), - path: z.object({ - user_id: z.string().min(1) - }), - query: z.never().optional() +export const zBulkRevokeWorkspaceMemberApiKeysPath = z.object({ + user_id: z.string().min(1) }) /** @@ -4447,12 +4024,8 @@ export const zBulkRevokeWorkspaceMemberApiKeysData = z.object({ export const zBulkRevokeWorkspaceMemberApiKeysResponse = zBulkRevokeApiKeysResponse -export const zRemoveWorkspaceMemberData = z.object({ - body: z.never().optional(), - path: z.object({ - userId: z.string() - }), - query: z.never().optional() +export const zRemoveWorkspaceMemberPath = z.object({ + userId: z.string() }) /** @@ -4460,12 +4033,10 @@ export const zRemoveWorkspaceMemberData = z.object({ */ export const zRemoveWorkspaceMemberResponse = z.void() -export const zUpdateWorkspaceMemberRoleData = z.object({ - body: zUpdateMemberRoleRequest, - path: z.object({ - userId: z.string() - }), - query: z.never().optional() +export const zUpdateWorkspaceMemberRoleBody = zUpdateMemberRoleRequest + +export const zUpdateWorkspaceMemberRolePath = z.object({ + userId: z.string() }) /** @@ -4473,56 +4044,32 @@ export const zUpdateWorkspaceMemberRoleData = z.object({ */ export const zUpdateWorkspaceMemberRoleResponse = zMember -export const zGetProviderPolicyData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * The policy document */ export const zGetProviderPolicyResponse = zProviderPolicy -export const zPutProviderPolicyData = z.object({ - body: zProviderPolicy, - path: z.never().optional(), - query: z.never().optional() -}) +export const zPutProviderPolicyBody = zProviderPolicy /** * Policy replaced */ export const zPutProviderPolicyResponse = zProviderPolicy -export const zListWorkspacesData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * List of workspaces */ export const zListWorkspacesResponse2 = zListWorkspacesResponse -export const zCreateWorkspaceData = z.object({ - body: zCreateWorkspaceRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zCreateWorkspaceBody = zCreateWorkspaceRequest /** * Workspace created */ export const zCreateWorkspaceResponse = zWorkspace -export const zDeleteWorkspaceData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zDeleteWorkspacePath = z.object({ + id: z.string() }) /** @@ -4530,12 +4077,8 @@ export const zDeleteWorkspaceData = z.object({ */ export const zDeleteWorkspaceResponse = z.void() -export const zGetWorkspaceData = z.object({ - body: z.never().optional(), - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zGetWorkspacePath = z.object({ + id: z.string() }) /** @@ -4543,12 +4086,10 @@ export const zGetWorkspaceData = z.object({ */ export const zGetWorkspaceResponse = zWorkspace -export const zUpdateWorkspaceData = z.object({ - body: zUpdateWorkspaceRequest, - path: z.object({ - id: z.string() - }), - query: z.never().optional() +export const zUpdateWorkspaceBody = zUpdateWorkspaceRequest + +export const zUpdateWorkspacePath = z.object({ + id: z.string() }) /** @@ -4556,26 +4097,17 @@ export const zUpdateWorkspaceData = z.object({ */ export const zUpdateWorkspaceResponse = zWorkspace -export const zGetStaticExtensionsData = z.object({ - body: z.never().optional(), - path: z.object({ - path: z.string() - }), - query: z.never().optional() -}) +/** + * The credential's workspace + */ +export const zGetCurrentWorkspaceResponse = zCurrentWorkspaceResponse -export const zRedirectExtensionScriptsData = z.object({ - body: z.never().optional(), - path: z.object({ - file: z.string() - }), - query: z.never().optional() +export const zGetStaticExtensionsPath = z.object({ + path: z.string() }) -export const zGetHealthData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() +export const zRedirectExtensionScriptsPath = z.object({ + file: z.string() }) /** @@ -4583,12 +4115,6 @@ export const zGetHealthData = z.object({ */ export const zGetHealthResponse = z.string() -export const zGetInternalFolderPathsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Map of folder type name to list of path entries */ @@ -4596,23 +4122,11 @@ export const zGetInternalFolderPathsResponse = z.record( z.array(z.array(z.string())) ) -export const zGetInternalLogsData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Log text */ export const zGetInternalLogsResponse = z.string() -export const zGetInternalLogsRawData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.never().optional() -}) - /** * Structured log data */ @@ -4633,39 +4147,25 @@ export const zGetInternalLogsRawResponse = z.object({ .optional() }) -export const zSubscribeToLogsData = z.object({ - body: z.object({ - clientId: z.string(), - enabled: z.boolean() - }), - path: z.never().optional(), - query: z.never().optional() +export const zSubscribeToLogsBody = z.object({ + clientId: z.string(), + enabled: z.boolean() }) -export const zGetStaticKjwebAsyncData = z.object({ - body: z.never().optional(), - path: z.object({ - path: z.string() - }), - query: z.never().optional() +export const zGetStaticKjwebAsyncPath = z.object({ + path: z.string() }) -export const zGetOAuthAuthorizeData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - response_type: z.string().optional(), - client_id: z.string().optional(), - redirect_uri: z.string().optional(), - scope: z.string().optional(), - state: z.string().optional(), - code_challenge: z.string().optional(), - code_challenge_method: z.string().optional(), - resource: z.string().optional(), - oauth_request_id: z.string().optional() - }) - .optional() +export const zGetOAuthAuthorizeQuery = z.object({ + response_type: z.string().optional(), + client_id: z.string().optional(), + redirect_uri: z.string().optional(), + scope: z.string().optional(), + state: z.string().optional(), + code_challenge: z.string().optional(), + code_challenge_method: z.string().optional(), + resource: z.string().optional(), + oauth_request_id: z.string().optional() }) /** @@ -4674,15 +4174,11 @@ export const zGetOAuthAuthorizeData = z.object({ */ export const zGetOAuthAuthorizeResponse = zOAuthConsentChallenge -export const zPostOAuthAuthorizeData = z.object({ - body: z.object({ - csrf_token: z.string(), - decision: z.enum(['allow', 'deny']), - oauth_request_id: z.string().uuid(), - workspace_id: z.string() - }), - path: z.never().optional(), - query: z.never().optional() +export const zPostOAuthAuthorizeBody = z.object({ + csrf_token: z.string(), + decision: z.enum(['allow', 'deny']), + oauth_request_id: z.string().uuid(), + workspace_id: z.string() }) /** @@ -4690,30 +4186,22 @@ export const zPostOAuthAuthorizeData = z.object({ */ export const zPostOAuthAuthorizeResponse = zOAuthAuthorizeRedirectResponse -export const zPostOAuthRegisterData = z.object({ - body: zOAuthRegisterRequest, - path: z.never().optional(), - query: z.never().optional() -}) +export const zPostOAuthRegisterBody = zOAuthRegisterRequest /** * Registered. Body echoes the metadata RFC 7591 §3.2.1 requires. */ export const zPostOAuthRegisterResponse = zOAuthRegisterResponse -export const zPostOAuthTokenData = z.object({ - body: z.object({ - client_id: z.string(), - client_secret: z.string().optional(), - code: z.string().optional(), - code_verifier: z.string().optional(), - grant_type: z.enum(['authorization_code', 'refresh_token']), - redirect_uri: z.string().optional(), - refresh_token: z.string().optional(), - scope: z.string().optional() - }), - path: z.never().optional(), - query: z.never().optional() +export const zPostOAuthTokenBody = z.object({ + client_id: z.string(), + client_secret: z.string().optional(), + code: z.string().optional(), + code_verifier: z.string().optional(), + grant_type: z.enum(['authorization_code', 'refresh_token']), + redirect_uri: z.string().optional(), + refresh_token: z.string().optional(), + scope: z.string().optional() }) /** @@ -4721,28 +4209,14 @@ export const zPostOAuthTokenData = z.object({ */ export const zPostOAuthTokenResponse = zOAuthTokenResponse -export const zGetTemplateProxyData = z.object({ - body: z.never().optional(), - path: z.object({ - path: z.string() - }), - query: z.never().optional() +export const zGetTemplateProxyPath = z.object({ + path: z.string() }) -export const zGetViewCompatAliasData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z.object({ - filename: z.string() - }) +export const zGetViewCompatAliasQuery = z.object({ + filename: z.string() }) -export const zGetWebsocketData = z.object({ - body: z.never().optional(), - path: z.never().optional(), - query: z - .object({ - clientId: z.string().optional() - }) - .optional() +export const zGetWebsocketQuery = z.object({ + clientId: z.string().optional() }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5f42f3279c9..500f3951dd3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -99,6 +99,9 @@ catalogs: '@storybook/vue3-vite': specifier: ^10.5.6 version: 10.5.6 + '@stripe/stripe-js': + specifier: ^9.12.0 + version: 9.12.1 '@tailwindcss/vite': specifier: ^4.3.2 version: 4.3.2 @@ -517,6 +520,9 @@ importers: '@sparkjsdev/spark': specifier: 'catalog:' version: 2.1.0(three@0.184.0) + '@stripe/stripe-js': + specifier: 'catalog:' + version: 9.12.1 '@tanstack/vue-virtual': specifier: 'catalog:' version: 3.13.32(vue@3.5.41(typescript@6.0.3)) @@ -3881,6 +3887,10 @@ packages: storybook: ^10.5.6 vue: ^3.0.0 + '@stripe/stripe-js@9.12.1': + resolution: {integrity: sha512-KLXPvjA0BfS4dQnW+ddHjwtIXMnIfKYxqmeNMmQCfKjvYog0cSG+Z7ZvK4RH1+bV90GC07nUztWDRWmJLi5HZQ==} + engines: {node: '>=12.16'} + '@swc/helpers@0.5.23': resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==} @@ -12084,6 +12094,8 @@ snapshots: vue: 3.5.41(typescript@6.0.3) vue-component-type-helpers: 3.3.9 + '@stripe/stripe-js@9.12.1': {} + '@swc/helpers@0.5.23': dependencies: tslib: 2.8.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 89f637d1f8d..c0a81f5ea74 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -41,6 +41,7 @@ catalog: '@storybook/addon-mcp': 0.7.0 '@storybook/vue3': ^10.5.6 '@storybook/vue3-vite': ^10.5.6 + '@stripe/stripe-js': ^9.12.0 '@tailwindcss/vite': ^4.3.2 '@tanstack/vue-virtual': ^3.13.12 '@testing-library/jest-dom': ^6.9.1 diff --git a/src/assets/css/style.css b/src/assets/css/style.css index 5957d089293..594854795d5 100644 --- a/src/assets/css/style.css +++ b/src/assets/css/style.css @@ -1,5 +1,18 @@ @import '@comfyorg/design-system/css/style.css'; +/* Toasts teleport to . Reka's modal mode sets pointer-events: none on + the body, which left toast close buttons painted above dialogs but + unclickable — clicks fell through to whatever sat beneath (including the + payment dialog's X, closing the checkout mid-payment). Keep toasts + interactive regardless of modal state. */ +.p-toast { + pointer-events: none; +} + +.p-toast-message { + pointer-events: auto; +} + /* Use 0.001ms instead of 0s so transitionend/animationend events still fire and JS listeners aren't broken. */ .disable-animations *, diff --git a/src/components/dialog/GlobalDialog.test.ts b/src/components/dialog/GlobalDialog.test.ts index 2043e243f86..6d83d4f1386 100644 --- a/src/components/dialog/GlobalDialog.test.ts +++ b/src/components/dialog/GlobalDialog.test.ts @@ -31,10 +31,18 @@ vi.mock( isResubscribing: ref(false), previewData: ref(null), reactivationRequired: ref(false), + quoteIsCurrent: ref(false), + savedPaymentMethods: ref([]), + selectedSavedPaymentMethodId: ref(null), selectedTierKey: ref(null), selectedTeamStop: ref(null), selectedBillingCycle: ref('yearly'), activeCheckoutActionUrl: ref(null), + authenticationState: ref(null), + authenticationError: ref(null), + canRetryAuthentication: ref(false), + isAuthenticating: ref(false), + reconciliationOperationId: ref(null), isPolling: ref(false), isTeamCheckout: computed(() => false), previewVariant: computed(() => null), @@ -45,6 +53,11 @@ vi.mock( handleAddCreditCard: vi.fn(), handleConfirmTransition: vi.fn(), handleTeamSubscribe: vi.fn(), + handleSubscriptionPayment: vi.fn(), + handleTeamSubscriptionPayment: vi.fn(), + retryPaymentAuthentication: vi.fn(), + applyPromotionCode: vi.fn(), + invalidateQuote: vi.fn(), handleResubscribe: vi.fn() }) } diff --git a/src/components/graph/GraphCanvas.firstRunEntry.test.ts b/src/components/graph/GraphCanvas.firstRunEntry.test.ts index 63ac127cc10..6e8496565b3 100644 --- a/src/components/graph/GraphCanvas.firstRunEntry.test.ts +++ b/src/components/graph/GraphCanvas.firstRunEntry.test.ts @@ -16,7 +16,9 @@ import GraphCanvas from './GraphCanvas.vue' * feeds the startup outcome to `handleStartupOutcome`, and the URL workflow * results to `handleUrlWorkflow`. Both composables are unit-tested on their * own; this file covers the seam, so deleting either call from the startup - * sequence fails a test instead of silently disconnecting the feature. + * sequence fails a test instead of silently disconnecting the feature. It also + * pins the order the deep-link loaders depend on: dialogs they open must land + * on top of the overlays `handleStartupOutcome` establishes. */ const mocks = vi.hoisted(() => ({ handleStartupOutcome: vi.fn(), @@ -24,6 +26,7 @@ const mocks = vi.hoisted(() => ({ initializeWorkflow: vi.fn(), loadTemplateFromUrlIfPresent: vi.fn(), loadSharedWorkflowFromUrlIfPresent: vi.fn(), + runUrlActionLoaders: vi.fn(), workspaceStore: { spinner: false, focusMode: false, @@ -88,7 +91,9 @@ vi.mock('@/services/useNewUserService', () => ({ })) vi.mock('@/composables/useUrlActionLoaders', () => ({ - useUrlActionLoaders: () => ({ runUrlActionLoaders: vi.fn() }) + useUrlActionLoaders: () => ({ + runUrlActionLoaders: mocks.runUrlActionLoaders + }) })) vi.mock('@/platform/updates/common/releaseStore', () => ({ @@ -193,6 +198,14 @@ describe('GraphCanvas first-run tour wiring', () => { expect(mocks.handleStartupOutcome).toHaveBeenCalledWith('url-intent') }) + it('settles the startup outcome before running the URL action loaders', async () => { + await mountGraphCanvas() + + expect( + mocks.runUrlActionLoaders.mock.invocationCallOrder[0] + ).toBeGreaterThan(mocks.handleStartupOutcome.mock.invocationCallOrder[0]) + }) + it('offers the tour over a workflow that arrived from the URL', async () => { await mountGraphCanvas() diff --git a/src/composables/useFeatureFlags.test.ts b/src/composables/useFeatureFlags.test.ts index 5e07ce3d902..09e7cc78c18 100644 --- a/src/composables/useFeatureFlags.test.ts +++ b/src/composables/useFeatureFlags.test.ts @@ -147,6 +147,33 @@ describe('useFeatureFlags', () => { }) }) + describe('embeddedCheckoutEnabled', () => { + it.for([ + ['missing', undefined, false], + ['false', false, false], + ['malformed', 'true', false], + ['true', true, true] + ] as const)('is fail-closed for %s values', ([, value, expected]) => { + vi.mocked(api.getServerFeature).mockReturnValue(value) + + const { flags } = useFeatureFlags() + + expect(flags.embeddedCheckoutEnabled).toBe(expected) + expect(api.getServerFeature).toHaveBeenCalledWith( + 'embedded_checked_enabled', + false + ) + }) + + it('is false when feature lookup throws', () => { + vi.mocked(api.getServerFeature).mockImplementation(() => { + throw new Error('feature service unavailable') + }) + + expect(useFeatureFlags().flags.embeddedCheckoutEnabled).toBe(false) + }) + }) + describe('linearToggleEnabled', () => { afterEach(() => { vi.mocked(distributionTypes).isNightly = false diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index 25035e0eaea..45d1ec4e7a8 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -36,6 +36,7 @@ export enum ServerFeatureFlag { UNIFIED_CLOUD_AUTH = 'unified_cloud_auth', BILLING_CONTROL_ENABLED = 'billing_control_enabled', LEGACY_BILLING_MIGRATION_ENABLED = 'legacy_billing_migration_enabled', + EMBEDDED_CHECKOUT_ENABLED = 'embedded_checked_enabled', V1_PAYMENT_RECOVERY = 'v1_payment_recovery', FREE_TIER_JOB_ALLOWANCE_ENABLED = 'free_tier_job_allowance_enabled', CHURNKEY_APP_ID = 'churnkey_app_id', @@ -84,6 +85,14 @@ function resolveAuthGatedFlag( return remoteConfigValue ?? api.getServerFeature(flagKey, false) } +function resolveFailClosedBooleanFlag(flagKey: string): boolean { + try { + return api.getServerFeature(flagKey, false) === true + } catch { + return false + } +} + /** * Composable for reactive access to server-side feature flags */ @@ -209,6 +218,11 @@ export function useFeatureFlags() { cachedLegacyBillingMigrationEnabled ) }, + get embeddedCheckoutEnabled() { + return resolveFailClosedBooleanFlag( + ServerFeatureFlag.EMBEDDED_CHECKOUT_ENABLED + ) + }, get v1PaymentRecovery() { return resolveAuthGatedFlag( ServerFeatureFlag.V1_PAYMENT_RECOVERY, diff --git a/src/composables/useUrlActionLoaders.test.ts b/src/composables/useUrlActionLoaders.test.ts index f9e1a84d9fa..a429650eacc 100644 --- a/src/composables/useUrlActionLoaders.test.ts +++ b/src/composables/useUrlActionLoaders.test.ts @@ -14,10 +14,14 @@ const mocks = vi.hoisted(() => ({ loadCreateWorkspace: vi.fn(async () => undefined), loadPricingTable: vi.fn(async () => undefined), loadTopUp: vi.fn(async () => undefined), + loadPaymentReturn: vi.fn(async () => undefined), + resumePendingPricingFlow: vi.fn(async () => undefined), useInvite: vi.fn(), useCreateWorkspace: vi.fn(), usePricingTable: vi.fn(), - useTopUp: vi.fn() + useTopUp: vi.fn(), + usePaymentReturn: vi.fn(), + useSubscriptionDialog: vi.fn() })) mocks.useInvite.mockImplementation(() => ({ loadInviteFromUrl: mocks.loadInvite @@ -31,6 +35,12 @@ mocks.usePricingTable.mockImplementation(() => ({ mocks.useTopUp.mockImplementation(() => ({ loadTopUpFromUrl: mocks.loadTopUp })) +mocks.usePaymentReturn.mockImplementation(() => ({ + loadPaymentReturnFromUrl: mocks.loadPaymentReturn +})) +mocks.useSubscriptionDialog.mockImplementation(() => ({ + resumePendingPricingFlow: mocks.resumePendingPricingFlow +})) vi.mock('@/platform/workspace/composables/useInviteUrlLoader', () => ({ useInviteUrlLoader: mocks.useInvite @@ -45,6 +55,14 @@ vi.mock( vi.mock('@/platform/cloud/subscription/composables/useTopUpUrlLoader', () => ({ useTopUpUrlLoader: mocks.useTopUp })) +vi.mock( + '@/platform/cloud/subscription/composables/usePaymentReturnUrlLoader', + () => ({ usePaymentReturnUrlLoader: mocks.usePaymentReturn }) +) +vi.mock( + '@/platform/cloud/subscription/composables/useSubscriptionDialog', + () => ({ useSubscriptionDialog: mocks.useSubscriptionDialog }) +) describe('useUrlActionLoaders', () => { beforeEach(() => { @@ -61,6 +79,12 @@ describe('useUrlActionLoaders', () => { mocks.useTopUp.mockImplementation(() => ({ loadTopUpFromUrl: mocks.loadTopUp })) + mocks.usePaymentReturn.mockImplementation(() => ({ + loadPaymentReturnFromUrl: mocks.loadPaymentReturn + })) + mocks.useSubscriptionDialog.mockImplementation(() => ({ + resumePendingPricingFlow: mocks.resumePendingPricingFlow + })) }) it('does not instantiate or run any loader off cloud', async () => { @@ -73,10 +97,14 @@ describe('useUrlActionLoaders', () => { expect(mocks.useCreateWorkspace).not.toHaveBeenCalled() expect(mocks.usePricingTable).not.toHaveBeenCalled() expect(mocks.useTopUp).not.toHaveBeenCalled() + expect(mocks.usePaymentReturn).not.toHaveBeenCalled() + expect(mocks.useSubscriptionDialog).not.toHaveBeenCalled() expect(mocks.loadInvite).not.toHaveBeenCalled() expect(mocks.loadCreateWorkspace).not.toHaveBeenCalled() expect(mocks.loadPricingTable).not.toHaveBeenCalled() expect(mocks.loadTopUp).not.toHaveBeenCalled() + expect(mocks.loadPaymentReturn).not.toHaveBeenCalled() + expect(mocks.resumePendingPricingFlow).not.toHaveBeenCalled() }) it('runs all loaders on Cloud', async () => { @@ -87,6 +115,26 @@ describe('useUrlActionLoaders', () => { expect(mocks.loadCreateWorkspace).toHaveBeenCalledOnce() expect(mocks.loadPricingTable).toHaveBeenCalledOnce() expect(mocks.loadTopUp).toHaveBeenCalledOnce() + expect(mocks.loadPaymentReturn).toHaveBeenCalledOnce() + }) + + it('recovers an interrupted checkout after handling the payment return', async () => { + const { runUrlActionLoaders } = useUrlActionLoaders() + await runUrlActionLoaders() + + expect(mocks.resumePendingPricingFlow).toHaveBeenCalledOnce() + expect( + mocks.resumePendingPricingFlow.mock.invocationCallOrder[0] + ).toBeGreaterThan(mocks.loadPaymentReturn.mock.invocationCallOrder[0]) + }) + + it('isolates a checkout-recovery failure so it does not abort the boot chain', async () => { + mocks.resumePendingPricingFlow.mockRejectedValueOnce(new Error('boom')) + + const { runUrlActionLoaders } = useUrlActionLoaders() + await expect(runUrlActionLoaders()).resolves.toBeUndefined() + + expect(mocks.loadPaymentReturn).toHaveBeenCalledOnce() }) it('isolates a pricing-loader failure so it does not abort the boot chain', async () => { @@ -107,5 +155,7 @@ describe('useUrlActionLoaders', () => { await expect(runUrlActionLoaders()).resolves.toBeUndefined() expect(mocks.loadPricingTable).toHaveBeenCalledOnce() + expect(mocks.loadPaymentReturn).toHaveBeenCalledOnce() + expect(mocks.resumePendingPricingFlow).toHaveBeenCalledOnce() }) }) diff --git a/src/composables/useUrlActionLoaders.ts b/src/composables/useUrlActionLoaders.ts index 42e69bfc1b7..bfac0dea470 100644 --- a/src/composables/useUrlActionLoaders.ts +++ b/src/composables/useUrlActionLoaders.ts @@ -1,4 +1,6 @@ +import { usePaymentReturnUrlLoader } from '@/platform/cloud/subscription/composables/usePaymentReturnUrlLoader' import { usePricingTableUrlLoader } from '@/platform/cloud/subscription/composables/usePricingTableUrlLoader' +import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { useTopUpUrlLoader } from '@/platform/cloud/subscription/composables/useTopUpUrlLoader' import { isCloud } from '@/platform/distribution/types' import { useCreateWorkspaceUrlLoader } from '@/platform/workspace/composables/useCreateWorkspaceUrlLoader' @@ -6,9 +8,10 @@ import { useInviteUrlLoader } from '@/platform/workspace/composables/useInviteUr /** * Aggregates the query-param "deep link" loaders the cloud app checks on mount - * (`?invite`, `?create_workspace`, `?pricing`, `?topup`). The loaders are - * instantiated in setup so their `useRoute`/`useRouter` resolve; call - * `runUrlActionLoaders()` from `onMounted` once the app is ready. + * (`?invite`, `?create_workspace`, `?pricing`, `?topup`), then recovers an + * interrupted checkout. The loaders are instantiated in setup so their + * `useRoute`/`useRouter` resolve; call `runUrlActionLoaders()` from + * `onMounted` once the app is ready. */ export function useUrlActionLoaders() { const inviteUrlLoader = isCloud ? useInviteUrlLoader() : null @@ -17,6 +20,8 @@ export function useUrlActionLoaders() { : null const pricingTableUrlLoader = isCloud ? usePricingTableUrlLoader() : null const topUpUrlLoader = isCloud ? useTopUpUrlLoader() : null + const paymentReturnUrlLoader = isCloud ? usePaymentReturnUrlLoader() : null + const subscriptionDialog = isCloud ? useSubscriptionDialog() : null async function runUrlActionLoaders() { // Accept workspace invite from URL if present (e.g., ?invite=TOKEN). @@ -60,6 +65,34 @@ export function useUrlActionLoaders() { ) } } + + // Handle the return leg of a redirect payment (Stripe appends + // payment_intent/redirect_status params): strip the params and refresh + // billing status so the pending checkout resumes polling immediately. + if (paymentReturnUrlLoader) { + try { + await paymentReturnUrlLoader.loadPaymentReturnFromUrl() + } catch (error) { + console.error( + '[UrlActionLoaders] Failed to handle payment return from URL:', + error + ) + } + } + + // Reopen a checkout that was interrupted by a redirect payment. Runs here, + // not during workspace init, so the first-run and Templates overlays are + // already settled and the recovered dialog is reachable. + if (subscriptionDialog) { + try { + await subscriptionDialog.resumePendingPricingFlow() + } catch (error) { + console.error( + '[UrlActionLoaders] Failed to resume pending billing flow:', + error + ) + } + } } return { runUrlActionLoaders } diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 2c4eac862d6..98b4d09c499 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2680,7 +2680,7 @@ "addMoreCreditsToRun": "Add more credits to run", "insufficientWorkflowMessage": "You don't have enough credits to run this workflow.", "creditsDescription": "Credits are used to run workflows or partner nodes.", - "chargedImmediatelyNote": "Your saved card is charged immediately.", + "chargedImmediatelyNote": "Your saved payment method is charged immediately.", "confirmSubtitle": "Credits are added to this workspace as soon as payment completes.", "confirmTitle": "Confirm", "howManyCredits": "How many credits would you like to add?", @@ -2745,6 +2745,17 @@ "topupSuccess": "Credits added successfully", "topupFailed": "Top-up failed", "topupTimeout": "Top-up verification timed out", + "paymentDeclinedDetail": "Your bank declined this payment. Try another payment method or contact your bank.", + "insufficientFundsDetail": "This payment method has insufficient funds. Try another payment method or contact your bank.", + "expiredCardDetail": "This card has expired. Use a different payment method.", + "incorrectCvcDetail": "The card security code is incorrect. Check it and try again.", + "processingErrorDetail": "Your payment couldn't be processed. Try again or use another payment method.", + "authenticationUnavailable": "Secure payment authentication is unavailable. Please refresh and try again.", + "authenticationFailedDetail": "We couldn't complete payment verification. Please try again.", + "authenticationManagerRequired": "Payment verification needs attention from a workspace billing manager.", + "retryVerification": "Retry verification", + "reconciliationTitle": "Payment received — confirmation pending", + "reconciliationDetail": "Your payment was received, but we couldn't finish updating your workspace. Contact support and include this operation ID:", "cancelFailed": "Failed to cancel subscription", "cancelTimeout": "Subscription cancellation timed out" }, @@ -2894,6 +2905,9 @@ "free": { "name": "Free" }, + "enterprise": { + "name": "Enterprise" + }, "founder": { "name": "Founder's Edition" }, @@ -3053,6 +3067,12 @@ "confirmChange": "Confirm change", "confirmChangeTitle": "Review your scheduled change", "paymentPopupBlocked": "Couldn't open the payment page — please allow popups and try again.", + "paymentMethod": "Payment method", + "stripeMethodChoice": "Your payment details are handled securely by Stripe.", + "alipayRenewalNote": "Alipay authorization will also be used for automatic renewals and future purchases.", + "payAndSubscribe": "Pay and subscribe", + "stripeUnavailable": "Payment options are unavailable. Please refresh and try again.", + "quoteUnavailable": "Unavailable", "switchesToday": "Switches today", "startsOn": "Starts {date}", "yearlySubscription": "Yearly subscription", @@ -3066,7 +3086,7 @@ "creditsRefillMonthlyTo": "Credits refill monthly to", "billedEachMonth": "{amount} billed each month. Cancel anytime.", "stayOnUntil": "You'll stay on {plan} until {date}.", - "termsAgreement": "By continuing, you agree to Comfy Org's {terms} and {privacy}.", + "termsAgreement": "By continuing, you agree to Comfy Org's {terms} and {privacy}, and authorize Comfy Org to charge your payment method each billing period until you cancel.", "terms": "Terms", "privacyPolicy": "Privacy Policy", "addCreditCard": "Add credit card", @@ -3087,7 +3107,22 @@ "confirmationRequired": "Your subscription is cancelled — please confirm the reactivation charge before continuing", "amountChanged": "The charge amount changed since you confirmed it — please review and try again", "unavailable": "We can't confirm this reactivation right now — please choose your plan again" - } + }, + "promoCodePlaceholder": "Promo code", + "applyPromoCode": "Apply", + "applyQuoteBeforeContinuing": "Apply the promo code to refresh your quote before continuing.", + "quoteStale": "Your quote changed. Review the updated amount and try again.", + "quoteRefreshFailed": "Your quote expired and couldn't be refreshed. Choose your plan again.", + "renewsAt": "Renews at {amount} on {date}. Cancel anytime.", + "discountComposition": "Discounts", + "discount": { + "plan": "Plan discount", + "promotion": "Promo code" + }, + "changePaymentMethod": "Change", + "savedPaymentMethod": "Payment method", + "addNewPaymentMethod": "Add new payment method", + "alipay": "Alipay" }, "success": { "allSet": "You're all set", @@ -3096,7 +3131,9 @@ "inviteTitle": "Invite your team", "planUpdated": "Your plan has been successfully updated.", "receiptEmailed": "A receipt has been emailed to you.", - "sendInvites": "Send invites" + "sendInvites": "Send invites", + "promoApplied": "{code} applied.", + "promoRenews": "Renews at {amount} on {date}" } }, "userSettings": { diff --git a/src/main.ts b/src/main.ts index 38fd07172c8..16220fea63c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -24,6 +24,7 @@ import { flushErrorReports } from '@/platform/telemetry/reportError' import '@/lib/litegraph/public/css/litegraph.css' import router from '@/router' import { isDesktop, isNightly } from '@/platform/distribution/types' +import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/paymentReturnUrl' import { useToastStore } from '@/platform/updates/common/toastStore' import { useBootstrapStore } from '@/stores/bootstrapStore' @@ -35,6 +36,8 @@ import { i18n } from './i18n' const isCloud = __DISTRIBUTION__ === 'cloud' const hasHostTelemetryBridge = Boolean(window.__comfyDesktop2?.Telemetry) +if (isCloud) stripPaymentReturnParams() + // Load remote config before initializeApp() below, so getFirebaseConfig() resolves // against the server's runtime values instead of the build-time defaults. const { refreshRemoteConfig } = diff --git a/src/platform/cloud/subscription/billingPolicyCapabilities.test.ts b/src/platform/cloud/subscription/billingPolicyCapabilities.test.ts index bfa043ac38a..c94e875b593 100644 --- a/src/platform/cloud/subscription/billingPolicyCapabilities.test.ts +++ b/src/platform/cloud/subscription/billingPolicyCapabilities.test.ts @@ -18,6 +18,10 @@ describe('getBillingPolicyCapabilities', () => { 'LocalTeamWithoutActiveSubscription', { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } ], + [ + 'LocalEnterpriseWithoutActiveSubscription', + { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } + ], [ 'LocalAndUnknown', { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } @@ -45,6 +49,10 @@ describe('getBillingPolicyCapabilities', () => { 'CloudTeamWithoutActiveSubscription', { topUpAccess: 'subscription-required', showsSubscribeUpsellUI: false } ], + [ + 'CloudEnterpriseWithoutActiveSubscription', + { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } + ], [ 'CloudAndUnknown', { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } diff --git a/src/platform/cloud/subscription/billingPolicyCapabilities.ts b/src/platform/cloud/subscription/billingPolicyCapabilities.ts index a2989b49960..e8869ce05f3 100644 --- a/src/platform/cloud/subscription/billingPolicyCapabilities.ts +++ b/src/platform/cloud/subscription/billingPolicyCapabilities.ts @@ -20,6 +20,8 @@ export function getBillingPolicyCapabilities( return { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } case 'LocalTeamWithoutActiveSubscription': return { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } + case 'LocalEnterpriseWithoutActiveSubscription': + return { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } case 'LocalAndUnknown': return { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } case 'LocalAndFree': @@ -44,6 +46,10 @@ export function getBillingPolicyCapabilities( topUpAccess: 'subscription-required', showsSubscribeUpsellUI: false } + // Sales-managed: reactivation goes through sales, so unlike the lapsed + // self-serve Team state it neither withholds top-up nor upsells. + case 'CloudEnterpriseWithoutActiveSubscription': + return { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } case 'CloudAndUnknown': return { topUpAccess: 'allowed', showsSubscribeUpsellUI: false } case 'CloudAndFree': diff --git a/src/platform/cloud/subscription/billingPolicyState.ts b/src/platform/cloud/subscription/billingPolicyState.ts index 436473f6337..17fc0a5c476 100644 --- a/src/platform/cloud/subscription/billingPolicyState.ts +++ b/src/platform/cloud/subscription/billingPolicyState.ts @@ -1,6 +1,7 @@ export type BillingPolicyState = | { kind: 'LocalWithoutActiveSubscription' } | { kind: 'LocalTeamWithoutActiveSubscription' } + | { kind: 'LocalEnterpriseWithoutActiveSubscription' } | { kind: 'LocalAndUnknown' } | { kind: 'LocalAndFree' } | { kind: 'LocalAndStandard' } @@ -10,6 +11,7 @@ export type BillingPolicyState = | { kind: 'LocalAndTeam' } | { kind: 'CloudWithoutActiveSubscription' } | { kind: 'CloudTeamWithoutActiveSubscription' } + | { kind: 'CloudEnterpriseWithoutActiveSubscription' } | { kind: 'CloudAndUnknown' } | { kind: 'CloudAndFree' } | { kind: 'CloudAndStandard' } diff --git a/src/platform/cloud/subscription/composables/useBillingPolicyState.test.ts b/src/platform/cloud/subscription/composables/useBillingPolicyState.test.ts index e54d2ad5195..e0a902941e2 100644 --- a/src/platform/cloud/subscription/composables/useBillingPolicyState.test.ts +++ b/src/platform/cloud/subscription/composables/useBillingPolicyState.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' +import type { IngestSubscriptionTier } from '@/platform/cloud/subscription/constants/tierPricing' import { deriveBillingPolicyState } from './useBillingPolicyState' describe('deriveBillingPolicyState', () => { @@ -128,4 +129,103 @@ describe('deriveBillingPolicyState', () => { ).toEqual({ kind }) } ) + + // The tier union is generated from the backend spec, so a value outside it is + // reachable at runtime even though the type forbids it. It must resolve to the + // restrictive state, not Unknown: Unknown grants topUpAccess 'allowed', which + // would hand paid-plan access to a tier purely for being unrecognised. + it.for([ + ['CloudWithoutActiveSubscription', true], + ['LocalWithoutActiveSubscription', false] + ] as const)( + 'resolves an unrecognised tier as %s (isCloud=%s)', + ([kind, isCloud]) => { + expect( + deriveBillingPolicyState({ + isCloud, + canAccessSubscriptionFeatures: true, + isTeamPlan: false, + tier: 'SOME_FUTURE_TIER' as IngestSubscriptionTier + }) + ).toEqual({ kind }) + } + ) + + // Sales-managed: active takes the team policy states; lapsed keeps its own + // state so it is never shown the personal subscribe upsell. + it.for<[string, boolean, boolean]>([ + ['CloudAndTeam', true, true], + ['LocalAndTeam', true, false], + ['CloudEnterpriseWithoutActiveSubscription', false, true], + ['LocalEnterpriseWithoutActiveSubscription', false, false] + ])( + 'resolves an ENTERPRISE tier as %s (canAccess=%s, isCloud=%s)', + ([kind, canAccess, isCloud]) => { + expect( + deriveBillingPolicyState({ + isCloud, + canAccessSubscriptionFeatures: canAccess, + isTeamPlan: false, + tier: 'ENTERPRISE' + }) + ).toEqual({ kind }) + } + ) +}) + +// Characterization of the full pre-ENTERPRISE input space. Every row pins the +// behavior that existed before the ENTERPRISE branch was added; a change to +// any of these rows is a regression, not a refactor. +describe('deriveBillingPolicyState regression matrix', () => { + const suffixTable: [ + IngestSubscriptionTier | null, + boolean, // canAccessSubscriptionFeatures + boolean, // isTeamPlan + string + ][] = [ + [null, true, false, 'AndUnknown'], + [null, false, false, 'WithoutActiveSubscription'], + [null, true, true, 'AndTeam'], + [null, false, true, 'TeamWithoutActiveSubscription'], + ['FREE', true, false, 'AndFree'], + ['FREE', false, false, 'WithoutActiveSubscription'], + ['FREE', true, true, 'AndTeam'], + ['FREE', false, true, 'TeamWithoutActiveSubscription'], + ['STANDARD', true, false, 'AndStandard'], + ['STANDARD', false, false, 'WithoutActiveSubscription'], + ['STANDARD', true, true, 'AndTeam'], + ['STANDARD', false, true, 'TeamWithoutActiveSubscription'], + ['CREATOR', true, false, 'AndCreator'], + ['CREATOR', false, false, 'WithoutActiveSubscription'], + ['CREATOR', true, true, 'AndTeam'], + ['CREATOR', false, true, 'TeamWithoutActiveSubscription'], + ['PRO', true, false, 'AndPro'], + ['PRO', false, false, 'WithoutActiveSubscription'], + ['PRO', true, true, 'AndTeam'], + ['PRO', false, true, 'TeamWithoutActiveSubscription'], + ['FOUNDERS_EDITION', true, false, 'AndFounders'], + ['FOUNDERS_EDITION', false, false, 'WithoutActiveSubscription'], + ['FOUNDERS_EDITION', true, true, 'AndTeam'], + ['FOUNDERS_EDITION', false, true, 'TeamWithoutActiveSubscription'], + ['TEAM', true, false, 'AndTeam'], + ['TEAM', false, false, 'TeamWithoutActiveSubscription'], + ['TEAM', true, true, 'AndTeam'], + ['TEAM', false, true, 'TeamWithoutActiveSubscription'] + ] + + it.for(suffixTable)( + 'tier=%s canAccess=%s isTeamPlan=%s stays %s in both distributions', + ([tier, canAccess, isTeamPlan, suffix]) => { + for (const isCloud of [true, false]) { + expect( + deriveBillingPolicyState({ + isCloud, + canAccessSubscriptionFeatures: canAccess, + isTeamPlan, + tier + }) + ).toEqual({ kind: `${isCloud ? 'Cloud' : 'Local'}${suffix}` }) + } + } + ) }) diff --git a/src/platform/cloud/subscription/composables/useBillingPolicyState.ts b/src/platform/cloud/subscription/composables/useBillingPolicyState.ts index c107a7d9604..773af7bc3e8 100644 --- a/src/platform/cloud/subscription/composables/useBillingPolicyState.ts +++ b/src/platform/cloud/subscription/composables/useBillingPolicyState.ts @@ -18,6 +18,18 @@ export function deriveBillingPolicyState(input: { }): BillingPolicyState { const distribution = input.isCloud ? 'Cloud' : 'Local' + // ENTERPRISE is a workspace-level, sales-managed plan and never self-serve. + // Active, it takes the team policy states; lapsed, it keeps its own state so + // it is never classified as plain WithoutActiveSubscription, which would + // expose the personal subscribe upsell to a sales-managed customer. + if (input.tier === 'ENTERPRISE') { + return { + kind: input.canAccessSubscriptionFeatures + ? `${distribution}AndTeam` + : `${distribution}EnterpriseWithoutActiveSubscription` + } + } + if (input.isTeamPlan || input.tier === 'TEAM') { return { kind: input.canAccessSubscriptionFeatures @@ -44,7 +56,24 @@ export function deriveBillingPolicyState(input: { case null: return { kind: `${distribution}AndUnknown` } default: - return input.tier satisfies never + // COMPATIBILITY FALLBACK, NOT A POLICY SIGNAL. + // + // The tier union is generated from the backend spec and can gain values + // without a frontend change, so this must not be a compile error. It + // resolves to the restrictive state rather than Unknown because Unknown + // grants topUpAccess 'allowed' — an unrecognised tier must not be handed + // paid-plan access for the sole reason that this build does not know it. + // + // It is deliberately NOT business-correct: a sales-managed tier that is + // genuinely active collapses to the same state as no subscription at all, + // so any UI keyed off this can offer subscribe/upgrade to someone who is + // already paying. Fail-closed on access, wrong on intent. + // + // Do not build cancellation, reactivation, pricing or upgrade decisions on + // this branch. Those need explicit server-sent capabilities (canOpenPricing, + // canChangePlan, canCancel, canReactivate) so a new tier cannot silently + // inherit a frontend-computed policy. + return { kind: `${distribution}WithoutActiveSubscription` } } } diff --git a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts new file mode 100644 index 00000000000..20574992ce8 --- /dev/null +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/paymentReturnUrl' + +import { usePaymentReturnUrlLoader } from './usePaymentReturnUrlLoader' + +const mocks = vi.hoisted(() => ({ + fetchStatus: vi.fn().mockResolvedValue(undefined), + embeddedCheckoutEnabled: true +})) + +vi.mock('@/composables/billing/useBillingContext', () => ({ + useBillingContext: () => ({ fetchStatus: mocks.fetchStatus }) +})) + +vi.mock('@/composables/useFeatureFlags', () => ({ + useFeatureFlags: () => ({ + flags: { + get embeddedCheckoutEnabled() { + return mocks.embeddedCheckoutEnabled + } + } + }) +})) + +describe('usePaymentReturnUrlLoader', () => { + beforeEach(() => { + mocks.embeddedCheckoutEnabled = true + window.history.replaceState({}, '', '/') + }) + + it('refreshes billing after bootstrap strips Stripe return params', async () => { + window.history.replaceState( + {}, + '', + '/?payment_intent=pi_123&payment_intent_client_secret=pi_123_secret_abc&redirect_status=succeeded&workspace=ws-1' + ) + stripPaymentReturnParams() + + const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() + await loadPaymentReturnFromUrl() + + expect(window.location.search).toBe('?workspace=ws-1') + expect(mocks.fetchStatus).toHaveBeenCalledOnce() + }) + + it('does nothing on an ordinary page load', async () => { + window.history.replaceState({}, '', '/?workspace=ws-1') + + const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() + await loadPaymentReturnFromUrl() + + expect(mocks.fetchStatus).not.toHaveBeenCalled() + }) + + it('does not start embedded recovery while the flag is off', async () => { + mocks.embeddedCheckoutEnabled = false + window.history.replaceState( + {}, + '', + '/?payment_intent=pi_123&redirect_status=succeeded' + ) + stripPaymentReturnParams() + + await usePaymentReturnUrlLoader().loadPaymentReturnFromUrl() + + expect(mocks.fetchStatus).not.toHaveBeenCalled() + }) +}) diff --git a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.ts b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.ts new file mode 100644 index 00000000000..1184c77f017 --- /dev/null +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.ts @@ -0,0 +1,27 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { consumePaymentReturn } from '@/platform/cloud/subscription/utils/paymentReturnUrl' + +/** + * Handles the return leg of a redirect payment method (Alipay). The checkout's + * `return_url` points back at the page it started on, and Stripe appends + * `payment_intent`, `payment_intent_client_secret`, and `redirect_status` to + * it. The client secret is a bearer capability, so it must not linger in the + * address bar or history; strip all three, then refresh billing status so the + * pending-operation recovery resumes polling the in-flight checkout without + * waiting for the next scheduled read. + */ +export function usePaymentReturnUrlLoader() { + const billingContext = useBillingContext() + const { flags } = useFeatureFlags() + + async function loadPaymentReturnFromUrl() { + if (!consumePaymentReturn()) return + if (!flags.embeddedCheckoutEnabled) return + await billingContext.fetchStatus() + } + + return { + loadPaymentReturnFromUrl + } +} diff --git a/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts b/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts index d60029d06ec..8ff2414128a 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionDialog.test.ts @@ -1,5 +1,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { SubscriptionInfo } from '@/composables/billing/types' +import type { + BillingSubscriptionStatus, + TeamCreditStops, + TeamCreditStopSummary +} from '@/platform/workspace/api/workspaceApi' +import { savePendingSubscriptionCheckout } from '@/platform/workspace/utils/pendingSubscriptionCheckout' + import { useSubscriptionDialog } from './useSubscriptionDialog' const mockCloseDialog = vi.fn() @@ -18,6 +26,24 @@ const mockIsLegacyTeamPlan = vi.hoisted(() => ({ value: false })) const mockIsTeamPlan = vi.hoisted(() => ({ value: false })) const mockCurrentPlanSlug = vi.hoisted(() => ({ value: null as string | null })) const mockCanManageSubscription = vi.hoisted(() => ({ value: true })) +const mockEmbeddedCheckoutEnabled = vi.hoisted(() => ({ value: false })) +const mockActiveWorkspaceId = vi.hoisted(() => ({ value: 'workspace-1' })) +const mockUserId = vi.hoisted(() => ({ value: 'user-1' as string | undefined })) +const mockStartOperation = vi.hoisted(() => vi.fn()) +const mockFetchPlans = vi.hoisted(() => vi.fn()) +const mockFetchStatus = vi.hoisted(() => vi.fn()) +const mockTeamCreditStops = vi.hoisted(() => ({ + value: null as TeamCreditStops | null +})) +const mockCurrentTeamCreditStop = vi.hoisted(() => ({ + value: null as TeamCreditStopSummary | null +})) +const mockSubscription = vi.hoisted(() => ({ + value: null as Pick | null +})) +const mockSubscriptionStatus = vi.hoisted(() => ({ + value: null as BillingSubscriptionStatus | null +})) vi.mock('vue', async (importOriginal) => { const actual = await importOriginal() @@ -55,6 +81,16 @@ vi.mock('@/composables/billing/useBillingRouting', () => ({ }) })) +vi.mock('@/composables/useFeatureFlags', () => ({ + useFeatureFlags: () => ({ + flags: { + get embeddedCheckoutEnabled() { + return mockEmbeddedCheckoutEnabled.value + } + } + }) +})) + vi.mock('@/platform/distribution/types', () => ({ get isCloud() { return mockIsCloud.value @@ -63,19 +99,40 @@ vi.mock('@/platform/distribution/types', () => ({ vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({ useTeamWorkspaceStore: () => ({ + get activeWorkspaceId() { + return mockActiveWorkspaceId.value + }, get isInPersonalWorkspace() { return mockIsInPersonalWorkspace.value } }) })) +vi.mock('@/platform/workspace/stores/billingOperationStore', () => ({ + useBillingOperationStore: () => ({ startOperation: mockStartOperation }) +})) + +vi.mock('@/stores/authStore', () => ({ + useAuthStore: () => ({ + get userId() { + return mockUserId.value + } + }) +})) + vi.mock('@/composables/billing/useBillingContext', () => ({ useBillingContext: () => ({ isFreeTier: mockIsFreeTier, isLegacyTeamPlan: mockIsLegacyTeamPlan, isTeamPlan: mockIsTeamPlan, currentPlanSlug: mockCurrentPlanSlug, - tier: mockTier + tier: mockTier, + fetchPlans: mockFetchPlans, + fetchStatus: mockFetchStatus, + teamCreditStops: mockTeamCreditStops, + currentTeamCreditStop: mockCurrentTeamCreditStop, + subscription: mockSubscription, + subscriptionStatus: mockSubscriptionStatus }) })) @@ -117,6 +174,17 @@ describe('useSubscriptionDialog', () => { mockIsTeamPlan.value = false mockCurrentPlanSlug.value = null mockCanManageSubscription.value = true + mockEmbeddedCheckoutEnabled.value = false + mockActiveWorkspaceId.value = 'workspace-1' + mockUserId.value = 'user-1' + mockStartOperation.mockResolvedValue({ status: 'succeeded' }) + mockFetchPlans.mockResolvedValue(undefined) + mockFetchStatus.mockResolvedValue(undefined) + mockTeamCreditStops.value = null + mockCurrentTeamCreditStop.value = null + mockSubscription.value = null + mockSubscriptionStatus.value = null + sessionStorage.clear() }) describe('showPricingTable', () => { @@ -301,6 +369,19 @@ describe('useSubscriptionDialog', () => { const props = mockShowLayoutDialog.mock.calls[0][0].props expect(props.initialPlanMode).toBe('personal') expect(props).not.toHaveProperty('onChooseTeam') + expect(props.embeddedCheckoutEnabled).toBe(false) + }) + + it('enables embedded checkout only for the exact server flag', () => { + mockShouldUseWorkspaceBilling.value = true + mockEmbeddedCheckoutEnabled.value = true + const { showPricingTable } = useSubscriptionDialog() + + showPricingTable() + + expect( + mockShowLayoutDialog.mock.calls[0][0].props.embeddedCheckoutEnabled + ).toBe(true) }) it('routes an existing per-member (legacy) team subscriber to the old team table', () => { @@ -543,7 +624,7 @@ describe('useSubscriptionDialog', () => { it('does nothing when no resume intent is stored', () => { const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() expect(mockShowLayoutDialog).not.toHaveBeenCalled() }) @@ -555,7 +636,7 @@ describe('useSubscriptionDialog', () => { mockCurrentPlanSlug.value = 'creator-monthly' const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() expect(sessionStorage.getItem('comfy:resume-team-pricing')).toBeNull() expect(mockShowLayoutDialog).toHaveBeenCalledWith( @@ -571,7 +652,7 @@ describe('useSubscriptionDialog', () => { mockIsInPersonalWorkspace.value = true const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() expect(sessionStorage.getItem('comfy:resume-team-pricing')).toBeNull() expect(mockShowLayoutDialog).not.toHaveBeenCalled() @@ -582,11 +663,241 @@ describe('useSubscriptionDialog', () => { mockIsInPersonalWorkspace.value = false const { resumePendingPricingFlow } = useSubscriptionDialog() - resumePendingPricingFlow() + void resumePendingPricingFlow() mockShowLayoutDialog.mockClear() - resumePendingPricingFlow() + void resumePendingPricingFlow() + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + }) + + it('reconciles a failed redirect and reopens the attempted checkout', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'failed' }) + savePendingSubscriptionCheckout({ + operationId: 'op-alipay', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).toHaveBeenCalledWith( + 'op-alipay', + 'subscription', + { + tier: 'creator', + cycle: 'monthly', + attemptStartedAt: expect.any(Number) + } + ) + expect(mockShowLayoutDialog).toHaveBeenCalledWith( + expect.objectContaining({ + props: expect.objectContaining({ + initialPlanMode: 'personal', + initialCheckout: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + } + }) + }) + ) + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('completes a succeeded redirect silently', async () => { + mockShouldUseWorkspaceBilling.value = true + savePendingSubscriptionCheckout({ + operationId: 'op-succeeded', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).toHaveBeenCalledOnce() expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('does not reopen checkout when reconciliation times out', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'timeout' }) + savePendingSubscriptionCheckout({ + operationId: 'op-timeout', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'creator', + billingCycle: 'monthly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('clears a checkout owned by another user without reconciling it', async () => { + savePendingSubscriptionCheckout({ + operationId: 'op-other-user', + workspaceId: 'workspace-1', + ownerUid: 'user-2', + selection: { + planMode: 'personal', + tierKey: 'standard', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).not.toHaveBeenCalled() + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('clears a checkout for another workspace without reconciling it', async () => { + savePendingSubscriptionCheckout({ + operationId: 'op-other-workspace', + workspaceId: 'workspace-2', + ownerUid: 'user-1', + selection: { + planMode: 'personal', + tierKey: 'standard', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockStartOperation).not.toHaveBeenCalled() + expect(mockShowLayoutDialog).not.toHaveBeenCalled() + expect( + sessionStorage.getItem('comfy:pending-subscription-checkout') + ).toBeNull() + }) + + it('restores a Team plan change from fresh catalog and subscription state', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'failed' }) + mockFetchPlans.mockImplementationOnce(async () => { + mockTeamCreditStops.value = { + default_stop_index: 0, + stops: [ + { + id: 'team_700', + credits: 147_700, + monthly: { + list_price_cents: 70_000, + price_cents: 66_500 + }, + yearly: { + list_price_cents: 70_000, + price_cents: 63_000 + } + } + ] + } + }) + mockFetchStatus.mockImplementationOnce(async () => { + mockCurrentTeamCreditStop.value = { + id: 'team_400', + stop_usd: 400, + credits_monthly: 84_400 + } + mockSubscription.value = { duration: 'MONTHLY' } + mockSubscriptionStatus.value = 'active' + }) + savePendingSubscriptionCheckout({ + operationId: 'op-team-change', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'team', + teamCreditStopId: 'team_700', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockShowLayoutDialog).toHaveBeenCalledWith( + expect.objectContaining({ + props: expect.objectContaining({ + initialCheckout: { + planMode: 'team', + stop: { + id: 'team_700', + credits: 147_700, + usd: 700, + discountedUsd: 630 + }, + billingCycle: 'yearly', + isChange: true + } + }) + }) + ) + }) + + it('falls back to Team pricing when the stop catalog is unavailable', async () => { + mockShouldUseWorkspaceBilling.value = true + mockStartOperation.mockResolvedValueOnce({ status: 'failed' }) + savePendingSubscriptionCheckout({ + operationId: 'op-team-catalog-failure', + workspaceId: 'workspace-1', + ownerUid: 'user-1', + selection: { + planMode: 'team', + teamCreditStopId: 'team_700', + billingCycle: 'yearly' + }, + attemptedAt: Date.now() + }) + + const { resumePendingPricingFlow } = useSubscriptionDialog() + await resumePendingPricingFlow() + + expect(mockShowLayoutDialog).toHaveBeenCalledWith( + expect.objectContaining({ + props: expect.objectContaining({ initialPlanMode: 'team' }) + }) + ) + const props = mockShowLayoutDialog.mock.calls[0][0].props + expect(props.initialCheckout).toBeUndefined() }) }) }) diff --git a/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts b/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts index ffc40d20cdd..92e1ec7bf3b 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionDialog.ts @@ -3,12 +3,24 @@ import { useDialogService } from '@/services/dialogService' import { useDialogStore } from '@/stores/dialogStore' import { useBillingContext } from '@/composables/billing/useBillingContext' import { useBillingRouting } from '@/composables/billing/useBillingRouting' +import { useFeatureFlags } from '@/composables/useFeatureFlags' +import { + getStopDiscountedMonthlyUsd, + mapApiTeamCreditStops +} from '@/platform/cloud/subscription/constants/teamPlanCreditStops' import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { PaymentIntentSource } from '@/platform/telemetry/types' import type { SubscriptionCheckoutSelection } from '@/platform/workspace/composables/useSubscriptionCheckout' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' +import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useAuthStore } from '@/stores/authStore' +import { + clearPendingSubscriptionCheckout, + getPendingSubscriptionCheckout +} from '@/platform/workspace/utils/pendingSubscriptionCheckout' +import type { PendingSubscriptionCheckout } from '@/platform/workspace/utils/pendingSubscriptionCheckout' const DIALOG_KEY = 'subscription-required' const RESUME_PRICING_KEY = 'comfy:resume-team-pricing' @@ -43,6 +55,7 @@ export const useSubscriptionDialog = () => { const dialogService = useDialogService() const dialogStore = useDialogStore() const workspaceStore = useTeamWorkspaceStore() + const { flags } = useFeatureFlags() function hide() { dialogStore.closeDialog({ key: DIALOG_KEY }) @@ -148,6 +161,7 @@ export const useSubscriptionDialog = () => { props: { onClose: hide, reason: options?.reason, + embeddedCheckoutEnabled: flags.embeddedCheckoutEnabled, initialCheckout: options?.initialCheckout, initialPlanMode: getInitialPlanMode( options?.planMode, @@ -164,6 +178,8 @@ export const useSubscriptionDialog = () => { // steps shrink (the content root sets its own width per checkoutStep). renderer: 'reka', size: 'full', + // A scrim click mid-checkout would silently discard typed card + // details and any pending 3DS state; the X is the only close. dismissableMask: false, contentClass: 'w-fit max-w-[min(1280px,95vw)] sm:max-w-[min(1280px,95vw)] max-h-[90vh] rounded-2xl border border-border-default bg-secondary-background shadow-[0_25px_80px_rgba(5,6,12,0.45)]' @@ -222,11 +238,86 @@ export const useSubscriptionDialog = () => { }) } - /** - * Check for and consume a pending team pricing resume intent. - * Call once after workspace initialization on app boot. - */ - function resumePendingPricingFlow() { + async function restoreCheckoutSelection( + pending: PendingSubscriptionCheckout + ): Promise { + const selection = pending.selection + if (selection.planMode === 'personal') return selection + + const { + fetchPlans, + fetchStatus, + teamCreditStops, + currentTeamCreditStop, + subscription, + subscriptionStatus + } = useBillingContext() + await Promise.all([fetchPlans(), fetchStatus()]) + const stop = mapApiTeamCreditStops(teamCreditStops.value?.stops ?? []).find( + ({ id }) => id === selection.teamCreditStopId + ) + if (!stop?.id) return null + + return { + planMode: 'team', + stop: { + id: stop.id, + usd: stop.usd, + credits: stop.credits, + discountedUsd: getStopDiscountedMonthlyUsd(stop, selection.billingCycle) + }, + billingCycle: selection.billingCycle, + isChange: + currentTeamCreditStop.value !== null && + subscriptionStatus.value !== 'ended' && + (currentTeamCreditStop.value.id !== stop.id || + (subscription.value?.duration === 'MONTHLY' + ? 'monthly' + : 'yearly') !== selection.billingCycle) + } + } + + async function resumePendingCheckout( + pending: PendingSubscriptionCheckout + ): Promise { + if ( + pending.workspaceId !== workspaceStore.activeWorkspaceId || + pending.ownerUid !== useAuthStore().userId + ) { + clearPendingSubscriptionCheckout(pending.operationId) + return + } + + const billingOperationStore = useBillingOperationStore() + try { + const operation = await billingOperationStore.startOperation( + pending.operationId, + 'subscription', + { + tier: + pending.selection.planMode === 'personal' + ? pending.selection.tierKey + : 'team', + cycle: pending.selection.billingCycle, + attemptStartedAt: pending.attemptedAt + } + ) + if (operation.status !== 'failed') return + + const initialCheckout = await restoreCheckoutSelection(pending) + showPricingTable({ + planMode: pending.selection.planMode, + ...(initialCheckout && { initialCheckout }) + }) + } finally { + clearPendingSubscriptionCheckout(pending.operationId) + } + } + + function resumePendingPricingFlow(): Promise | void { + const pendingCheckout = getPendingSubscriptionCheckout() + if (pendingCheckout) return resumePendingCheckout(pendingCheckout) + try { const pending = sessionStorage.getItem(RESUME_PRICING_KEY) if (!pending) return diff --git a/src/platform/cloud/subscription/constants/tierPricing.test.ts b/src/platform/cloud/subscription/constants/tierPricing.test.ts new file mode 100644 index 00000000000..4b54a1e63b7 --- /dev/null +++ b/src/platform/cloud/subscription/constants/tierPricing.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' + +import type { IngestSubscriptionTier } from './tierPricing' +import { hasActivePaidPlan, toTierKey } from './tierPricing' + +describe('toTierKey', () => { + it('maps every personal-catalog tier to its key', () => { + expect(toTierKey('FREE')).toBe('free') + expect(toTierKey('STANDARD')).toBe('standard') + expect(toTierKey('CREATOR')).toBe('creator') + expect(toTierKey('PRO')).toBe('pro') + expect(toTierKey('FOUNDERS_EDITION')).toBe('founder') + }) + + it('returns null for workspace-level tiers', () => { + expect(toTierKey('TEAM')).toBeNull() + expect(toTierKey('ENTERPRISE')).toBeNull() + }) + + // The tier arrives as unvalidated JSON from the backend, so a value outside + // the union is reachable at runtime even though the type forbids it. It must + // return null rather than failing, which is what keeps a backend-side tier + // addition from breaking the frontend. + it('returns null for a tier the frontend does not know', () => { + expect(toTierKey('SOME_FUTURE_TIER' as IngestSubscriptionTier)).toBeNull() + }) + + // hasOwnProperty rather than `in`: these are inherited from Object.prototype, + // so `in` would return a function or object where a TierKey is expected. + it.for(['constructor', 'toString', '__proto__', 'valueOf'])( + 'returns null for the inherited property %s', + (key) => { + expect(toTierKey(key as IngestSubscriptionTier)).toBeNull() + } + ) + + // tier is unvalidated backend JSON, so a non-string is reachable. These must + // return null rather than coercing to a property key or throwing. + it.for([[['FREE']], [{}], [null], [undefined], [42]])( + 'returns null for the non-string value %s', + ([value]) => { + expect(toTierKey(value as unknown as IngestSubscriptionTier)).toBeNull() + } + ) +}) + +describe('hasActivePaidPlan', () => { + // Deliberately not keyed off toTierKey: workspace-level tiers map to no + // catalog key yet are paid plans, so a null key must not read as unpaid. + it('treats catalog, workspace-level, and unrecognised tiers as paid', () => { + expect(hasActivePaidPlan('PRO')).toBe(true) + expect(hasActivePaidPlan('TEAM')).toBe(true) + expect(hasActivePaidPlan('ENTERPRISE')).toBe(true) + }) + + it('treats FREE and an absent tier as unpaid', () => { + expect(hasActivePaidPlan('FREE')).toBe(false) + expect(hasActivePaidPlan(null)).toBe(false) + expect(hasActivePaidPlan(undefined)).toBe(false) + }) +}) diff --git a/src/platform/cloud/subscription/constants/tierPricing.ts b/src/platform/cloud/subscription/constants/tierPricing.ts index 84c3aa088b0..dd9fbcf3221 100644 --- a/src/platform/cloud/subscription/constants/tierPricing.ts +++ b/src/platform/cloud/subscription/constants/tierPricing.ts @@ -56,9 +56,27 @@ const TIER_FEATURES: Record = { export const DEFAULT_TIER_KEY: TierKey = 'standard' -// TEAM is workspace-level, so it maps to no key in this personal plan catalog. +// Membership is tested rather than listing the exclusions, so a tier added to +// the ingest enum narrows to false and returns null instead of failing the +// build. Two details are load-bearing: +// - `typeof`, because tier is unvalidated backend JSON and need not be a +// string; hasOwnProperty coerces its argument to a property key, so +// ['FREE'] would be accepted as FREE and a null toString would throw. +// - own-property rather than `in`, which walks the prototype chain and would +// return an inherited function for 'constructor' or 'toString'. +function isRegistrySubscriptionTier( + tier: unknown +): tier is RegistrySubscriptionTier { + return ( + typeof tier === 'string' && + Object.prototype.hasOwnProperty.call(TIER_TO_KEY, tier) + ) +} + +// Workspace-level tiers (TEAM, and any added later) map to no key in this +// personal plan catalog. export function toTierKey(tier: IngestSubscriptionTier): TierKey | null { - return tier === 'TEAM' ? null : TIER_TO_KEY[tier] + return isRegistrySubscriptionTier(tier) ? TIER_TO_KEY[tier] : null } // Includes the workspace-level TEAM, which toTierKey maps to null: a catalog diff --git a/src/platform/cloud/subscription/utils/paymentReturnUrl.test.ts b/src/platform/cloud/subscription/utils/paymentReturnUrl.test.ts new file mode 100644 index 00000000000..faf1c1176ed --- /dev/null +++ b/src/platform/cloud/subscription/utils/paymentReturnUrl.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it, vi } from 'vitest' + +import { paymentReturnUrl } from './paymentReturnUrl' + +vi.mock('@/config/comfyApi', () => ({ + getComfyPlatformBaseUrl: () => 'https://platform.comfy.org' +})) + +describe('paymentReturnUrl', () => { + it('returns to the page the checkout started on, without query or hash', () => { + vi.stubGlobal('location', { + origin: 'https://cloud.comfy.org', + pathname: '/workspace/abc', + search: '?pricing=team', + hash: '#section' + }) + expect(paymentReturnUrl()).toBe('https://cloud.comfy.org/workspace/abc') + }) + + it('accepts an HTTP origin', () => { + vi.stubGlobal('location', { + origin: 'http://localhost:5173', + pathname: '/workspace/abc' + }) + + expect(paymentReturnUrl()).toBe('http://localhost:5173/workspace/abc') + }) + + it('falls back to the platform success page on a non-HTTP origin, which the backend would reject', () => { + vi.stubGlobal('location', { + origin: 'file://', + pathname: '/index.html' + }) + expect(paymentReturnUrl()).toBe( + 'https://platform.comfy.org/payment/success' + ) + }) +}) diff --git a/src/platform/cloud/subscription/utils/paymentReturnUrl.ts b/src/platform/cloud/subscription/utils/paymentReturnUrl.ts new file mode 100644 index 00000000000..bb79fd6e06d --- /dev/null +++ b/src/platform/cloud/subscription/utils/paymentReturnUrl.ts @@ -0,0 +1,44 @@ +import { getComfyPlatformBaseUrl } from '@/config/comfyApi' + +const STRIPE_RETURN_PARAMS = [ + 'payment_intent', + 'payment_intent_client_secret', + 'redirect_status' +] as const + +let paymentReturnPending = false + +export function stripPaymentReturnParams(): void { + const url = new URL(globalThis.location.href) + const returnParams = STRIPE_RETURN_PARAMS.filter((param) => + url.searchParams.has(param) + ) + if (returnParams.length === 0) return + + paymentReturnPending = true + for (const param of returnParams) url.searchParams.delete(param) + globalThis.history.replaceState(globalThis.history.state, '', url) +} + +export function consumePaymentReturn(): boolean { + stripPaymentReturnParams() + const pending = paymentReturnPending + paymentReturnPending = false + return pending +} + +/** + * Where a redirect payment method (Alipay) or a hosted checkout sends the + * customer afterwards. Returning to the page the checkout started on keeps + * them in the app, where the pending-operation recovery on the next billing + * status read resumes polling and completes the flow. Non-HTTP origins + * (Electron) fall back to the platform success page: the backend requires an + * absolute HTTP(S) return URL. + */ +export function paymentReturnUrl(): string { + const { origin, pathname } = globalThis.location + if (origin?.startsWith('https://') || origin?.startsWith('http://')) { + return `${origin}${pathname}` + } + return `${getComfyPlatformBaseUrl()}/payment/success` +} diff --git a/src/platform/cloud/subscription/utils/subscriptionQuoteFormatting.ts b/src/platform/cloud/subscription/utils/subscriptionQuoteFormatting.ts new file mode 100644 index 00000000000..67e9fb9055c --- /dev/null +++ b/src/platform/cloud/subscription/utils/subscriptionQuoteFormatting.ts @@ -0,0 +1,11 @@ +export function formatQuoteMoney( + cents: number, + currency: string | undefined, + locale: string +): string { + if (!currency) return '' + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: currency.toUpperCase() + }).format(cents / 100) +} diff --git a/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts b/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts index 4991f0c3b1b..811aa4b1176 100644 --- a/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts +++ b/src/platform/cloud/subscription/utils/teamSubscriptionCheckoutUtil.ts @@ -7,6 +7,7 @@ import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFai import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { trackWorkspaceCheckoutStarted } from '@/platform/workspace/utils/workspaceCheckoutTelemetry' +import { paymentReturnUrl } from './paymentReturnUrl' import type { BillingCycle } from './subscriptionTierRank' interface PerformTeamSubscriptionCheckoutOptions { @@ -63,7 +64,7 @@ async function initiateTeamSubscriptionCheckout( ): Promise { const planSlug = getTeamPlanSlug(billingCycle) const response = await workspaceApi.subscribe(planSlug, { - returnUrl: `${getComfyPlatformBaseUrl()}/payment/success`, + returnUrl: paymentReturnUrl(), cancelUrl: `${getComfyPlatformBaseUrl()}/payment/failed`, teamCreditStopId }) diff --git a/src/platform/telemetry/types.ts b/src/platform/telemetry/types.ts index f565e342377..d9bf95b1cd6 100644 --- a/src/platform/telemetry/types.ts +++ b/src/platform/telemetry/types.ts @@ -734,6 +734,7 @@ type BillingFailureCategory = | 'provider_decline' | 'redirect' | 'poll_timeout' + | 'reconciliation_needed' | 'stale_operation' | 'rendering' | 'unknown' diff --git a/src/platform/workspace/api/workspaceApi.test.ts b/src/platform/workspace/api/workspaceApi.test.ts index c010afcaf61..14f18159955 100644 --- a/src/platform/workspace/api/workspaceApi.test.ts +++ b/src/platform/workspace/api/workspaceApi.test.ts @@ -1,5 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { + BillingOpStatusResponse, + SavedPaymentMethod +} from './workspaceApi' + const { mockAxiosInstance, mockGetWorkspaceAuthHeaderOrThrow, @@ -439,7 +444,93 @@ describe('workspaceApi', () => { }) describe('subscription', () => { - it('previewSubscribe() sends only fields defined by the ingest contract', async () => { + it('listSavedPaymentMethods() returns masked methods from GET', async () => { + const data: SavedPaymentMethod[] = [ + { + type: 'card', + id: 'pm_saved', + brand: 'visa', + last4: '4242', + is_default: true + } + ] + mockAxiosInstance.get.mockResolvedValue({ data }) + + const result = await workspaceApi.listSavedPaymentMethods() + + expect(mockAxiosInstance.get).toHaveBeenCalledWith( + '/api/billing/payment-methods', + { headers: AUTH_HEADER } + ) + expect(result).toEqual(data) + }) + + it('previewSubscribe() sends the promotion code only when applied', async () => { + mockAxiosInstance.post.mockResolvedValue({ data: { allowed: true } }) + + await workspaceApi.previewSubscribe('pro-monthly', { + promotionCode: 'SAVE20' + }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/api/billing/preview-subscribe', + expect.objectContaining({ promotion_code: 'SAVE20' }), + { headers: AUTH_HEADER } + ) + }) + + it('subscribe() echoes the quote and selected saved method', async () => { + mockAxiosInstance.post.mockResolvedValue({ + data: { billing_op_id: 'op-quote', status: 'subscribed' } + }) + + await workspaceApi.subscribe('pro-monthly', { + promotionCode: 'SAVE20', + quoteId: 'quote_123', + quoteVersion: 2, + savedPaymentMethodId: 'pm_saved' + }) + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/api/billing/subscribe', + expect.objectContaining({ + promotion_code: 'SAVE20', + quote_id: 'quote_123', + quote_version: 2, + saved_payment_method_id: 'pm_saved' + }), + { headers: AUTH_HEADER } + ) + }) + + it('subscribe() omits a promotion code when none is applied', async () => { + mockAxiosInstance.post.mockResolvedValue({ + data: { billing_op_id: 'op-no-promo', status: 'subscribed' } + }) + + await workspaceApi.subscribe('pro-monthly') + + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + '/api/billing/subscribe', + expect.objectContaining({ promotion_code: undefined }), + { headers: AUTH_HEADER } + ) + }) + + it('subscribe() rejects mutually exclusive payment credentials', async () => { + await expect( + workspaceApi.subscribe('pro-monthly', { + confirmationToken: 'ctoken_1', + savedPaymentMethodId: 'pm_saved' + }) + ).rejects.toThrow( + 'confirmationToken and savedPaymentMethodId are mutually exclusive' + ) + + expect(mockAxiosInstance.post).not.toHaveBeenCalled() + }) + + it('previewSubscribe() sends fields defined by the ingest contract', async () => { const data = { allowed: true, transition_type: 'new_subscription' } mockAxiosInstance.post.mockResolvedValue({ data }) @@ -466,6 +557,7 @@ describe('workspaceApi', () => { mockAxiosInstance.post.mockResolvedValue({ data }) const result = await workspaceApi.subscribe('pro-monthly', { + confirmationToken: 'ctoken_1', returnUrl: 'https://return.url', cancelUrl: 'https://cancel.url' }) @@ -474,6 +566,7 @@ describe('workspaceApi', () => { '/api/billing/subscribe', { plan_slug: 'pro-monthly', + confirmation_token: 'ctoken_1', return_url: 'https://return.url', cancel_url: 'https://cancel.url', team_credit_stop_id: undefined, @@ -497,6 +590,7 @@ describe('workspaceApi', () => { '/api/billing/subscribe', { plan_slug: 'team_per_credit_annual', + confirmation_token: undefined, return_url: undefined, cancel_url: undefined, team_credit_stop_id: 'team_700', @@ -617,9 +711,12 @@ describe('workspaceApi', () => { it('getBillingOpStatus() sends GET /billing/ops/:id', async () => { const data = { id: 'op-1', - status: 'succeeded', - started_at: '2026-01-01' - } + status: 'pending', + authentication_state: 'failed_retryable', + decline_reason: 'card_declined', + payment_intent_client_secret: 'pi_secret_current', + started_at: '2026-01-01T00:00:00Z' + } satisfies BillingOpStatusResponse mockAxiosInstance.get.mockResolvedValue({ data }) const result = await workspaceApi.getBillingOpStatus('op-1') diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index 5c2c4d575be..79b7227495f 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -25,6 +25,7 @@ import type { PreviewSubscribeResponse, ResubscribeRequest, ResubscribeResponse, + SavedPaymentMethod, SubscribeRequest, SubscribeResponse, SubscriptionDuration, @@ -81,6 +82,11 @@ export type { TeamCreditStopSummary } type SubscribeBillingCycle = 'monthly' | 'yearly' export interface SubscribeOptions { + confirmationToken?: string + promotionCode?: string + quoteId?: string + quoteVersion?: number + savedPaymentMethodId?: string returnUrl?: string cancelUrl?: string teamCreditStopId?: string @@ -91,6 +97,7 @@ export interface SubscribeOptions { export interface PreviewSubscribeOptions { teamCreditStopId?: string + promotionCode?: string } export type { SubscribeResponse } @@ -107,6 +114,13 @@ export type { BillingStatusResponse } export type { BillingBalanceResponse } export type { CreateTopupResponse } export type { BillingOpStatusResponse } +export type { SavedPaymentMethod } +export type BillingAuthenticationState = NonNullable< + BillingOpStatusResponse['authentication_state'] +> +export type BillingDeclineReason = NonNullable< + BillingOpStatusResponse['decline_reason'] +> interface GetBillingEventsParams { page?: number @@ -433,6 +447,19 @@ export const workspaceApi = { } }, + async listSavedPaymentMethods(): Promise { + const headers = await getAuthHeaderOrThrow() + try { + const response = await workspaceApiClient.get( + workspaceApiUrl('/billing/payment-methods'), + { headers } + ) + return response.data + } catch (err) { + handleAxiosError(err) + } + }, + /** * Preview subscription change * POST /api/billing/preview-subscribe @@ -447,7 +474,8 @@ export const workspaceApi = { workspaceApiUrl('/billing/preview-subscribe'), { plan_slug: planSlug, - team_credit_stop_id: options.teamCreditStopId + team_credit_stop_id: options.teamCreditStopId, + promotion_code: options.promotionCode } satisfies PreviewSubscribeRequest, { headers } ) @@ -465,12 +493,22 @@ export const workspaceApi = { planSlug: string, options: SubscribeOptions = {} ): Promise { + if (options.confirmationToken && options.savedPaymentMethodId) { + throw new TypeError( + 'confirmationToken and savedPaymentMethodId are mutually exclusive' + ) + } const headers = await getAuthHeaderOrThrow() try { const response = await workspaceApiClient.post( workspaceApiUrl('/billing/subscribe'), { plan_slug: planSlug, + confirmation_token: options.confirmationToken, + promotion_code: options.promotionCode, + quote_id: options.quoteId, + quote_version: options.quoteVersion, + saved_payment_method_id: options.savedPaymentMethodId, return_url: options.returnUrl, cancel_url: options.cancelUrl, team_credit_stop_id: options.teamCreditStopId, @@ -611,7 +649,7 @@ export const workspaceApi = { const headers = await getAuthHeaderOrThrow() try { const response = await workspaceApiClient.get( - workspaceApiUrl(`/billing/ops/${opId}`), + workspaceApiUrl(`/billing/ops/${encodeURIComponent(opId)}`), { headers, timeout: 30_000 } ) return response.data diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 23a6323b7a1..df7c37044c8 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -98,20 +98,6 @@ vi.mock('@/platform/distribution/types', () => ({ } })) -const mockResumePendingPricingFlow = vi.fn() -vi.mock( - '@/platform/cloud/subscription/composables/useSubscriptionDialog', - () => ({ - useSubscriptionDialog: () => ({ - show: vi.fn(), - showPricingTable: vi.fn(), - hide: vi.fn(), - startTeamWorkspaceUpgradeFlow: vi.fn(), - resumePendingPricingFlow: mockResumePendingPricingFlow - }) - }) -) - describe('WorkspaceAuthGate', () => { beforeEach(() => { mockIsCloud.value = true @@ -309,19 +295,9 @@ describe('WorkspaceAuthGate', () => { expect(signal.aborted).toBe(true) expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() - expect(mockResumePendingPricingFlow).not.toHaveBeenCalled() expect(mockReportError).not.toHaveBeenCalled() }) - it('calls resumePendingPricingFlow after successful workspace init', async () => { - mockWorkspaceStoreInitState.value = 'ready' - - mountComponent() - await flushPromises() - - expect(mockResumePendingPricingFlow).toHaveBeenCalled() - }) - it('skips workspace init when store is already initialized', async () => { mockWorkspaceStoreInitState.value = 'ready' @@ -546,7 +522,6 @@ describe('WorkspaceAuthGate', () => { expect(retrySignal.aborted).toBe(true) expect(mockLogout).toHaveBeenCalledOnce() expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() - expect(mockResumePendingPricingFlow).not.toHaveBeenCalled() }) }) }) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index 21f14d8af48..1d8fdca44a9 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -71,7 +71,6 @@ import Button from '@/components/ui/button/Button.vue' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { isCloud } from '@/platform/distribution/types' -import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { remoteConfigErrorStatus, remoteConfigState @@ -90,7 +89,6 @@ const initializationState = ref< >(isCloud ? 'initializing' : 'ready') const initializationRetryable = ref(true) const errorPanel = useTemplateRef('errorPanel') -const subscriptionDialog = useSubscriptionDialog() let initializationGeneration = 0 let initializationController: AbortController | null = null let backgroundInitialization: Promise | null = null @@ -173,14 +171,6 @@ async function initialize(): Promise { throw new Error('Unified cloud auth was cleared during workspace setup') } - // Resume any pending pricing flow from team workspace creation - // Only safe after workspace store initialized successfully — the pricing - // dialog reads workspace state to decide which variant to show. - const workspaceStore = useTeamWorkspaceStore() - if (workspaceStore.initState === 'ready') { - subscriptionDialog.resumePendingPricingFlow() - } - if (generation === initializationGeneration) { initializationState.value = 'ready' } diff --git a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts index ac88a3e8222..80f9c23a1d6 100644 --- a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts +++ b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.test.ts @@ -22,6 +22,12 @@ function previewFixture( cost_next_period_cents: priceCents, credits_today_cents: 0, credits_next_period_cents: 0, + quote_id: 'quote_123', + quote_version: 1, + amount_due_cents: priceCents, + currency: 'usd', + renewal_amount_cents: priceCents, + renewal_at: '2027-06-19T00:00:00Z', new_plan: { slug: 'creator', tier: 'CREATOR', @@ -41,7 +47,8 @@ function previewFixture( vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key, - n: (value: number) => value.toLocaleString('en-US') + n: (value: number) => value.toLocaleString('en-US'), + locale: { value: 'en' } }) })) @@ -56,6 +63,114 @@ const globalOptions = { } describe('SubscriptionAddPaymentPreviewWorkspace', () => { + // Stripe Elements configure themselves once from the amount and currency, so + // mounting the selector before the quote lands leaves it permanently + // unusable. The team checkout renders its preview step while the quote is + // still in flight, which is how "payment options are unavailable" reached + // customers holding a perfectly good quote. + it('withholds the payment element until the quote is usable, then renders it', async () => { + let selectorInstances = 0 + const { rerender } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + teamPlan: { usd: 700, credits: 147_700, discountedUsd: 665 }, + usePaymentElement: true + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + UnifiedStripePaymentSelector: { + name: 'UnifiedStripePaymentSelector', + props: ['amountCents', 'currency'], + template: + '
{{ amountCents }}/{{ currency }}
', + setup() { + selectorInstances += 1 + } + } + } + } + }) + + expect(screen.queryByTestId('payment-selector')).toBeNull() + + await rerender({ previewData: previewFixture('MONTHLY', 66_500) }) + + expect(screen.getByTestId('payment-selector')).toHaveTextContent( + '66500/usd' + ) + expect(selectorInstances).toBe(1) + + await rerender({ + previewData: { + ...previewFixture('MONTHLY', 50_000), + quote_id: 'quote_456', + quote_version: 2 + } + }) + + expect(screen.getByTestId('payment-selector')).toHaveTextContent( + '50000/usd' + ) + expect(selectorInstances).toBe(2) + }) + + it('submits a zero-dollar quote without mounting Stripe Elements', async () => { + const quote = previewFixture('MONTHLY', 0) + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: quote, + usePaymentElement: true, + quoteIsCurrent: true + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + UnifiedStripePaymentSelector: { + template: '
' + } + } + } + }) + + expect(screen.queryByTestId('payment-selector')).toBeNull() + await userEvent.click( + screen.getByText('subscription.preview.payAndSubscribe') + ) + expect(emitted().addCreditCard).toBeTruthy() + }) + + it('falls back to subscription confirmation when quote identity is missing', async () => { + const quote = previewFixture('MONTHLY', 3500) + delete quote.quote_id + delete quote.quote_version + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: quote, + usePaymentElement: true, + quoteIsCurrent: true + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + UnifiedStripePaymentSelector: { + template: '
' + } + } + } + }) + + expect(screen.queryByTestId('payment-selector')).toBeNull() + await userEvent.click( + screen.getByText('subscription.preview.payAndSubscribe') + ) + expect(emitted().addCreditCard).toBeTruthy() + }) + it('renders personal tier price and credits from tierKey', () => { render(SubscriptionAddPaymentPreviewWorkspace, { props: { tierKey: 'creator' }, @@ -73,7 +188,7 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { expect(screen.getByText('subscription.teamPlan.name')).toBeTruthy() expect(screen.getByText('$380')).toBeTruthy() expect(screen.getAllByText('84,400').length).toBeGreaterThan(0) - expect(screen.getByText('$380.00')).toBeTruthy() + expect(screen.queryByText('$380.00')).toBeNull() }) it('shows the monthly-equivalent price and annual total for a yearly preview', () => { @@ -102,7 +217,7 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { }) expect(screen.getByText('$28')).toBeTruthy() expect(screen.getByText('subscription.billedYearly')).toBeTruthy() - expect(screen.getByText('$336.00')).toBeTruthy() + expect(screen.queryByText('$336.00')).toBeNull() }) it('omits the billed-yearly note for a monthly subscription', () => { @@ -135,12 +250,16 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { }) expect(screen.getByText('$380')).toBeTruthy() expect(screen.getByText('subscription.billedYearly')).toBeTruthy() - expect(screen.getByText('$4560.00')).toBeTruthy() + expect(screen.queryByText('$4,560.00')).toBeNull() }) it('emits addCreditCard from the team confirm CTA', async () => { const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { - props: { teamPlan: { usd: 400, credits: 84_400, discountedUsd: 380 } }, + props: { + teamPlan: { usd: 400, credits: 84_400, discountedUsd: 380 }, + previewData: previewFixture('MONTHLY', 38_000), + quoteIsCurrent: true + }, global: globalOptions }) await userEvent.click( @@ -149,6 +268,70 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { expect(emitted().addCreditCard).toBeTruthy() }) + it('invalidates while editing a promo and applies only on button click', async () => { + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: previewFixture('MONTHLY', 3500), + quoteIsCurrent: true, + embeddedCheckoutEnabled: true + }, + global: globalOptions + }) + const input = screen.getByPlaceholderText( + 'subscription.preview.promoCodePlaceholder' + ) + + await userEvent.type(input, 'SAVE20') + expect(emitted().invalidateQuote).toBeTruthy() + expect(emitted().applyPromotionCode).toBeUndefined() + + await userEvent.click( + screen.getByText('subscription.preview.applyPromoCode') + ) + expect(emitted().applyPromotionCode?.at(-1)).toEqual(['SAVE20']) + }) + + it('offers Add new payment method from the saved-method picker', async () => { + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + previewData: previewFixture('MONTHLY', 3500), + quoteIsCurrent: true, + embeddedCheckoutEnabled: true, + selectedSavedMethodId: 'pm_default', + savedMethods: [ + { + type: 'card', + id: 'pm_default', + brand: 'visa', + last4: '4242', + is_default: true + }, + { type: 'alipay', id: 'pm_alipay', is_default: false } + ] + }, + global: { + ...globalOptions, + stubs: { + ...globalOptions.stubs, + SingleSelect: { + props: ['options'], + emits: ['update:modelValue'], + template: + '' + } + } + } + }) + + await userEvent.click( + screen.getByText('subscription.preview.addNewPaymentMethod') + ) + expect(emitted()['update:selectedSavedMethodId']).toEqual([[null]]) + expect(emitted().changePaymentMethod).toBeTruthy() + }) + it('opens verification only from its button without exposing the URL', async () => { const actionUrl = 'https://verify.example/sensitive-token' const open = vi.spyOn(window, 'open').mockReturnValue({} as Window) @@ -171,16 +354,53 @@ describe('SubscriptionAddPaymentPreviewWorkspace', () => { ) }) - it('prevents leaving the preview while payment is pending', () => { + it('renders an explicit retry action after failed verification', async () => { + const { emitted } = render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + embeddedCheckoutEnabled: true, + authenticationState: 'failed_retryable', + authenticationError: 'Challenge was closed', + canRetryAuthentication: true + }, + global: globalOptions + }) + + expect(screen.getByRole('alert')).toHaveTextContent('Challenge was closed') + await userEvent.click( + screen.getByRole('button', { + name: 'billingOperation.retryVerification' + }) + ) + expect(emitted().retryAuthentication).toBeTruthy() + }) + + it('shows reconciliation support guidance with the operation id', () => { + render(SubscriptionAddPaymentPreviewWorkspace, { + props: { + tierKey: 'creator', + embeddedCheckoutEnabled: true, + reconciliationOperationId: 'op-reconcile-123' + }, + global: globalOptions + }) + + expect( + screen.getByText('billingOperation.reconciliationTitle') + ).toBeTruthy() + expect(screen.getByText('op-reconcile-123')).toBeTruthy() + }) + + it('does not render a back action on the payment confirmation', () => { render(SubscriptionAddPaymentPreviewWorkspace, { props: { tierKey: 'creator', isLoading: true }, global: globalOptions }) expect( - screen.getByRole('button', { + screen.queryByRole('button', { name: 'subscription.preview.backToAllPlans' }) - ).toBeDisabled() + ).toBeNull() }) }) diff --git a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue index b673bda0534..d9faffa26a3 100644 --- a/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue +++ b/src/platform/workspace/components/SubscriptionAddPaymentPreviewWorkspace.vue @@ -1,21 +1,67 @@ diff --git a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts index 20384f42b54..b233b40d804 100644 --- a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts +++ b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.test.ts @@ -8,23 +8,38 @@ import SubscriptionRequiredDialogContentUnified from './SubscriptionRequiredDial const mockHandleSubscribeTeamClick = vi.fn() const mockHandleSubscribeClick = vi.fn() +const mockInvalidateQuote = vi.fn() const mockIsInPersonalWorkspace = ref(false) +const mockCheckoutStep = ref('pricing') +const mockPreviewVariant = ref(null) +const mockPreviewData = ref | null>(null) +const mockSelectedTeamStop = ref | null>(null) +const mockSelectedSavedPaymentMethodId = ref('pm_default') +const mockSavedPaymentMethods = ref[]>([]) vi.mock('@/platform/workspace/composables/useSubscriptionCheckout', () => ({ useSubscriptionCheckout: () => ({ - checkoutStep: ref('pricing'), + checkoutStep: mockCheckoutStep, isLoadingPreview: ref(false), loadingTier: ref(null), isSubscribing: ref(false), isResubscribing: ref(false), - previewData: ref(null), + previewData: mockPreviewData, + quoteIsCurrent: ref(false), + savedPaymentMethods: mockSavedPaymentMethods, + selectedSavedPaymentMethodId: mockSelectedSavedPaymentMethodId, selectedTierKey: ref(null), - selectedTeamStop: ref(null), + selectedTeamStop: mockSelectedTeamStop, selectedBillingCycle: ref('yearly'), activeCheckoutActionUrl: ref(null), + authenticationState: ref(null), + authenticationError: ref(null), + canRetryAuthentication: ref(false), + isAuthenticating: ref(false), + reconciliationOperationId: ref(null), isPolling: ref(false), isTeamCheckout: computed(() => false), - previewVariant: computed(() => null), + previewVariant: computed(() => mockPreviewVariant.value), handleSubscribeClick: mockHandleSubscribeClick, handleSubscribeTeamClick: mockHandleSubscribeTeamClick, handleBackToPricing: vi.fn(), @@ -32,6 +47,11 @@ vi.mock('@/platform/workspace/composables/useSubscriptionCheckout', () => ({ handleAddCreditCard: vi.fn(), handleConfirmTransition: vi.fn(), handleTeamSubscribe: vi.fn(), + handleSubscriptionPayment: vi.fn(), + handleTeamSubscriptionPayment: vi.fn(), + retryPaymentAuthentication: vi.fn(), + applyPromotionCode: vi.fn(), + invalidateQuote: mockInvalidateQuote, handleResubscribe: vi.fn() }) })) @@ -73,12 +93,27 @@ const UnifiedPricingTableStub = { function renderComponent(props: Record = {}) { return render(SubscriptionRequiredDialogContentUnified, { - props: { onClose: vi.fn(), ...props }, + props: { onClose: vi.fn(), embeddedCheckoutEnabled: true, ...props }, global: { plugins: [i18n], stubs: { UnifiedPricingTable: UnifiedPricingTableStub, - SubscriptionAddPaymentPreviewWorkspace: { template: '
' }, + SubscriptionAddPaymentPreviewWorkspace: { + name: 'SubscriptionAddPaymentPreviewWorkspace', + props: [ + 'previewData', + 'teamPlan', + 'savedMethods', + 'usePaymentElement' + ], + template: `
+ {{ previewData?.amount_due_cents ?? "no-quote" }} + {{ savedMethods.length }} + {{ usePaymentElement }} + + +
` + }, SubscriptionTransitionPreviewWorkspace: { template: '
' }, SubscriptionSuccessWorkspace: { template: '
' } } @@ -89,6 +124,68 @@ function renderComponent(props: Record = {}) { describe('SubscriptionRequiredDialogContentUnified team-plan subscribe', () => { beforeEach(() => { mockIsInPersonalWorkspace.value = false + mockCheckoutStep.value = 'pricing' + mockPreviewVariant.value = null + mockPreviewData.value = null + mockSelectedTeamStop.value = null + mockSelectedSavedPaymentMethodId.value = 'pm_default' + mockSavedPaymentMethods.value = [] + }) + + // The team checkout mounts the payment element against the quote's amount, so + // omitting preview-data left the element with nothing to charge and it + // refused to render — a served, correctly priced quote presented as + // "Payment options are unavailable". + it('hands the team checkout its quote so the payment element can mount', () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'team-new' + mockSelectedTeamStop.value = TEAM_PAYLOAD.stop + mockPreviewData.value = { amount_due_cents: 129_500, currency: 'usd' } + + renderComponent() + + expect(screen.getByTestId('add-payment-preview')).toHaveTextContent( + '129500' + ) + }) + + it('preserves the quote when the payment method changes', async () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'personal-new' + mockPreviewData.value = { amount_due_cents: 1600, currency: 'usd' } + renderComponent() + + await userEvent.click(screen.getByTestId('saved-method-btn')) + await userEvent.click(screen.getByTestId('new-method-btn')) + + expect(mockSelectedSavedPaymentMethodId.value).toBeNull() + expect(mockInvalidateQuote).not.toHaveBeenCalled() + }) + + it('collects a new method when none is selected', () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'personal-new' + mockPreviewData.value = { amount_due_cents: 1600, currency: 'usd' } + mockSavedPaymentMethods.value = [ + { id: 'pm_first', type: 'card', last4: '1111', is_default: false } + ] + mockSelectedSavedPaymentMethodId.value = null + + renderComponent() + + expect(screen.getByTestId('saved-method-count')).toHaveTextContent('0') + }) + + it('does not initialize the payment element while embedded checkout is off', () => { + mockCheckoutStep.value = 'preview' + mockPreviewVariant.value = 'personal-new' + mockPreviewData.value = { amount_due_cents: 1600, currency: 'usd' } + + renderComponent({ embeddedCheckoutEnabled: false }) + + expect(screen.getByTestId('payment-element-enabled')).toHaveTextContent( + 'false' + ) }) it('advances to team checkout from a team workspace', async () => { diff --git a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue index e3587740cf8..bb75978af34 100644 --- a/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue +++ b/src/platform/workspace/components/SubscriptionRequiredDialogContentUnified.vue @@ -1,15 +1,39 @@ @@ -110,6 +201,7 @@ :team-plan="selectedTeamStop" :preview-data="previewData" :billing-cycle="selectedBillingCycle" + :dark-surface="isEmbeddedSuccessStep" @close="handleSuccessClose" />
@@ -118,7 +210,7 @@ diff --git a/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts b/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts index 276489812d0..8ee3e1cd46e 100644 --- a/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts +++ b/src/platform/workspace/components/SubscriptionTransitionPreviewWorkspaceReactivation.test.ts @@ -87,7 +87,7 @@ const i18n = createI18n({ function makePreview( overrides: Partial ): PreviewSubscribeResponse { - return { + const result: PreviewSubscribeResponse = { allowed: true, transition_type: 'upgrade', effective_at: '2026-08-01T00:00:00Z', @@ -123,14 +123,25 @@ function makePreview( }, ...overrides } + return { + ...result, + quote_id: 'quote_123', + quote_version: 1, + amount_due_cents: result.cost_today_cents, + currency: 'usd', + renewal_amount_cents: result.new_plan.price_cents, + renewal_at: result.new_plan.period_end ?? '2026-09-01T00:00:00Z', + ...overrides + } } function renderComponent( previewData: PreviewSubscribeResponse, - forceReactivation = false + forceReactivation = false, + quoteIsCurrent = true ) { return render(SubscriptionTransitionPreviewWorkspace, { - props: { previewData, forceReactivation }, + props: { previewData, forceReactivation, quoteIsCurrent }, global: { plugins: [i18n] } }) } @@ -534,6 +545,45 @@ describe('SubscriptionTransitionPreviewWorkspace reactivation disclosure', () => }) describe('confirm gating on load state', () => { + it('shows unavailable exact quote fields', () => { + mockSubscription.value = { isCancelled: false, endDate: null } + renderComponent( + makePreview({ + quote_id: undefined, + quote_version: undefined, + amount_due_cents: undefined, + currency: undefined, + renewal_amount_cents: undefined, + renewal_at: undefined + }) + ) + + expect( + screen.getAllByText('subscription.preview.quoteUnavailable') + ).toHaveLength(2) + }) + + it('does not confirm without a current quote', async () => { + const user = userEvent.setup() + mockSubscription.value = { isCancelled: false, endDate: null } + const { emitted } = render(SubscriptionTransitionPreviewWorkspace, { + props: { + previewData: makePreview({}), + forceReactivation: false, + quoteIsCurrent: false, + embeddedCheckoutEnabled: true + }, + global: { plugins: [i18n] } + }) + const confirmButton = screen.getByRole('button', { + name: 'Confirm upgrade' + }) + + expect(confirmButton).toBeDisabled() + await user.click(confirmButton) + expect(emitted().confirm).toBeUndefined() + }) + it('disables confirm while subscription status has not loaded yet, even below the charge threshold', () => { mockSubscription.value = null renderComponent( diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index e507c0243c5..1fd55d4691c 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -14,6 +14,7 @@ const mockFetchStatus = vi.fn() const mockTopup = vi.fn<(amountCents: number) => Promise>() const mockStartOperation = vi.fn() +const mockRetryPaymentAuthentication = vi.fn() const mockShowSettings = vi.fn() const mockToastAdd = vi.fn() const mockCloseDialog = vi.fn() @@ -23,10 +24,21 @@ const mockPermissions = vi.hoisted(() => ({ ref: undefined as { value: { canTopUp: boolean } } | undefined })) const mockShouldUseWorkspaceBilling = vi.hoisted(() => ({ value: true })) + +interface MockTopupOperation { + opId: string + status: 'pending' | 'reconciliation_needed' + actionUrl: string | null + authenticationState?: string + errorMessage?: string | null + canRetryAuthentication?: boolean + isAuthenticating?: boolean +} + const mockBillingOperationState = vi.hoisted(() => ({ isAddingCredits: undefined as { value: boolean } | undefined, topupActionOperation: undefined as - | { value: { actionUrl: string } | undefined } + | { value: MockTopupOperation | undefined } | undefined })) @@ -51,7 +63,8 @@ vi.mock('@/platform/workspace/stores/billingOperationStore', async () => { get topupActionOperation() { return mockBillingOperationState.topupActionOperation?.value }, - startOperation: mockStartOperation + startOperation: mockStartOperation, + retryPaymentAuthentication: mockRetryPaymentAuthentication }) } }) @@ -149,6 +162,12 @@ const i18n = createI18n({ 'Your bank requires additional verification to complete this payment.', verifyTitle: 'Verify your payment' } + }, + billingOperation: { + authenticationFailedDetail: 'Verification failed.', + authenticationManagerRequired: 'Ask a workspace manager for help.', + retryVerification: 'Try verification again', + reconciliationDetail: 'Contact support with operation ID' } } } @@ -192,7 +211,7 @@ function setIsAddingCredits(isAddingCredits: boolean) { mockBillingOperationState.isAddingCredits.value = isAddingCredits } -function setTopupActionOperation(operation: { actionUrl: string } | undefined) { +function setTopupActionOperation(operation: MockTopupOperation | undefined) { if (!mockBillingOperationState.topupActionOperation) { throw new Error('Billing operation mock not initialized') } @@ -288,7 +307,11 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('reopens in verification without exposing the action URL', async () => { const actionUrl = 'https://verify.example/sensitive-token' const open = vi.spyOn(window, 'open').mockReturnValue({} as Window) - setTopupActionOperation({ actionUrl }) + setTopupActionOperation({ + opId: 'op-action', + status: 'pending', + actionUrl + }) const { container } = renderDialog() @@ -308,6 +331,11 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('reopens in verification while the action URL is loading', () => { setIsAddingCredits(true) + setTopupActionOperation({ + opId: 'op-loading', + status: 'pending', + actionUrl: null + }) renderDialog() @@ -320,11 +348,17 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('returns to amount selection when a reopened operation ends', async () => { setIsAddingCredits(true) + setTopupActionOperation({ + opId: 'op-loading', + status: 'pending', + actionUrl: null + }) renderDialog() expect(screen.getByText('Verify your payment')).toBeInTheDocument() setIsAddingCredits(false) + setTopupActionOperation(undefined) await nextTick() expect(screen.getByText('Select amount')).toBeInTheDocument() @@ -334,6 +368,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('hides topup verification after permission is revoked', () => { setCanTopUp(false) setTopupActionOperation({ + opId: 'op-action', + status: 'pending', actionUrl: 'https://verify.example/sensitive-token' }) @@ -344,6 +380,47 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ).not.toBeInTheDocument() }) + it('retries failed payment authentication', async () => { + renderDialog() + + setIsAddingCredits(true) + setTopupActionOperation({ + opId: 'op-retry', + status: 'pending', + actionUrl: null, + authenticationState: 'failed_retryable', + errorMessage: 'Your bank rejected the verification.', + canRetryAuthentication: true + }) + await nextTick() + + expect( + screen.getByText('Your bank rejected the verification.') + ).toBeInTheDocument() + await userEvent.click( + screen.getByRole('button', { name: 'Try verification again' }) + ) + expect(mockRetryPaymentAuthentication).toHaveBeenCalledWith('op-retry') + }) + + it('keeps a top-up locked when reconciliation needs support', () => { + setTopupActionOperation({ + opId: 'op-reconcile', + status: 'reconciliation_needed', + actionUrl: null + }) + + renderDialog() + + expect( + screen.getByText('Contact support with operation ID') + ).toBeInTheDocument() + expect(screen.getByText('op-reconcile')).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Add credits' }) + ).not.toBeInTheDocument() + }) + it('locks pending payment actions and prevents duplicate top-ups', async () => { mockTopup.mockResolvedValue(topupResponse('pending')) @@ -356,7 +433,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(screen.getByRole('button', { name: 'Back' })).toBeDisabled() expect(payButton).toBeDisabled() expect(mockStartOperation).toHaveBeenCalledWith('op-1', 'topup', { - attemptStartedAt: expect.any(Number) + attemptStartedAt: expect.any(Number), + autoHandleRequiresAction: true }) payButton.dispatchEvent(new MouseEvent('click', { bubbles: true })) @@ -448,7 +526,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) expect(mockStartOperation).toHaveBeenCalledWith('op-1', 'topup', { - attemptStartedAt: expect.any(Number) + attemptStartedAt: expect.any(Number), + autoHandleRequiresAction: true }) expect(mockFetchBalance).not.toHaveBeenCalled() expect(mockFetchStatus).not.toHaveBeenCalled() diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue index 9f358a79bf4..606a2612cb7 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue @@ -82,8 +82,18 @@ {{ $t('credits.topUp.verifyTitle') }}

- {{ $t('credits.topUp.verifyBody') }} + {{ + topupReconciliationOperationId + ? $t('billingOperation.reconciliationDetail') + : topupAuthenticationError || $t('credits.topUp.verifyBody') + }}

+ + {{ topupReconciliationOperationId }} +
@@ -188,6 +198,18 @@
+