AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(ai): users who cancel their sub can delete their AI BYOK keys, but not add or edit them (#15948)
Bartosz Majewskiee2ce4ecbead
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex f44241c9587..73f05175055 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.200.1",+ "version": "0.200.2","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/ee/billing/index.ts b/packages/core/shared/src/lib/ee/billing/index.tsindex 2871b183712..6d8c5e2c47f 100644--- a/packages/core/shared/src/lib/ee/billing/index.ts+++ b/packages/core/shared/src/lib/ee/billing/index.ts@@ -30,6 +30,10 @@ export const PurchasablePlan = z.object({includedSeats: Nullable(z.number()),includedCredits: Nullable(z.number()),creditsResetInterval: Nullable(z.string()),+ creditTopUp: Nullable(z.object({+ price: z.number(),+ credits: z.number(),+ })),})export type PurchasablePlan = z.infer<typeof PurchasablePlan>@@ -74,7 +78,7 @@ export const AUTUMN_FREE_PLAN: PlatformPlanWithOnlyLimits = {plan: 'free',tablesEnabled: true,eventStreamingEnabled: false,- includedCredits: 100,+ includedCredits: 1000,activeFlowsLimit: undefined,projectsLimit: 1,embeddingEnabled: false,diff --git a/packages/server/api/src/app/ai/ai-provider-controller.ts b/packages/server/api/src/app/ai/ai-provider-controller.tsindex f8dce07f219..6d57ba754fa 100644--- a/packages/server/api/src/app/ai/ai-provider-controller.ts+++ b/packages/server/api/src/app/ai/ai-provider-controller.ts@@ -1,6 +1,7 @@import { AiProviderKeyStatus, AIProviderName } from '@activepieces/core-utils'import { modelTierCatalog } from '@activepieces/server-utils'import { AIProviderModel, CreateAIProviderRequest, PrincipalType, spreadIfDefined, UpdateAIProviderRequest } from '@activepieces/shared'+import { FastifyRequest } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'import { z } from 'zod'@@ -134,6 +135,7 @@ const CreateAIProvider = {config: {security: securityAccess.platformAdminOnly([PrincipalType.USER]),},+ preHandler: (request: FastifyRequest): Promise<void> => aiProviderService(request.log).assertAiProvidersPlan(request.principal.platform.id),schema: {body: CreateAIProviderRequest,},diff --git a/packages/server/api/src/app/ai/ai-provider-service.ts b/packages/server/api/src/app/ai/ai-provider-service.tsindex e5728418acc..13319e23064 100644--- a/packages/server/api/src/app/ai/ai-provider-service.ts+++ b/packages/server/api/src/app/ai/ai-provider-service.ts@@ -124,6 +124,7 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({return}+ await this.assertAiProvidersPlan(platformId)await assertDisplayNameIsFree({ platformId, provider: aiProvider.provider, displayName: request.displayName, exceptId: providerId })const config = request.config ?? aiProvider.config@@ -198,7 +199,7 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({async delete(platformId: PlatformId, providerId: string): Promise<void> {const deleted = await transaction(async (manager) => {- await platformModelTierService.assertKeyCanBeDeleted({ manager, platformId, configId: providerId })+ await platformModelTierService.removeKeyFromTiers({ manager, platformId, configId: providerId })return deleteRowForUpdate({ manager, where: { platformId, id: providerId } })})await revokeKeyIfManaged({ row: deleted, log })@@ -293,6 +294,15 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({const aiProvider = await resolveRowForScope({ platformId, provider, scope, configId })this.assertKeyAllowsModel({ key: aiProvider, modelId })},+ async assertAiProvidersPlan(platformId: PlatformId): Promise<void> {+ const platform = await platformService(log).getOneWithPlanOrThrow(platformId)+ if (!platform.plan.aiProvidersEnabled) {+ throw new ActivepiecesError({+ code: ErrorCode.FEATURE_DISABLED,+ params: { message: 'AI providers are not included in your plan' },+ })+ }+ },assertKeyAllowsModel({ key, modelId }: { key: Pick<AIProviderSchema, 'modelScope' | 'modelIds'>, modelId: string }): void {if (!aiKeyScope.scopeAllows({ modelScope: key.modelScope, modelIds: key.modelIds, modelId })) {throw new ActivepiecesError({diff --git a/packages/server/api/src/app/ai/platform-model-tier-controller.ts b/packages/server/api/src/app/ai/platform-model-tier-controller.tsindex 47c16f67d63..102482fa779 100644--- a/packages/server/api/src/app/ai/platform-model-tier-controller.ts+++ b/packages/server/api/src/app/ai/platform-model-tier-controller.ts@@ -1,4 +1,4 @@-import { ActivepiecesError, ApId, ErrorCode } from '@activepieces/core-utils'+import { ApId } from '@activepieces/core-utils'import { CreatePlatformModelTierRequest, DeletePlatformModelTierRequest, PlatformModelTier, PlatformModelTierSummary, PrincipalType, ReorderPlatformModelTiersRequest, UpdatePlatformModelTierRequest } from '@activepieces/shared'import { FastifyRequest } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'@@ -6,7 +6,7 @@ import { StatusCodes } from 'http-status-codes'import { z } from 'zod'import { ProjectResourceType } from '../core/security/authorization/common'import { securityAccess } from '../core/security/authorization/fastify-security'-import { platformService } from '../platform/platform.service'+import { aiProviderService } from './ai-provider-service'import { platformModelTierService } from './platform-model-tier-service'export const platformModelTierController: FastifyPluginAsyncZod = async (app) => {@@ -31,16 +31,6 @@ export const platformModelTierController: FastifyPluginAsyncZod = async (app) =>})}-async function requireAiProvidersPlan(request: FastifyRequest): Promise<void> {- const platform = await platformService(request.log).getOneWithPlanOrThrow(request.principal.platform.id)- if (!platform.plan.aiProvidersEnabled) {- throw new ActivepiecesError({- code: ErrorCode.FEATURE_DISABLED,- params: { message: 'AI providers are not included in your plan' },- })- }-}-const TierIdParams = z.object({id: ApId,})@@ -74,7 +64,7 @@ const CreatePlatformModelTier = {config: {security: securityAccess.platformAdminOnly([PrincipalType.USER]),},- preHandler: requireAiProvidersPlan,+ preHandler: (request: FastifyRequest): Promise<void> => aiProviderService(request.log).assertAiProvidersPlan(request.principal.platform.id),schema: {body: CreatePlatformModelTierRequest,response: {@@ -87,7 +77,7 @@ const ReorderPlatformModelTiers = {config: {security: securityAccess.platformAdminOnly([PrincipalType.USER]),},- preHandler: requireAiProvidersPlan,+ preHandler: (request: FastifyRequest): Promise<void> => aiProviderService(request.log).assertAiProvidersPlan(request.principal.platform.id),schema: {body: ReorderPlatformModelTiersRequest,response: {@@ -100,7 +90,7 @@ const UpdatePlatformModelTier = {config: {security: securityAccess.platformAdminOnly([PrincipalType.USER]),},- preHandler: requireAiProvidersPlan,+ preHandler: (request: FastifyRequest): Promise<void> => aiProviderService(request.log).assertAiProvidersPlan(request.principal.platform.id),schema: {params: TierIdParams,body: UpdatePlatformModelTierRequest,diff --git a/packages/server/api/src/app/ai/platform-model-tier-service.ts b/packages/server/api/src/app/ai/platform-model-tier-service.tsindex a204bb9aeae..5258b958367 100644--- a/packages/server/api/src/app/ai/platform-model-tier-service.ts+++ b/packages/server/api/src/app/ai/platform-model-tier-service.ts@@ -1,4 +1,4 @@-import { ActivepiecesError, AIProviderName, apId, ErrorCode, isNil, PlatformId, spreadIfDefined, spreadIfNotUndefined, tryCatch, unique } from '@activepieces/core-utils'+import { ActivepiecesError, AIProviderName, apId, ErrorCode, isNil, partition, PlatformId, spreadIfDefined, spreadIfNotUndefined, tryCatch, unique } from '@activepieces/core-utils'import { AiProviderModelScope, CreatePlatformModelTierRequest, PlatformModelTier, PlatformModelTierEntry, PlatformModelTierSummary, UpdatePlatformModelTierRequest } from '@activepieces/shared'import { EntityManager, In } from 'typeorm'import { repoFactory } from '../core/db/repo-factory'@@ -154,12 +154,44 @@ export const platformModelTierService = {}},- async assertKeyCanBeDeleted({ manager, platformId, configId }: { manager: EntityManager, platformId: PlatformId, configId: string }): Promise<void> {+ async removeKeyFromTiers({ manager, platformId, configId }: { manager: EntityManager, platformId: PlatformId, configId: string }): Promise<void> {await lockPlatform({ manager, platformId })const tiers = await findLiveTiersUsingKey({ manager, platformId, configId })- if (tiers.length > 0) {- throw keyInUseError({ tierNames: tiers.map((tier) => tier.name) })+ const trimmed = tiers.map((tier) => ({ ...tier, entries: tier.entries.filter((entry) => entry.configId !== configId) }))+ const [emptied, kept] = partition(trimmed, (tier) => tier.entries.length === 0)+ if (kept.length > 0) {+ await manager.query(+ `+ UPDATE "platform_model_tier"+ SET "entries" = (+ SELECT jsonb_agg(entry ORDER BY position)+ FROM jsonb_array_elements("entries") WITH ORDINALITY AS kept_entries(entry, position)+ WHERE entry->>'configId' <> $3+ )+ WHERE "platformId" = $1 AND "id" = ANY($2)+ `,+ [platformId, kept.map((tier) => tier.id), configId],+ )}+ if (emptied.length === 0) {+ return+ }+ const emptiedIds = emptied.map((tier) => tier.id)+ await tierRepo(manager).update({ platformId, id: In(emptiedIds) }, { isDefault: false, isFast: false })+ await tierRepo(manager).softDelete({ platformId, id: In(emptiedIds) })+ const replacement = (await listLive({ platformId, manager }))[0]+ if (isNil(replacement)) {+ await platformConfigurationRepo(manager).update({ platformId }, { aiSpecificModelsVisible: true })+ return+ }+ await manager.query(+ 'UPDATE "platform_model_tier" SET "replacedBy" = $1 WHERE "platformId" = $2 AND ("id" = ANY($3) OR "replacedBy" = ANY($3))',+ [replacement.id, platformId, emptiedIds],+ )+ await tierRepo(manager).update({ platformId, id: replacement.id }, {+ ...(emptied.some((tier) => tier.isDefault) ? { isDefault: true } : {}),+ ...(emptied.some((tier) => tier.isFast) ? { isFast: true } : {}),+ })},async getFastForRun({ platformId, scope }: { platformId: PlatformId, scope: ProviderScope }): Promise<TierForRun | null> {diff --git a/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-utils.ts b/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-utils.tsindex 9e5005a7ff3..2a0086218e4 100644--- a/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-utils.ts+++ b/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-utils.ts@@ -393,6 +393,7 @@ function largestGrantResetAt(balance: Balance): number | null {function toPurchasablePlan(plan: ConsoleAutumnPlan): PurchasablePlan {const creditsItem = (plan.items ?? []).find((item) => item.featureId === ConsumableFeatureId.AP_CREDITS && isNil(item.price))+ const creditTopUpPrice = (plan.items ?? []).find((item) => item.featureId === ConsumableFeatureId.AP_CREDITS && !isNil(item.price))?.pricereturn {id: plan.id,name: plan.name,@@ -404,6 +405,7 @@ function toPurchasablePlan(plan: ConsoleAutumnPlan): PurchasablePlan {includedSeats: (plan.items ?? []).find((item) => item.featureId === UnconsumableFeatureId.USERS_LIMIT)?.included ?? null,includedCredits: creditsItem?.included ?? null,creditsResetInterval: creditsItem?.reset?.interval ?? null,+ creditTopUp: isNil(creditTopUpPrice?.amount) ? null : { price: creditTopUpPrice.amount, credits: creditTopUpPrice.billingUnits ?? 1 },}}diff --git a/packages/server/api/test/integration/ce/ai-provider/managed-provider-key-race.test.ts b/packages/server/api/test/integration/ce/ai-provider/managed-provider-key-race.test.tsindex 596ce92e7ce..4baef1ec005 100644--- a/packages/server/api/test/integration/ce/ai-provider/managed-provider-key-race.test.ts+++ b/packages/server/api/test/integration/ce/ai-provider/managed-provider-key-race.test.ts@@ -201,7 +201,6 @@ describe('managed AI provider deletion', () => {entries: [{ configId: managedId, modelId: 'openai/gpt-4o' }],isDefault: true,})- await expect(aiProviderService(app.log).delete(ctx.platform.id, managedId)).rejects.toThrow()await aiProviderService(app.log).deleteManagedProvider({ platformId: ctx.platform.id })diff --git a/packages/server/api/test/integration/ce/ai-provider/platform-model-tier.test.ts b/packages/server/api/test/integration/ce/ai-provider/platform-model-tier.test.tsindex 8e67efbd024..67067ea5826 100644--- a/packages/server/api/test/integration/ce/ai-provider/platform-model-tier.test.ts+++ b/packages/server/api/test/integration/ce/ai-provider/platform-model-tier.test.ts@@ -315,14 +315,45 @@ describe('Platform model tiers API', () => {})describe('key guard', () => {- it('refuses to delete a key a tier uses', async () => {+ it('removes a deleted key from a tier and keeps the tier when other models are left', async () => {const key = await seedKey({ testCtx: ctx })- await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Expert' }) })+ const otherKey = await seedKey({ testCtx: ctx })+ const tier = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, entries: [+ { configId: key.id, modelId: 'gpt-4o' },+ { configId: otherKey.id, modelId: 'gpt-4o-mini' },+ ] }) })const response = await ctx.delete(`/v1/ai-providers/${key.id}`)- expect(response.statusCode).toBe(StatusCodes.CONFLICT)- expect(response.body).toContain('Expert')+ expect(response.statusCode).toBe(StatusCodes.NO_CONTENT)+ expect(await listAdmin({ testCtx: ctx })).toMatchObject([+ { id: tier.id, isDefault: true, isFast: true, entries: [{ configId: otherKey.id, modelId: 'gpt-4o-mini' }] },+ ])+ })++ it('deletes a tier left with no models and moves its users and flags to the first tier left', async () => {+ const key = await seedKey({ testCtx: ctx })+ const otherKey = await seedKey({ testCtx: ctx })+ const expert = await createTier({ testCtx: ctx, body: tierBody({ configId: key.id, name: 'Expert' }) })+ const kept = await createTier({ testCtx: ctx, body: tierBody({ configId: otherKey.id, name: 'Kept' }) })++ const response = await ctx.delete(`/v1/ai-providers/${key.id}`)++ expect(response.statusCode).toBe(StatusCodes.NO_CONTENT)+ expect(await listAdmin({ testCtx: ctx })).toMatchObject([{ id: kept.id, isDefault: true, isFast: true }])+ expect(await findWithDeleted({ id: expert.id })).toMatchObject({ replacedBy: kept.id, isDefault: false, isFast: false })+ })++ it('shows specific models again when deleting a key removes the last tier', async () => {+ const key = await seedKey({ testCtx: ctx })+ await createTier({ testCtx: ctx, body: tierBody({ configId: key.id }) })+ await ctx.post(CONFIGURATIONS, { aiSpecificModelsVisible: false })++ const response = await ctx.delete(`/v1/ai-providers/${key.id}`)++ expect(response.statusCode).toBe(StatusCodes.NO_CONTENT)+ expect(await listAdmin({ testCtx: ctx })).toEqual([])+ expect((await ctx.get(CONFIGURATIONS)).json()).toMatchObject({ aiSpecificModelsVisible: true })})it('refuses a scope change that drops a tier model', async () => {diff --git a/packages/server/api/test/integration/ee/ai-provider/ai-provider-plan.test.ts b/packages/server/api/test/integration/ee/ai-provider/ai-provider-plan.test.tsnew file mode 100644index 00000000000..12de1e024c0--- /dev/null+++ b/packages/server/api/test/integration/ee/ai-provider/ai-provider-plan.test.ts@@ -0,0 +1,61 @@+import { AIProviderName } from '@activepieces/core-utils'+import { FastifyInstance } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { databaseConnection } from '../../../../src/app/database/database-connection'+import { mockAndSaveAIProvider } from '../../../helpers/mocks'+import { createTestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance | null = null++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('AI provider keys plan gate', () => {+ it('refuses creating and updating keys but still deletes them when the plan has no AI providers', async () => {+ const ctx = await createTestContext(app!, { plan: { aiProvidersEnabled: false } })+ const key = await mockAndSaveAIProvider({+ platformId: ctx.platform.id,+ provider: AIProviderName.CUSTOM,+ config: CUSTOM_CONFIG,+ })++ const create = await ctx.post(KEYS, { provider: AIProviderName.CUSTOM, displayName: 'New key', config: CUSTOM_CONFIG, auth: { apiKey: 'test-key' } })+ const update = await ctx.post(`${KEYS}/${key.id}`, { displayName: 'Renamed key', config: CUSTOM_CONFIG, auth: { apiKey: 'test-key' } })+ const remove = await ctx.delete(`${KEYS}/${key.id}`)++ expect(create.statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)+ expect(update.statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)+ expect(remove.statusCode).toBe(StatusCodes.NO_CONTENT)+ })++ it('moves chat back to the managed key when the plan has no AI providers', async () => {+ const ctx = await createTestContext(app!, { plan: { aiProvidersEnabled: false } })+ const managed = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.ACTIVEPIECES, enabledForChat: false })+ const key = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.CUSTOM, config: CUSTOM_CONFIG, enabledForChat: true })++ const update = await ctx.post(`${KEYS}/${managed.id}`, { displayName: 'Activepieces', enabledForChat: true })+ const managedAfter = await databaseConnection().getRepository('ai_provider').findOneByOrFail({ id: managed.id })+ const keyAfter = await databaseConnection().getRepository('ai_provider').findOneByOrFail({ id: key.id })++ expect(update.statusCode).toBe(StatusCodes.OK)+ expect(managedAfter.enabledForChat).toBe(true)+ expect(keyAfter.enabledForChat).toBe(false)+ })++ it('allows creating keys when the plan has AI providers', async () => {+ const ctx = await createTestContext(app!, { plan: { aiProvidersEnabled: true } })++ const create = await ctx.post(KEYS, { provider: AIProviderName.CUSTOM, displayName: 'New key', config: CUSTOM_CONFIG, auth: { apiKey: 'test-key' } })++ expect(create.statusCode).toBe(StatusCodes.OK)+ })+})++const KEYS = '/v1/ai-providers'+const CUSTOM_CONFIG = { baseUrl: 'https://api.example.com/v1', apiKeyHeader: 'Authorization', models: [] }diff --git a/packages/server/api/test/integration/ee/ai-provider/platform-model-tier-plan.test.ts b/packages/server/api/test/integration/ee/ai-provider/platform-model-tier-plan.test.tsindex afb582b248d..d056ee5cbea 100644--- a/packages/server/api/test/integration/ee/ai-provider/platform-model-tier-plan.test.ts+++ b/packages/server/api/test/integration/ee/ai-provider/platform-model-tier-plan.test.ts@@ -32,7 +32,7 @@ describe('Platform model tiers plan gate', () => {expect(list.statusCode).toBe(StatusCodes.OK)})- it('lets a downgraded platform delete its last tier and then its key', async () => {+ it('lets a downgraded platform delete a key a tier uses, and deletes the tier with it', async () => {const ctx = await createTestContext(app!, { plan: { aiProvidersEnabled: true } })const key = await mockAndSaveAIProvider({platformId: ctx.platform.id,@@ -42,13 +42,11 @@ describe('Platform model tiers plan gate', () => {const tier = (await ctx.post(TIERS, { name: 'Fast', emoji: '⚡', entries: [{ configId: key.id, modelId: 'gpt-4o' }] })).json()await databaseConnection().getRepository('platform_plan').update({ platformId: ctx.platform.id }, { aiProvidersEnabled: false })- const keyWhileUsed = await ctx.delete(`/v1/ai-providers/${key.id}`)- const deleteTier = await ctx.delete(`${TIERS}/${tier.id}`)const deleteKey = await ctx.delete(`/v1/ai-providers/${key.id}`)+ const deleteTier = await ctx.delete(`${TIERS}/${tier.id}`)- expect(keyWhileUsed.statusCode).toBe(StatusCodes.CONFLICT)- expect(deleteTier.statusCode).toBe(StatusCodes.NO_CONTENT)expect(deleteKey.statusCode).toBe(StatusCodes.NO_CONTENT)+ expect(deleteTier.statusCode).toBe(StatusCodes.NOT_FOUND)})it('allows writes when the plan has AI providers', async () => {diff --git a/packages/web/AGENTS.md b/packages/web/AGENTS.mdindex ba8eadfe3bc..e276a3abfb9 100644--- a/packages/web/AGENTS.md+++ b/packages/web/AGENTS.md@@ -143,6 +143,23 @@ This project uses **ICU MessageFormat** via `i18next-icu` (configured in `src/i1```json"membersAddedCount": "{count, plural, =1 {1 member joined {projectName}} other {# members joined {projectName}}}"```+- **Every translated string must appear in the code as `t('literal text')`.** The key extractor (`i18next-parser.config.js`, `keepRemoved: false`) only finds keys written as `t('...')` with a string literal, and deletes every other key from `translation.json`. A string kept in a constant or config array and rendered later as `t(item.label)` is invisible to it, so its key disappears on the next extraction.+- **Static copy in arrays or config objects goes in a function that calls `t('...')`, called inside the component's render.** Never call `t()` at module scope: that runs at import time, before the language has loaded, so the text stays in English. Render the returned strings as they are, without a second `t()`.+ ```tsx+ // ✅ Correct — the extractor finds each key, and t() runs during render+ function planCatalog() {+ return [{ label: t('Unlimited flows'), tooltip: t('Build as many automations as you want.') }];+ }+ function PlanCard() {+ return planCatalog().map((feature) => <span key={feature.label}>{feature.label}</span>);+ }++ // ❌ Wrong — the extractor never sees 'Unlimited flows', so the key is deleted+ const PLAN_CATALOG = [{ label: 'Unlimited flows' }];+ function PlanCard() {+ return PLAN_CATALOG.map((feature) => <span key={feature.label}>{t(feature.label)}</span>);+ }+ ```## Guidelinesdiff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 46260ed97a1..a8e8403d52c 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -472,6 +472,9 @@"Upgrade plan": "Upgrade plan","Upgrade to unlock": "Upgrade to unlock","Upgrade to {tier}": "Upgrade to {tier}",+ "Your plan does not include Bring your own AI keys": "Your plan does not include Bring your own AI keys",+ "Could not delete this key": "Could not delete this key",+ "You can still delete the keys below. Upgrade your plan to add new keys or change existing ones.": "You can still delete the keys below. Upgrade your plan to add new keys or change existing ones.","Included with the {tier} plan and above.": "Included with the {tier} plan and above.","This is an Enterprise feature, available on our paid plans.": "This is an Enterprise feature, available on our paid plans.","Flow has been renamed.": "Flow has been renamed.",@@ -1754,9 +1757,8 @@"Danger zone": "Danger zone","Irreversible actions for this key.": "Irreversible actions for this key.","Delete this key": "Delete this key",- "Steps and agents using it will stop working.": "Steps and agents using it will stop working.",+ "Flows and agents that use it will fail.": "Flows and agents that use it will fail.","Delete {name}": "Delete {name}",- "Steps and agents using this key will stop working.": "Steps and agents using this key will stop working.","You have unsaved changes": "You have unsaved changes","Change which projects can use {name}?": "Change which projects can use {name}?","Save anyway": "Save anyway",@@ -2645,6 +2647,60 @@"what the call costs": "what the call costs","AI Steps (per call)": "AI Steps (per call)","BYOK": "BYOK",+ "Bring your own AI keys": "Bring your own AI keys",+ "50,000 credits a month, five times what the Plus plan gets.": "50,000 credits a month, five times what the Plus plan gets.",+ "Auto recharge: {price} per {credits} credits": "Auto recharge: {price} per {credits} credits",+ "When your credits run out, auto recharge buys more at this price. It stays off until you turn it on.": "When your credits run out, auto recharge buys more at this price. It stays off until you turn it on.",+ "Perfect for individuals who want to explore automation without any commitment.": "Perfect for individuals who want to explore automation without any commitment.",+ "Plus": "Plus",+ "Built for solo builders who automate regularly and need more credits and advanced tools.": "Built for solo builders who automate regularly and need more credits and advanced tools.",+ "Designed for teams that collaborate on automations and need user management and integrations.": "Designed for teams that collaborate on automations and need user management and integrations.",+ "Enterprise": "Enterprise",+ "For organizations that require enterprise-grade security, compliance, and dedicated support.": "For organizations that require enterprise-grade security, compliance, and dedicated support.",+ "What you get": "What you get",+ "1,000 credits a month": "1,000 credits a month",+ "A fresh 1,000 credits every month, so there is always room to build and test. One credit runs a whole flow.": "A fresh 1,000 credits every month, so there is always room to build and test. One credit runs a whole flow.",+ "Unlimited flows": "Unlimited flows",+ "Build as many automations as you want. We never cap the number of flows.": "Build as many automations as you want. We never cap the number of flows.",+ "Up to 5 users": "Up to 5 users",+ "Invite up to five teammates to build and run automations together.": "Invite up to five teammates to build and run automations together.",+ "Chat to automation": "Chat to automation",+ "Chat with your tools and turn the boring work into automations. Still rolling out, so chat may not be on your account yet.": "Chat with your tools and turn the boring work into automations. Still rolling out, so chat may not be on your account yet.",+ "Flows, Agents, Tables": "Flows, Agents, Tables",+ "Build visual Flows, add Agents and Chat, and keep your data in Tables.": "Build visual Flows, add Agents and Chat, and keep your data in Tables.",+ "MCPs and API access": "MCPs and API access",+ "Serve your tools to any AI assistant over MCP, and manage Activepieces from your own code over the API.": "Serve your tools to any AI assistant over MCP, and manage Activepieces from your own code over the API.",+ "Everything in Free, plus": "Everything in Free, plus",+ "10× the Free plan": "10× the Free plan",+ "10,000 credits a month, ten times what the Free plan gets.": "10,000 credits a month, ten times what the Free plan gets.",+ "Connect your own AI provider keys and every AI step costs 1 credit. The model cost goes to your AI provider, not to your credits.": "Connect your own AI provider keys and every AI step costs 1 credit. The model cost goes to your AI provider, not to your credits.",+ "Everything in Plus, plus": "Everything in Plus, plus",+ "5× the Plus plan": "5× the Plus plan",+ "Unlimited projects": "Unlimited projects",+ "Projects start on Team: separate workspaces for teams, clients, or environments, and you can create as many as you need.": "Projects start on Team: separate workspaces for teams, clients, or environments, and you can create as many as you need.",+ "25 users included": "25 users included",+ "The price is flat, not per seat: twenty-five people for one price.": "The price is flat, not per seat: twenty-five people for one price.",+ "SSO and standard roles": "SSO and standard roles",+ "Single sign-on plus built-in roles to control who can do what.": "Single sign-on plus built-in roles to control who can do what.",+ "Global connections": "Global connections",+ "Shared service-account connections available to every project.": "Shared service-account connections available to every project.",+ "Email support": "Email support",+ "Reach our team by email whenever you need a hand.": "Reach our team by email whenever you need a hand.",+ "Everything in Team, plus": "Everything in Team, plus",+ "Credits sized to you, yearly": "Credits sized to you, yearly",+ "Your allowance runs across the whole year, so a heavy month is covered by a quiet month, and we size the volume to how you run.": "Your allowance runs across the whole year, so a heavy month is covered by a quiet month, and we size the volume to how you run.",+ "Dedicated workers": "Dedicated workers",+ "Your own isolated workers on cloud, not shared with anyone else.": "Your own isolated workers on cloud, not shared with anyone else.",+ "Execution priority": "Execution priority",+ "Set execution priority per project, so the flows that matter run first.": "Set execution priority per project, so the flows that matter run first.",+ "SCIM and custom roles": "SCIM and custom roles",+ "Provision users automatically and define exactly what each role is allowed to do.": "Provision users automatically and define exactly what each role is allowed to do.",+ "Releases and Git Sync": "Releases and Git Sync",+ "Promote changes across environments and keep every flow versioned in your own Git repo.": "Promote changes across environments and keep every flow versioned in your own Git repo.",+ "Audit logs and secrets": "Audit logs and secrets",+ "Track every action, connect your own secret manager, and govern the whole platform centrally.": "Track every action, connect your own secret manager, and govern the whole platform centrally.",+ "Dedicated support": "Dedicated support",+ "A dedicated contact and priority help from our team.": "A dedicated contact and priority help from our team.","Bring Your Own Key — flat execution cost, no model markup": "Bring Your Own Key — flat execution cost, no model markup","What are credits?": "What are credits?","Credits are the unit used to measure your usage on Activepieces. Every action you run consumes a certain number of credits depending on what it does.": "Credits are the unit used to measure your usage on Activepieces. Every action you run consumes a certain number of credits depending on what it does.",@@ -2707,14 +2763,15 @@"Activate trial key": "Activate trial key","Activate license key": "Activate license key","Update license key": "Update license key",- "billed annually ({total}/year)": "billed annually ({total}/year)",+ "flat per month, billed monthly": "flat per month, billed monthly",+ "flat per month, billed yearly": "flat per month, billed yearly","{amount} credits/day": "{amount} credits/day","{amount} credits/mo": "{amount} credits/mo","{amount} credits/yr": "{amount} credits/yr","{amount} credits": "{amount} credits","Your {count, plural, =1 {1 additional seat} other {# additional seats}} will be removed and the unused time credited back.": "Your {count, plural, =1 {1 additional seat} other {# additional seats}} will be removed and the unused time credited back.","Downgrade to Free": "Downgrade to Free",- "{count, plural, =1 {1 free month} other {# free months}}": "{count, plural, =1 {1 free month} other {# free months}}",+ "Save {count, plural, =1 {1 month} other {# months}}": "Save {count, plural, =1 {1 month} other {# months}}","Talk to sales": "Talk to sales","Downgrade": "Downgrade","Purchase Now": "Purchase Now",@@ -3140,5 +3197,6 @@"1 min ago": "1 min ago","{count} mins ago": "{count} mins ago","1 hour ago": "1 hour ago",- "{count} hours ago": "{count} hours ago"+ "{count} hours ago": "{count} hours ago",+ "Flows and agents that use this key will fail.": "Flows and agents that use this key will fail."}diff --git a/packages/web/src/app/components/feature-banner.tsx b/packages/web/src/app/components/feature-banner.tsxindex 5661c67a2d6..e518d932e88 100644--- a/packages/web/src/app/components/feature-banner.tsx+++ b/packages/web/src/app/components/feature-banner.tsx@@ -3,7 +3,7 @@ import { t } from 'i18next';import { ExternalLink } from 'lucide-react';import { Alert, AlertDescription } from '@/components/ui/alert';-import { useManagePlanDialogStore } from '@/features/billing';+import { billingDialogHooks } from '@/features/billing';import { flagsHooks } from '@/hooks/flags-hooks';import { AdminControl, adminControl } from '@/lib/admin-control';@@ -12,7 +12,8 @@ export function FeatureBanner({documentationUrl,className,}: FeatureBannerProps) {- const { openDialog: openManagePlanDialog } = useManagePlanDialogStore();+ const { openDialog: openManagePlanDialog } =+ billingDialogHooks.useManagePlanDialogStore();const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);const isCommunity = edition === ApEdition.COMMUNITY;const docsUrl = documentationUrl ?? ENTERPRISE_DOCUMENTATION_URL;diff --git a/packages/web/src/app/query-client.ts b/packages/web/src/app/query-client.tsindex e925eb8835d..6921a98c6f6 100644--- a/packages/web/src/app/query-client.ts+++ b/packages/web/src/app/query-client.ts@@ -3,7 +3,7 @@ import { MutationCache, QueryCache, QueryClient } from '@tanstack/react-query';import { StatusCodes } from 'http-status-codes';import { internalErrorToast } from '@/components/ui/sonner';-import { useManagePlanDialogStore } from '@/features/billing';+import { billingDialogHooks } from '@/features/billing';import { api } from '@/lib/api';import { errorReporting } from '@/lib/error-reporting';@@ -50,7 +50,8 @@ export const queryClient = new QueryClient({return;}if (api.isApError(err, ErrorCode.QUOTA_EXCEEDED)) {- const { openDialog } = useManagePlanDialogStore.getState();+ const { openDialog } =+ billingDialogHooks.useManagePlanDialogStore.getState();openDialog();} else {internalErrorToast();diff --git a/packages/web/src/app/routes/platform-routes.tsx b/packages/web/src/app/routes/platform-routes.tsxindex 6403b4c4154..2fd4ed0c26c 100644--- a/packages/web/src/app/routes/platform-routes.tsx+++ b/packages/web/src/app/routes/platform-routes.tsx@@ -162,11 +162,9 @@ export const platformRoutes = [<PlatformLayout><PageTitle title="AI Center"><LegacyTabRedirect basePath="/platform/ai" tabPaths={AI_TAB_PATHS}>- <PlanFeatureSample feature="aiProviders">- <SuspenseWrapper>- <AIProvidersPage section="providers" />- </SuspenseWrapper>- </PlanFeatureSample>+ <SuspenseWrapper>+ <AIProvidersPage section="providers" />+ </SuspenseWrapper></LegacyTabRedirect></PageTitle></PlatformLayout>diff --git a/packages/web/src/app/routes/platform/billing/index.tsx b/packages/web/src/app/routes/platform/billing/index.tsxindex 11b19f5020c..850b8243d37 100644--- a/packages/web/src/app/routes/platform/billing/index.tsx+++ b/packages/web/src/app/routes/platform/billing/index.tsx@@ -28,7 +28,7 @@ import {billingMutations,billingUtils,useCancelSubscriptionGuard,- useManagePlanDialogStore,+ billingDialogHooks,} from '@/features/billing';import { flagsHooks } from '@/hooks/flags-hooks';import { platformHooks } from '@/hooks/platform-hooks';@@ -100,7 +100,7 @@ function BillingRefreshButton() {}function PlanTab({ platform, info }: PlanTabProps) {- const { openDialog } = useManagePlanDialogStore();+ const { openDialog } = billingDialogHooks.useManagePlanDialogStore();const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);const isCommunity = edition === ApEdition.COMMUNITY;const { mutate: redirectToPortalSession, isPending: isOpeningPortal } =diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsxindex 7bb20a7bc0a..ae20f044d1f 100644--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx@@ -381,7 +381,7 @@ export function ConfigDetail({{t('Delete this key')}</p><p className="mt-1 text-sm text-gray-11">- {t('Steps and agents using it will stop working.')}+ {t('Flows and agents that use it will fail.')}</p></div><Button@@ -399,9 +399,10 @@ export function ConfigDetail({open={deleteOpen}onOpenChange={setDeleteOpen}title={t('Delete {name}', { name: config.name })}- message={t('Steps and agents using this key will stop working.')}+ message={t('Flows and agents that use this key will fail.')}entityName={config.name}showToast={true}+ onError={() => undefined}controlId={AdminControl.AI_PROVIDER_KEY_DELETE_CONFIRM}mutationFn={async () => {await onDelete();diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsxindex 632ef80cae4..1ce07743c54 100644--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsx+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/index.tsx@@ -1,14 +1,27 @@import { AIProviderName, tryCatch } from '@activepieces/core-utils';-import { AIProviderWithoutSensitiveData, Project } from '@activepieces/shared';+import {+ AIProviderWithoutSensitiveData,+ PlatformAdminSurface,+ Project,+} from '@activepieces/shared';import { useQueryClient } from '@tanstack/react-query';import { t } from 'i18next';-import { Bot, ChevronRight, MessageSquare, Plus, Trash2 } from 'lucide-react';+import {+ Bot,+ ChevronRight,+ Lock,+ MessageSquare,+ Plus,+ Trash2,+} from 'lucide-react';import { useState } from 'react';import { useSearchParams } from 'react-router-dom';import { toast } from 'sonner';+import { PlanFeatureSample } from '@/app/routes/platform/plan-feature-sample';import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import {Select,@@ -24,12 +37,18 @@ import {TooltipTrigger,} from '@/components/ui/tooltip';import { AiProviderInfo, SUPPORTED_AI_PROVIDERS } from '@/features/agents';+import {+ PLATFORM_FEATURES,+ TIER_LABELS,+ useUpgradeClick,+} from '@/features/billing';import {aiProviderKeys,aiProviderMutations,aiProviderQueries,} from '@/features/platform-admin';import { projectCollectionUtils } from '@/features/projects';+import { platformHooks } from '@/hooks/platform-hooks';import { AdminControl, adminControl } from '@/lib/admin-control';import { cn } from '@/lib/utils';@@ -53,6 +72,8 @@ export function ProvidersTab() {>(undefined);const queryClient = useQueryClient();+ const { platform } = platformHooks.useCurrentPlatform();+ const locked = !platform.plan.aiProvidersEnabled;const {data: providers,isLoading,@@ -77,6 +98,16 @@ export function ProvidersTab() {const { mutateAsync: deleteProvider } =aiProviderMutations.useDeleteAiProvider({onSuccess: () => refetch(),+ onError: (error) => {+ const data = error.response?.data;+ toast.error(+ t(+ data?.params?.message ??+ data?.message ??+ 'Could not delete this key',+ ),+ );+ },});const { mutate: recheckProvider, isPending: isRechecking } =aiProviderMutations.useRecheckAiProvider({@@ -162,7 +193,7 @@ export function ProvidersTab() {const activeInfo = activeConfig? providerInfoOf({ provider: activeConfig.provider }): undefined;- if (activeConfig && activeInfo) {+ if (activeConfig && activeInfo && !locked) {return (<><ConfigDetail@@ -193,7 +224,7 @@ export function ProvidersTab() {);}- return (+ const page = (<><div className="flex flex-col gap-6"><div className="flex items-start justify-between gap-3">@@ -209,15 +240,17 @@ export function ProvidersTab() {: t('Each key has its own models and project access.')}/>- <Button- size="sm"- className="shrink-0"- onClick={() => openConnect()}- {...adminControl(AdminControl.AI_PROVIDER_KEY_OPEN)}- >- <Plus className="size-4" />- {t('Add key')}- </Button>+ {!locked && (+ <Button+ size="sm"+ className="shrink-0"+ onClick={() => openConnect()}+ {...adminControl(AdminControl.AI_PROVIDER_KEY_OPEN)}+ >+ <Plus className="size-4" />+ {t('Add key')}+ </Button>+ )}</div>{isProvidersError ? (@@ -226,12 +259,15 @@ export function ProvidersTab() {<EmptyProviders onConnect={openConnect} />) : (<>- <ChatProviderRow- configs={providers ?? []}- value={chatProviderRow?.id ?? null}- isSwitching={isSwitchingChatProvider}- onChange={selectChatConfig}- />+ {locked && <LockedProvidersAlert />}+ {!locked && (+ <ChatProviderRow+ configs={providers ?? []}+ value={chatProviderRow?.id ?? null}+ isSwitching={isSwitchingChatProvider}+ onChange={selectChatConfig}+ />+ )}<div className="flex flex-col gap-6">{connectedProviders.map((provider) => (<ProviderGroup@@ -241,13 +277,14 @@ export function ProvidersTab() {(config) => config.provider === provider,)}projects={projects}+ locked={locked}onAdd={() => openConnect(provider)}onOpen={openConfig}onDelete={(id) => deleteProvider(id)}/>))}</div>- {available.length > 0 && (+ {!locked && available.length > 0 && (<section className="flex flex-col gap-4 border-t border-gray-6/60 pt-6"><SectionHeadertitle={t('Also available')}@@ -280,12 +317,51 @@ export function ProvidersTab() {/></>);++ if (configs.length === 0 && !isProvidersError) {+ return <PlanFeatureSample feature="aiProviders">{page}</PlanFeatureSample>;+ }+ return page;+}++function LockedProvidersAlert() {+ const upgradeClick = useUpgradeClick();+ const { featureKey, tier } = PLATFORM_FEATURES.aiProviders;++ return (+ <Alert variant="primary">+ <Lock />+ <AlertTitle>+ {t('Your plan does not include Bring your own AI keys')}+ </AlertTitle>+ <AlertDescription className="flex flex-col items-start gap-3">+ <p>+ {t(+ 'You can still delete the keys below. Upgrade your plan to add new keys or change existing ones.',+ )}+ </p>+ <Button+ size="sm"+ onClick={() =>+ upgradeClick({+ feature: featureKey,+ tier,+ surface: PlatformAdminSurface.SAMPLE,+ })+ }+ >+ {t('Upgrade to {tier}', { tier: TIER_LABELS[tier] })}+ </Button>+ </AlertDescription>+ </Alert>+ );}function ProviderGroup({provider,configs,projects,+ locked,onAdd,onOpen,onDelete,@@ -293,6 +369,7 @@ function ProviderGroup({provider: AIProviderName;configs: AIProviderWithoutSensitiveData[];projects: Project[];+ locked: boolean;onAdd: () => void;onOpen: (id: string) => void;onDelete: (id: string) => Promise<unknown>;@@ -317,15 +394,17 @@ function ProviderGroup({{t('configurationsCount', { count: configs.length })}</p></div>- <Button- variant="ghost"- size="sm"- onClick={onAdd}- {...adminControl(AdminControl.AI_PROVIDER_KEY_OPEN)}- >- <Plus className="size-4" />- {t('Add key')}- </Button>+ {!locked && (+ <Button+ variant="ghost"+ size="sm"+ onClick={onAdd}+ {...adminControl(AdminControl.AI_PROVIDER_KEY_OPEN)}+ >+ <Plus className="size-4" />+ {t('Add key')}+ </Button>+ )}</div><div className="border-t border-gray-6/60 px-5 pb-1 pt-3"><p className="text-[11px] font-medium uppercase tracking-wide text-gray-11">@@ -338,6 +417,7 @@ function ProviderGroup({key={config.id}config={config}projects={projects}+ locked={locked}onOpen={() => onOpen(config.id)}onDelete={() => onDelete(config.id)}/>@@ -350,11 +430,13 @@ function ProviderGroup({function ConfigRow({config,projects,+ locked,onOpen,onDelete,}: {config: AIProviderWithoutSensitiveData;projects: Project[];+ locked: boolean;onOpen: () => void;onDelete: () => Promise<unknown>;}) {@@ -379,18 +461,19 @@ function ConfigRow({return (<div- role="button"- tabIndex={0}- onClick={onOpen}+ role={locked ? undefined : 'button'}+ tabIndex={locked ? undefined : 0}+ onClick={locked ? undefined : onOpen}onKeyDown={(event) => {- if (event.key === 'Enter' || event.key === ' ') {+ if (!locked && (event.key === 'Enter' || event.key === ' ')) {event.preventDefault();onOpen();}}}className={cn('group flex items-center gap-4 px-5 py-3 transition-colors',- 'cursor-pointer hover:bg-gray-4 active:bg-gray-5 focus-visible:bg-gray-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-8',+ !locked &&+ 'cursor-pointer hover:bg-gray-4 active:bg-gray-5 focus-visible:bg-gray-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-8',)}><div className="flex min-w-0 flex-1 flex-col gap-1">@@ -440,7 +523,10 @@ function ConfigRow({<Buttonvariant="ghost"size="sm"- className="px-2 text-gray-11 opacity-0 transition-opacity hover:bg-danger-3 hover:text-danger-11 focus-visible:opacity-100 group-hover:opacity-100"+ className={cn(+ 'px-2 text-gray-11 opacity-0 transition-opacity hover:bg-danger-3 hover:text-danger-11 focus-visible:opacity-100 group-hover:opacity-100',+ locked && 'opacity-100',+ )}onClick={() => setDeleteOpen(true)}{...adminControl(AdminControl.AI_PROVIDER_KEY_DELETE_OPEN)}>@@ -450,14 +536,17 @@ function ConfigRow({</TooltipTrigger><TooltipContent>{t('Delete')}</TooltipContent></Tooltip>- <ChevronRight className="size-4 text-gray-11 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-gray-12" />+ {!locked && (+ <ChevronRight className="size-4 text-gray-11 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-gray-12" />+ )}<ConfirmationDeleteDialogopen={deleteOpen}onOpenChange={setDeleteOpen}title={t('Delete {name}', { name: config.name })}- message={t('Steps and agents using this key will stop working.')}+ message={t('Flows and agents that use this key will fail.')}entityName={config.name}showToast={true}+ onError={() => undefined}controlId={AdminControl.AI_PROVIDER_KEY_DELETE_CONFIRM}mutationFn={async () => {await onDelete();diff --git a/packages/web/src/features/billing/components/confirm-purchase-dialog.tsx b/packages/web/src/features/billing/components/confirm-purchase-dialog.tsxindex bb0b395edf4..bb12842df99 100644--- a/packages/web/src/features/billing/components/confirm-purchase-dialog.tsx+++ b/packages/web/src/features/billing/components/confirm-purchase-dialog.tsx@@ -13,16 +13,17 @@ import {} from '@/components/ui/dialog';import { AdminControl, adminControl } from '@/lib/admin-control';+import { billingDialogHooks } from '../hooks/billing-dialog-hooks';import { billingMutations } from '../hooks/billing-hooks';import { usePlanSeatFloorGuard } from '../hooks/use-plan-seat-floor-guard';-import { useConfirmPurchaseDialogStore } from '../stores/confirm-purchase-dialog-state';import { planSelectorUtils } from './plan-selector-utils';export function ConfirmPurchaseDialog() {- const { payload, closeDialog } = useConfirmPurchaseDialogStore();+ const { purchase, closeDialog } =+ billingDialogHooks.useConfirmPurchaseDialogStore();const { openSeatFloor, seatFloorDialog } = usePlanSeatFloorGuard({- enabled: !isNil(payload),+ enabled: !isNil(purchase),});const { mutate: checkout, isPending } = billingMutations.useCheckout({onDone: () => closeDialog(),@@ -37,7 +38,7 @@ export function ConfirmPurchaseDialog() {});const cycleLabel =- payload?.billingCycle === planSelectorUtils.ANNUAL_INTERVAL+ purchase?.billingCycle === planSelectorUtils.ANNUAL_INTERVAL? t('Annually'): t('Monthly');@@ -45,15 +46,15 @@ export function ConfirmPurchaseDialog() {<>{seatFloorDialog}<Dialog- open={!isNil(payload)}+ open={!isNil(purchase)}onOpenChange={(open) => !open && closeDialog()}><DialogContent className="max-w-md">- {!isNil(payload) && (+ {!isNil(purchase) && (<><DialogHeader><DialogTitle>- {t('Confirm your {plan} plan', { plan: payload.planName })}+ {t('Confirm your {plan} plan', { plan: purchase.planName })}</DialogTitle><DialogDescription>{t(@@ -69,7 +70,7 @@ export function ConfirmPurchaseDialog() {</span><div className="flex items-baseline gap-2"><span className="text-3xl font-bold">- {payload.priceAmount}+ {purchase.priceAmount}</span><span className="text-sm text-gray-11">{t('billed {cycle}', { cycle: cycleLabel.toLowerCase() })}@@ -77,15 +78,15 @@ export function ConfirmPurchaseDialog() {</div></div>- {payload.features.length > 0 && (+ {purchase.features.length > 0 && (<ul className="flex flex-col gap-2.5">- {payload.features.map((feature) => (+ {purchase.features.map((feature) => (<likey={feature}className="flex items-center gap-2 text-sm text-gray-12"><Check className="size-4 shrink-0 text-accent-11" />- <span>{t(feature)}</span>+ <span>{feature}</span></li>))}</ul>@@ -109,8 +110,8 @@ export function ConfirmPurchaseDialog() {loading={isPending}onClick={() =>checkout({- planId: payload.planId,- successUrl: payload.successUrl,+ planId: purchase.planId,+ successUrl: purchase.successUrl,})}>diff --git a/packages/web/src/features/billing/components/credits-action-button.tsx b/packages/web/src/features/billing/components/credits-action-button.tsxindex 5993da8d43a..896bae8321f 100644--- a/packages/web/src/features/billing/components/credits-action-button.tsx+++ b/packages/web/src/features/billing/components/credits-action-button.tsx@@ -8,9 +8,9 @@ import { Button } from '@/components/ui/button';import { flagsHooks } from '@/hooks/flags-hooks';import { AdminControl, adminControl } from '@/lib/admin-control';+import { billingDialogHooks } from '../hooks/billing-dialog-hooks';import { billingQueries } from '../hooks/billing-hooks';import { useCreditsUsage } from '../hooks/use-credits-usage';-import { useManagePlanDialogStore } from '../stores/manage-plan-dialog-state';import { billingUtils } from '../utils/billing-utils';import { AutoRechargeConfigDialog } from './feature-usage/auto-recharge-config-dialog';@@ -23,7 +23,8 @@ export function CreditsActionButton({useCreditsUsage();const { embedState } = useEmbedding();const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);- const { openDialog: openManagePlanDialog } = useManagePlanDialogStore();+ const { openDialog: openManagePlanDialog } =+ billingDialogHooks.useManagePlanDialogStore();const [autoRechargeOpen, setAutoRechargeOpen] = useState(false);const canManageBilling =diff --git a/packages/web/src/features/billing/components/feature-usage/credits-card.tsx b/packages/web/src/features/billing/components/feature-usage/credits-card.tsxindex 4ec337940d9..f813bac2c47 100644--- a/packages/web/src/features/billing/components/feature-usage/credits-card.tsx+++ b/packages/web/src/features/billing/components/feature-usage/credits-card.tsx@@ -34,7 +34,7 @@ export const CreditsCard = ({ info }: CreditsCardProps) => {<div className="flex items-start justify-between gap-4"><div className="flex items-baseline gap-1.5"><span className="text-3xl font-bold text-gray-12">- {(isUnlimited ? used : total).toLocaleString()}+ {Math.floor(isUnlimited ? used : total).toLocaleString()}</span><span className="text-gray-11">{t('credits')}</span></div>@@ -44,7 +44,7 @@ export const CreditsCard = ({ info }: CreditsCardProps) => {<Progress value={percentUsed} usage /><span className="text-sm text-gray-11">{t('{amount} remaining', {- amount: Math.round(remaining).toLocaleString(),+ amount: Math.floor(remaining).toLocaleString(),})}</span></>diff --git a/packages/web/src/features/billing/components/manage-plan-dialog.tsx b/packages/web/src/features/billing/components/manage-plan-dialog.tsxindex 089a1e26563..86f4af0d7cc 100644--- a/packages/web/src/features/billing/components/manage-plan-dialog.tsx+++ b/packages/web/src/features/billing/components/manage-plan-dialog.tsx@@ -7,14 +7,14 @@ import {DialogTitle,} from '@/components/ui/dialog';-import { useManagePlanDialogStore } from '../stores/manage-plan-dialog-state';+import { billingDialogHooks } from '../hooks/billing-dialog-hooks';import { ConfirmPurchaseDialog } from './confirm-purchase-dialog';import { PlanSelector } from './plan-selector';import { PlanSwitchSuccessDialog } from './plan-switch-success-dialog';export function ManagePlanDialog() {- const { isOpen, closeDialog } = useManagePlanDialogStore();+ const { isOpen, closeDialog } = billingDialogHooks.useManagePlanDialogStore();return (<>diff --git a/packages/web/src/features/billing/components/plan-selector-utils.ts b/packages/web/src/features/billing/components/plan-selector-utils.tsindex 2feeb69a30a..2db5909609b 100644--- a/packages/web/src/features/billing/components/plan-selector-utils.ts+++ b/packages/web/src/features/billing/components/plan-selector-utils.ts@@ -2,6 +2,8 @@ import { isNil } from '@activepieces/core-utils';import { PurchasablePlan } from '@activepieces/shared';import { t } from 'i18next';+import { formatUtils } from '@/lib/format-utils';+const FREE_PLAN_ID = 'free';const ANNUAL_INTERVAL = 'year';const SALES_URL = 'https://www.activepieces.com/sales?ap_cta=app_plan_selector';@@ -31,11 +33,9 @@ function findPurchasablePlan({function computePricing({entry,apiPlan,- monthlySibling,}: {entry: PlanCatalogEntry;apiPlan?: PurchasablePlan;- monthlySibling?: PurchasablePlan;}): PlanPricing | null {if (entry.key === 'enterprise') {return null;@@ -50,64 +50,54 @@ function computePricing({const amount = isNil(apiPlan.price)? apiPlan.priceDisplay ?? '': `$${apiPlan.price}`;- return { amount, suffix: t('/mo') };+ return { amount, note: t('flat per month, billed monthly') };}if (isNil(apiPlan.price)) {return { amount: apiPlan.priceDisplay ?? '', suffix: t('/year') };}const perMonth = Math.floor(apiPlan.price / 12);- const monthlyPrice = monthlySibling?.price;- const freeMonths =- !isNil(monthlyPrice) && monthlyPrice > 0- ? Math.round(12 - apiPlan.price / monthlyPrice)- : null;return {amount: `$${perMonth.toLocaleString()}`,- suffix: t('/mo'),- freeMonths: !isNil(freeMonths) && freeMonths >= 1 ? freeMonths : null,- annualNote: t('billed annually ({total}/year)', {- total: `$${apiPlan.price.toLocaleString()}`,- }),+ note: t('flat per month, billed yearly'),};}-function resolveFeatures({- entry,- apiPlan,-}: {- entry: PlanCatalogEntry;- apiPlan?: PurchasablePlan;-}): ResolvedPlanFeature[] {- return entry.features.flatMap((feature): ResolvedPlanFeature[] => {- if (isNil(feature.metric)) {- return isNil(feature.label)- ? []- : [{ label: feature.label, tooltip: feature.tooltip }];- }- if (feature.metric === 'seats') {- return isNil(apiPlan?.includedSeats)- ? []- : [- {- label: t('{count, plural, =1 {1 seat} other {# seats}}', {- count: apiPlan.includedSeats,- }),- tooltip: feature.tooltip,- },- ];+function creditTopUpFeature(apiPlan?: PurchasablePlan): PlanFeature[] {+ if (isNil(apiPlan?.creditTopUp)) {+ return [];+ }+ return [+ {+ label: t('Auto recharge: {price} per {credits} credits', {+ price: `$${apiPlan.creditTopUp.price.toLocaleString()}`,+ credits: formatUtils.formatNumberCompact(apiPlan.creditTopUp.credits),+ }),+ tooltip: t(+ 'When your credits run out, auto recharge buys more at this price. It stays off until you turn it on.',+ ),+ },+ ];+}++function annualSavedMonths(plans: PurchasablePlan[]): number | null {+ const savedMonths = planCatalog().flatMap((entry) => {+ const annualPrice = findPurchasablePlan({+ plans,+ key: entry.key,+ cycle: 'year',+ })?.price;+ const monthlyPrice = findPurchasablePlan({+ plans,+ key: entry.key,+ cycle: 'month',+ })?.price;+ if (isNil(annualPrice) || isNil(monthlyPrice) || monthlyPrice <= 0) {+ return [];}- return isNil(apiPlan?.includedCredits)- ? []- : [- {- label: creditsLabel({- credits: apiPlan.includedCredits,- interval: apiPlan.creditsResetInterval,- }),- tooltip: feature.tooltip,- },- ];+ return [Math.round(12 - annualPrice / monthlyPrice)];});+ const mostSaved = Math.max(0, ...savedMonths);+ return mostSaved >= 1 ? mostSaved : null;}function creditsLabel({@@ -156,119 +146,191 @@ function dropToFreeWarning(additionalSeats: number | null | undefined): string {)}`;}-const PLAN_CATALOG: PlanCatalogEntry[] = [- {- key: 'free',- name: 'Free',- blurb:- 'Perfect for individuals who want to explore automation without any commitment.',- featuresHeader: "What's included:",- features: [- { metric: 'credits' },- { metric: 'seats' },- { label: 'Automation flows' },- { label: 'Personal project only' },- { label: 'Tables' },- { label: 'API Keys' },- ],- },- {- key: 'plus',- name: 'Plus',- blurb:- 'Built for solo builders who automate regularly and need more credits and advanced tools.',- featuresHeader: 'Everything in Free, +',- features: [- { metric: 'credits' },- { metric: 'seats' },- { label: 'Agents' },- { label: '1 team project, MCPs' },- { label: 'BYOK' },- { label: 'Team analytics' },- ],- },- {- key: 'team',- name: 'Team',- highlighted: true,- blurb:- 'Designed for teams that collaborate on automations and need user management and integrations.',- featuresHeader: 'Everything in Plus, +',- features: [- { metric: 'credits' },- { metric: 'seats' },- { label: 'Unlimited team projects' },- { label: 'SSO' },- { label: 'Standard roles' },- { label: 'Global connections' },- { label: 'Email support' },- ],- },- {- key: 'enterprise',- name: 'Enterprise',- blurb:- 'For organizations that require enterprise-grade security, compliance, and dedicated support.',- featuresHeader: 'Everything in Team, +',- features: [- {- label: 'From 1M credits',- tooltip:- 'Custom monthly AI credit allotment negotiated for your organization.',- },- {- label: 'SSO + SCIM',- tooltip:- 'Single sign-on with automated user provisioning and deprovisioning.',- },- {- label: 'Custom RBAC',- tooltip: 'Define custom roles and granular permissions for your team.',- },- {- label: 'Audit logs',- tooltip: 'Full activity history across your platform for compliance.',- },- {- label: 'Priority execution',- tooltip: 'Higher execution priority and dedicated capacity.',- },- {- label: 'White-label',- tooltip:- 'Fully brand the platform with your own logo, colors, and domain.',- },- {- label: 'Embedding',- tooltip:- 'Embed Activepieces (flows/chat/connections/tables..etc) directly inside your own product.',- },- {- label: 'Piece management',- tooltip: 'Control which pieces are available across your platform.',- },- {- label: 'Template management',- tooltip: 'Curate and manage flow templates for your team.',- },- {- label: 'Dedicated support',- tooltip: 'A dedicated support contact and onboarding assistance.',- },- ],- },-];+function planCatalog(): PlanCatalogEntry[] {+ return [+ {+ key: 'free',+ name: t('Free'),+ blurb: t(+ 'Perfect for individuals who want to explore automation without any commitment.',+ ),+ featuresHeader: t('What you get'),+ features: [+ {+ label: t('1,000 credits a month'),+ tooltip: t(+ 'A fresh 1,000 credits every month, so there is always room to build and test. One credit runs a whole flow.',+ ),+ },+ {+ label: t('Unlimited flows'),+ tooltip: t(+ 'Build as many automations as you want. We never cap the number of flows.',+ ),+ },+ {+ label: t('Up to 5 users'),+ tooltip: t(+ 'Invite up to five teammates to build and run automations together.',+ ),+ },+ {+ label: t('Chat to automation'),+ tooltip: t(+ 'Chat with your tools and turn the boring work into automations. Still rolling out, so chat may not be on your account yet.',+ ),+ },+ {+ label: t('Flows, Agents, Tables'),+ tooltip: t(+ 'Build visual Flows, add Agents and Chat, and keep your data in Tables.',+ ),+ },+ {+ label: t('MCPs and API access'),+ tooltip: t(+ 'Serve your tools to any AI assistant over MCP, and manage Activepieces from your own code over the API.',+ ),+ },+ ],+ },+ {+ key: 'plus',+ name: t('Plus'),+ blurb: t(+ 'Built for solo builders who automate regularly and need more credits and advanced tools.',+ ),+ featuresHeader: t('Everything in Free, plus'),+ features: [+ {+ label: t('10× the Free plan'),+ tooltip: t(+ '10,000 credits a month, ten times what the Free plan gets.',+ ),+ },+ {+ label: t('Up to 5 users'),+ tooltip: t(+ 'Invite up to five teammates to build and run automations together.',+ ),+ },+ {+ label: t('Bring your own AI keys'),+ tooltip: t(+ 'Connect your own AI provider keys and every AI step costs 1 credit. The model cost goes to your AI provider, not to your credits.',+ ),+ },+ ],+ },+ {+ key: 'team',+ name: t('Team'),+ highlighted: true,+ blurb: t(+ 'Designed for teams that collaborate on automations and need user management and integrations.',+ ),+ featuresHeader: t('Everything in Plus, plus'),+ features: [+ {+ label: t('5× the Plus plan'),+ tooltip: t(+ '50,000 credits a month, five times what the Plus plan gets.',+ ),+ },+ {+ label: t('Unlimited projects'),+ tooltip: t(+ 'Projects start on Team: separate workspaces for teams, clients, or environments, and you can create as many as you need.',+ ),+ },+ {+ label: t('25 users included'),+ tooltip: t(+ 'The price is flat, not per seat: twenty-five people for one price.',+ ),+ },+ {+ label: t('SSO and standard roles'),+ tooltip: t(+ 'Single sign-on plus built-in roles to control who can do what.',+ ),+ },+ {+ label: t('Global connections'),+ tooltip: t(+ 'Shared service-account connections available to every project.',+ ),+ },+ {+ label: t('Email support'),+ tooltip: t('Reach our team by email whenever you need a hand.'),+ },+ ],+ },+ {+ key: 'enterprise',+ name: t('Enterprise'),+ blurb: t(+ 'For organizations that require enterprise-grade security, compliance, and dedicated support.',+ ),+ featuresHeader: t('Everything in Team, plus'),+ features: [+ {+ label: t('Credits sized to you, yearly'),+ tooltip: t(+ 'Your allowance runs across the whole year, so a heavy month is covered by a quiet month, and we size the volume to how you run.',+ ),+ },+ {+ label: t('Dedicated workers'),+ tooltip: t(+ 'Your own isolated workers on cloud, not shared with anyone else.',+ ),+ },+ {+ label: t('Execution priority'),+ tooltip: t(+ 'Set execution priority per project, so the flows that matter run first.',+ ),+ },+ {+ label: t('SCIM and custom roles'),+ tooltip: t(+ 'Provision users automatically and define exactly what each role is allowed to do.',+ ),+ },+ {+ label: t('Releases and Git Sync'),+ tooltip: t(+ 'Promote changes across environments and keep every flow versioned in your own Git repo.',+ ),+ },+ {+ label: t('Audit logs and secrets'),+ tooltip: t(+ 'Track every action, connect your own secret manager, and govern the whole platform centrally.',+ ),+ },+ {+ label: t('Dedicated support'),+ tooltip: t('A dedicated contact and priority help from our team.'),+ },+ ],+ },+ ];+}export const planSelectorUtils = {stripPlanInterval,findPurchasablePlan,computePricing,- resolveFeatures,+ annualSavedMonths,creditsLabel,dropToFreeWarning,actionFor,buildSuccessUrl,- PLAN_CATALOG,+ planCatalog,+ creditTopUpFeature,FREE_PLAN_ID,ANNUAL_INTERVAL,SALES_URL,@@ -283,21 +345,14 @@ export type CheckoutAction = 'create' | 'upgrade' | 'downgrade';export type PlanPricing = {amount: string;suffix?: string;- freeMonths?: number | null;- annualNote?: string;+ note?: string;};export type PlanKey = 'free' | 'plus' | 'team' | 'enterprise';export type PlanFeature = {- label?: string;- tooltip?: string;- metric?: 'seats' | 'credits';-};--export type ResolvedPlanFeature = {label: string;- tooltip?: string;+ tooltip: string;};export type PlanCatalogEntry = {diff --git a/packages/web/src/features/billing/components/plan-selector.tsx b/packages/web/src/features/billing/components/plan-selector.tsxindex 5e331d09916..292510cccba 100644--- a/packages/web/src/features/billing/components/plan-selector.tsx+++ b/packages/web/src/features/billing/components/plan-selector.tsx@@ -1,11 +1,10 @@import { isNil } from '@activepieces/core-utils';import { PurchasablePlan, TelemetryEventName } from '@activepieces/shared';import { t } from 'i18next';-import { Check, Info } from 'lucide-react';+import { Check } from 'lucide-react';import { useState } from 'react';import { useTelemetry } from '@/components/providers/telemetry-provider';-import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';@@ -18,10 +17,10 @@ import { platformHooks } from '@/hooks/platform-hooks';import { AdminControl, adminControl } from '@/lib/admin-control';import { cn } from '@/lib/utils';+import { billingDialogHooks } from '../hooks/billing-dialog-hooks';import { billingMutations, billingQueries } from '../hooks/billing-hooks';import { useCancelSubscriptionGuard } from '../hooks/use-cancel-subscription-guard';import { usePlanSeatFloorGuard } from '../hooks/use-plan-seat-floor-guard';-import { useConfirmPurchaseDialogStore } from '../stores/confirm-purchase-dialog-state';import { CancelSubscriptionDialog } from './cancel-subscription-dialog';import { KeepPlanDialog } from './keep-plan-dialog';@@ -63,7 +62,8 @@ export function PlanSelector({ enabled, onSelected }: PlanSelectorProps) {platform.id,enabled,);- const { openDialog: openConfirmDialog } = useConfirmPurchaseDialogStore();+ const { openDialog: openConfirmDialog } =+ billingDialogHooks.useConfirmPurchaseDialogStore();const currentPlanId = subscription?.plan.plan ?? platform.plan.plan;const hasScheduledChange = !isNil(subscription?.cancelAt);@@ -75,6 +75,7 @@ export function PlanSelector({ enabled, onSelected }: PlanSelectorProps) {const hasAnnualOption = allPlans.some((plan) => plan.interval === planSelectorUtils.ANNUAL_INTERVAL,);+ const annualSavedMonths = planSelectorUtils.annualSavedMonths(allPlans);const [cycleOverride, setCycleOverride] = useState<BillingCycle | null>(null);const billingCycle =cycleOverride ??@@ -128,12 +129,21 @@ export function PlanSelector({ enabled, onSelected }: PlanSelectorProps) {><TabsList><TabsTrigger value="month">{t('Monthly')}</TabsTrigger>- <TabsTrigger value="year">{t('Annually')}</TabsTrigger>+ <TabsTrigger value="year" className="gap-1.5">+ {t('Annually')}+ {!isNil(annualSavedMonths) && (+ <span className="text-xs font-medium text-accent-11">+ {t('Save {count, plural, =1 {1 month} other {# months}}', {+ count: annualSavedMonths,+ })}+ </span>+ )}+ </TabsTrigger></TabsList></Tabs>)}<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">- {planSelectorUtils.PLAN_CATALOG.map((entry) => {+ {planSelectorUtils.planCatalog().map((entry) => {const apiPlan =entry.key === 'enterprise'? undefined@@ -142,14 +152,6 @@ export function PlanSelector({ enabled, onSelected }: PlanSelectorProps) {key: entry.key,cycle: entry.key === 'free' ? 'month' : billingCycle,});- const monthlySibling =- entry.key === 'enterprise' || entry.key === 'free'- ? undefined- : planSelectorUtils.findPurchasablePlan({- plans: allPlans,- key: entry.key,- cycle: 'month',- });return (<PlanColumnkey={entry.key}@@ -158,7 +160,6 @@ export function PlanSelector({ enabled, onSelected }: PlanSelectorProps) {pricing={planSelectorUtils.computePricing({entry,apiPlan,- monthlySibling,})}currentPlanId={currentPlanId}hasScheduledChange={hasScheduledChange}@@ -234,14 +235,13 @@ function PlanColumn({const chargeAmount = isNil(apiPlan?.price)? apiPlan?.priceDisplay ?? '': `$${apiPlan.price.toLocaleString()}`;- const features = planSelectorUtils.resolveFeatures({ entry, apiPlan });const handleCtaCheckout = (planId: string, action: CheckoutAction) =>onCheckout({planId,action,- planName: t(entry.name),+ planName: entry.name,priceAmount: chargeAmount,- features: features.map((feature) => feature.label),+ features: entry.features.map((feature) => feature.label),});return (@@ -258,9 +258,9 @@ function PlanColumn({entry.highlighted && 'text-accent-11',)}>- {t(entry.name)}+ {entry.name}</h3>- <p className="text-sm text-gray-11">{t(entry.blurb)}</p>+ <p className="text-sm text-gray-11">{entry.blurb}</p></div><div className="flex min-h-[3.25rem] flex-col gap-1">@@ -271,19 +271,9 @@ function PlanColumn({{!isNil(pricing.suffix) && (<span className="text-sm text-gray-11">{pricing.suffix}</span>)}- {!isNil(pricing.freeMonths) && (- <Badge variant="accent" className="rounded-sm">- {t(- '{count, plural, =1 {1 free month} other {# free months}}',- {- count: pricing.freeMonths,- },- )}- </Badge>- )}</div>- {!isNil(pricing.annualNote) && (- <span className="text-xs text-gray-11">{pricing.annualNote}</span>+ {!isNil(pricing.note) && (+ <span className="text-xs text-gray-11">{pricing.note}</span>)}</>)}@@ -306,25 +296,28 @@ function PlanColumn({/><div className="flex flex-col gap-3">- <span className="text-sm font-medium">{t(entry.featuresHeader)}</span>+ <span className="text-sm font-medium">{entry.featuresHeader}</span><ul className="flex flex-col gap-2.5">- {features.map((feature) => (+ {[+ ...entry.features.slice(0, 1),+ ...planSelectorUtils.creditTopUpFeature(apiPlan),+ ...entry.features.slice(1),+ ].map((feature) => (<likey={feature.label}className="flex items-center gap-2 text-sm text-gray-12"><Check className="size-4 shrink-0 text-accent-11" />- <span className="flex-1">{t(feature.label)}</span>- {!isNil(feature.tooltip) && (- <Tooltip>- <TooltipTrigger asChild>- <Info className="size-3.5 shrink-0 text-gray-11" />- </TooltipTrigger>- <TooltipContent className="max-w-[220px]">- {t(feature.tooltip)}- </TooltipContent>- </Tooltip>- )}+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="cursor-help underline decoration-gray-9 decoration-dotted underline-offset-4">+ {feature.label}+ </span>+ </TooltipTrigger>+ <TooltipContent className="max-w-[220px]">+ {feature.tooltip}+ </TooltipContent>+ </Tooltip></li>))}</ul>diff --git a/packages/web/src/features/billing/components/plan-switch-success-dialog.tsx b/packages/web/src/features/billing/components/plan-switch-success-dialog.tsxindex 1bac964dd2a..c24109d6730 100644--- a/packages/web/src/features/billing/components/plan-switch-success-dialog.tsx+++ b/packages/web/src/features/billing/components/plan-switch-success-dialog.tsx@@ -4,10 +4,8 @@ import { Check } from 'lucide-react';import { Button } from '@/components/ui/button';import { Dialog, DialogContent } from '@/components/ui/dialog';-import { platformHooks } from '@/hooks/platform-hooks';-import { billingQueries } from '../hooks/billing-hooks';-import { usePlanSwitchSuccessDialogStore } from '../stores/plan-switch-success-dialog-state';+import { billingDialogHooks } from '../hooks/billing-dialog-hooks';import {planSelectorUtils,@@ -18,23 +16,14 @@ const HIGHLIGHT_COUNT = 3;function resolveEntry(planId: string): PlanCatalogEntry | undefined {const key = planId.replace(/_annual$/, '');- return planSelectorUtils.PLAN_CATALOG.find((entry) => entry.key === key);+ return planSelectorUtils.planCatalog().find((entry) => entry.key === key);}export function PlanSwitchSuccessDialog() {- const { payload: planId, closeDialog } = usePlanSwitchSuccessDialogStore();- const { platform } = platformHooks.useCurrentPlatform();- const { data: plans } = billingQueries.useListPlans(- platform.id,- !isNil(planId),- );+ const { planId, closeDialog } =+ billingDialogHooks.usePlanSwitchSuccessDialogStore();const entry = isNil(planId) ? undefined : resolveEntry(planId);- const features = isNil(entry)- ? []- : planSelectorUtils.resolveFeatures({- entry,- apiPlan: plans?.find((plan) => plan.id === planId),- });+ const features = entry?.features ?? [];return (<Dialog@@ -49,7 +38,7 @@ export function PlanSwitchSuccessDialog() {</span><div className="flex flex-col gap-2"><h2 className="text-xl font-semibold">- {t("You're on the {plan} plan", { plan: t(entry.name) })}+ {t("You're on the {plan} plan", { plan: entry.name })}</h2><p className="text-sm text-gray-11">{t('You now have access to {benefits}.', {@@ -59,7 +48,7 @@ export function PlanSwitchSuccessDialog() {}).format(features.slice(0, HIGHLIGHT_COUNT)- .map((feature) => t(feature.label)),+ .map((feature) => feature.label),),})}</p>diff --git a/packages/web/src/features/billing/hooks/billing-dialog-hooks.ts b/packages/web/src/features/billing/hooks/billing-dialog-hooks.tsnew file mode 100644index 00000000000..4b7beed79d1--- /dev/null+++ b/packages/web/src/features/billing/hooks/billing-dialog-hooks.ts@@ -0,0 +1,58 @@+import { create } from 'zustand';++import type { BillingCycle } from '../components/plan-selector-utils';++const useManagePlanDialogStore = create<ManagePlanDialogStore>((set) => ({+ isOpen: false,+ openDialog: () => set({ isOpen: true }),+ closeDialog: () => set({ isOpen: false }),+}));++const useConfirmPurchaseDialogStore = create<ConfirmPurchaseDialogStore>(+ (set) => ({+ purchase: null,+ openDialog: (purchase) => set({ purchase }),+ closeDialog: () => set({ purchase: null }),+ }),+);++const usePlanSwitchSuccessDialogStore = create<PlanSwitchSuccessDialogStore>(+ (set) => ({+ planId: null,+ openDialog: (planId) => set({ planId }),+ closeDialog: () => set({ planId: null }),+ }),+);++export const billingDialogHooks = {+ useManagePlanDialogStore,+ useConfirmPurchaseDialogStore,+ usePlanSwitchSuccessDialogStore,+};++type PlanPurchase = {+ planId: string;+ planName: string;+ priceAmount: string;+ billingCycle: BillingCycle;+ features: string[];+ successUrl: string;+};++type ManagePlanDialogStore = {+ isOpen: boolean;+ openDialog: () => void;+ closeDialog: () => void;+};++type ConfirmPurchaseDialogStore = {+ purchase: PlanPurchase | null;+ openDialog: (purchase: PlanPurchase) => void;+ closeDialog: () => void;+};++type PlanSwitchSuccessDialogStore = {+ planId: string | null;+ openDialog: (planId: string) => void;+ closeDialog: () => void;+};diff --git a/packages/web/src/features/billing/hooks/billing-hooks.ts b/packages/web/src/features/billing/hooks/billing-hooks.tsindex fe2afc132de..d50371c223c 100644--- a/packages/web/src/features/billing/hooks/billing-hooks.ts+++ b/packages/web/src/features/billing/hooks/billing-hooks.ts@@ -26,7 +26,8 @@ import { api } from '@/lib/api';import { platformBillingApi } from '../api/billing-plans-api';import { planSelectorUtils } from '../components/plan-selector-utils';-import { usePlanSwitchSuccessDialogStore } from '../stores/plan-switch-success-dialog-state';++import { billingDialogHooks } from './billing-dialog-hooks';export const PLATFORM_BILLING_SUBSCRIPTION_KEY = ['platform-billing-subscription',@@ -60,7 +61,9 @@ export const billingMutations = {window.open(checkoutUrl, '_blank');} else {refreshBillingCaches(queryClient);- usePlanSwitchSuccessDialogStore.getState().openDialog(planId);+ billingDialogHooks.usePlanSwitchSuccessDialogStore+ .getState()+ .openDialog(planId);}onDone?.();},diff --git a/packages/web/src/features/billing/hooks/use-seat-limit-guard.tsx b/packages/web/src/features/billing/hooks/use-seat-limit-guard.tsxindex 8d95d317913..38249ead1d2 100644--- a/packages/web/src/features/billing/hooks/use-seat-limit-guard.tsx+++ b/packages/web/src/features/billing/hooks/use-seat-limit-guard.tsx@@ -16,8 +16,8 @@ import { platformHooks } from '@/hooks/platform-hooks';import { api } from '@/lib/api';import { OutOfSeatsDialog } from '../components/feature-usage/out-of-seats-dialog';-import { useManagePlanDialogStore } from '../stores/manage-plan-dialog-state';+import { billingDialogHooks } from './billing-dialog-hooks';import { billingQueries } from './billing-hooks';export const useSeatLimitGuard = () => {@@ -29,7 +29,7 @@ export const useSeatLimitGuard = () => {platform.id,isPlatformAdmin,);- const { openDialog } = useManagePlanDialogStore();+ const { openDialog } = billingDialogHooks.useManagePlanDialogStore();const seatFeature = info?.seatsFeature;const openSeatLimit = () => {diff --git a/packages/web/src/features/billing/hooks/use-upgrade-click.ts b/packages/web/src/features/billing/hooks/use-upgrade-click.tsindex 2f76534fed7..0f9fd832874 100644--- a/packages/web/src/features/billing/hooks/use-upgrade-click.ts+++ b/packages/web/src/features/billing/hooks/use-upgrade-click.ts@@ -3,12 +3,13 @@ import { PlatformAdminSurface, TelemetryEventName } from '@activepieces/shared';import { useTelemetry } from '@/components/providers/telemetry-provider';import { FeatureKey } from '../components/request-trial';-import { useManagePlanDialogStore } from '../stores/manage-plan-dialog-state';import { FeatureTier } from '../utils/feature-tier';+import { billingDialogHooks } from './billing-dialog-hooks';+export function useUpgradeClick() {const { capture } = useTelemetry();- const { openDialog } = useManagePlanDialogStore();+ const { openDialog } = billingDialogHooks.useManagePlanDialogStore();return ({ feature, tier, surface }: UpgradeClickParams) => {capture({diff --git a/packages/web/src/features/billing/index.ts b/packages/web/src/features/billing/index.tsindex 2054d8a884c..4fbbdec1448 100644--- a/packages/web/src/features/billing/index.ts+++ b/packages/web/src/features/billing/index.ts@@ -28,7 +28,7 @@ export {DROP_TO_FREE_WARNING,planSelectorUtils,} from './components/plan-selector-utils';-export { useManagePlanDialogStore } from './stores/manage-plan-dialog-state';+export { billingDialogHooks } from './hooks/billing-dialog-hooks';export { AutomaticTrialActivation } from './components/automatic-trial-activation';export { useFeatureGate, UpgradeFeatureDialog } from './hooks/use-feature-gate';export { useUpgradeClick } from './hooks/use-upgrade-click';diff --git a/packages/web/src/features/billing/stores/confirm-purchase-dialog-state.ts b/packages/web/src/features/billing/stores/confirm-purchase-dialog-state.tsdeleted file mode 100644index 3b389c24ee5..00000000000--- a/packages/web/src/features/billing/stores/confirm-purchase-dialog-state.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { BillingCycle } from '../components/plan-selector-utils';--import { createPayloadDialogStore } from './create-dialog-store';--export const useConfirmPurchaseDialogStore =- createPayloadDialogStore<ConfirmPurchasePayload>();--export type ConfirmPurchasePayload = {- planId: string;- planName: string;- priceAmount: string;- billingCycle: BillingCycle;- features: string[];- successUrl: string;-};diff --git a/packages/web/src/features/billing/stores/create-dialog-store.ts b/packages/web/src/features/billing/stores/create-dialog-store.tsdeleted file mode 100644index 20dc95deb8c..00000000000--- a/packages/web/src/features/billing/stores/create-dialog-store.ts+++ /dev/null@@ -1,29 +0,0 @@-import { create } from 'zustand';--export function createToggleDialogStore() {- return create<ToggleDialogStore>((set) => ({- isOpen: false,- openDialog: () => set({ isOpen: true }),- closeDialog: () => set({ isOpen: false }),- }));-}--export function createPayloadDialogStore<TPayload>() {- return create<PayloadDialogStore<TPayload>>((set) => ({- payload: null,- openDialog: (payload) => set({ payload }),- closeDialog: () => set({ payload: null }),- }));-}--export type ToggleDialogStore = {- isOpen: boolean;- openDialog: () => void;- closeDialog: () => void;-};--export type PayloadDialogStore<TPayload> = {- payload: TPayload | null;- openDialog: (payload: TPayload) => void;- closeDialog: () => void;-};diff --git a/packages/web/src/features/billing/stores/manage-plan-dialog-state.ts b/packages/web/src/features/billing/stores/manage-plan-dialog-state.tsdeleted file mode 100644index d131f0e952d..00000000000--- a/packages/web/src/features/billing/stores/manage-plan-dialog-state.ts+++ /dev/null@@ -1,3 +0,0 @@-import { createToggleDialogStore } from './create-dialog-store';--export const useManagePlanDialogStore = createToggleDialogStore();diff --git a/packages/web/src/features/billing/stores/plan-switch-success-dialog-state.ts b/packages/web/src/features/billing/stores/plan-switch-success-dialog-state.tsdeleted file mode 100644index 8347e9bdd02..00000000000--- a/packages/web/src/features/billing/stores/plan-switch-success-dialog-state.ts+++ /dev/null@@ -1,4 +0,0 @@-import { createPayloadDialogStore } from './create-dialog-store';--export const usePlanSwitchSuccessDialogStore =- createPayloadDialogStore<string>();diff --git a/packages/web/src/features/billing/utils/billing-utils.ts b/packages/web/src/features/billing/utils/billing-utils.tsindex 1ab94df899d..806e30d8952 100644--- a/packages/web/src/features/billing/utils/billing-utils.ts+++ b/packages/web/src/features/billing/utils/billing-utils.ts@@ -45,7 +45,7 @@ function creditsSeverity(percent: number): CreditsSeverity {}function formatCredits(credits: number): string {- const wholeCredits = Math.round(credits);+ const wholeCredits = Math.floor(credits);return wholeCredits >= COMPACT_CREDITS_FROM? formatUtils.formatNumberCompact(wholeCredits): formatUtils.formatNumber(wholeCredits);diff --git a/packages/web/src/features/flow-runs/hooks/flow-run-hooks.ts b/packages/web/src/features/flow-runs/hooks/flow-run-hooks.tsindex 239965c7f2c..d5815ce5bab 100644--- a/packages/web/src/features/flow-runs/hooks/flow-run-hooks.ts+++ b/packages/web/src/features/flow-runs/hooks/flow-run-hooks.ts@@ -17,7 +17,7 @@ import { toast } from 'sonner';import { getDefaultRange } from '@/components/custom/date-time-picker-range';import { internalErrorToast } from '@/components/ui/sonner';-import { useManagePlanDialogStore } from '@/features/billing';+import { billingDialogHooks } from '@/features/billing';import { flowsApi } from '@/features/flows/api/flows-api';import { api } from '@/lib/api';import { authenticationSession } from '@/lib/authentication-session';@@ -160,7 +160,7 @@ export const flowRunMutations = {dismissible: true,});} else if (apError.code === ErrorCode.QUOTA_EXCEEDED) {- useManagePlanDialogStore.getState().openDialog();+ billingDialogHooks.useManagePlanDialogStore.getState().openDialog();}return;}diff --git a/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.ts b/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.tsindex e551ce2badd..4a4cb13e92a 100644--- a/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/ai-provider-hooks.ts@@ -82,10 +82,19 @@ export const aiProviderMutations = {onSuccess,});},- useDeleteAiProvider: ({ onSuccess }: { onSuccess: () => void }) => {+ useDeleteAiProvider: ({+ onSuccess,+ onError,+ }: {+ onSuccess: () => void;+ onError?: (+ error: AxiosError<{ message?: string; params?: { message: string } }>,+ ) => void;+ }) => {return useMutation({mutationFn: (providerId: string) => aiProviderApi.delete(providerId),onSuccess,+ onError,});},useUpdateAiProvider: ({diff --git a/packages/web/test/app/billing/feature-gating.test.tsx b/packages/web/test/app/billing/feature-gating.test.tsxindex 0481637c8b8..e39682de097 100644--- a/packages/web/test/app/billing/feature-gating.test.tsx+++ b/packages/web/test/app/billing/feature-gating.test.tsx@@ -9,6 +9,7 @@ import * as React from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';let teamProjectsLimit: number | null = 0;+let aiProvidersEnabled = false;let edition = 'cloud';const createProject = vi.fn();@@ -27,6 +28,7 @@ vi.mock('@/hooks/platform-hooks', () => ({plan: {billedTeamProjectsLimit: teamProjectsLimit,globalConnectionsEnabled: false,+ aiProvidersEnabled,},},}),@@ -47,12 +49,16 @@ vi.mock('@/hooks/flags-hooks', () => ({useFlags: () => ({ data: {} }),},}));-vi.mock('@/features/billing/stores/manage-plan-dialog-state', () => ({- useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+vi.mock('@/features/billing/hooks/billing-dialog-hooks', () => ({+ billingDialogHooks: {+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+ },}));vi.mock('@/features/billing', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+ billingDialogHooks: {+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+ },}));vi.mock('@/features/connections', () => ({globalConnectionsQueries: {@@ -96,6 +102,7 @@ vi.mock('@/components/ui/sidebar-shadcn', () => ({import { FeatureSample } from '@/app/components/feature-sample';import { FeatureTeaser } from '@/app/components/feature-teaser';+import { PlanFeatureSample } from '@/app/routes/platform/plan-feature-sample';import { CreateProjectButton } from '@/features/projects/components/create-project-button';const LIMIT_REACHED_COPY = "You've reached your team project limit";@@ -118,6 +125,7 @@ const usedTeamProjects = (count: number) =>beforeEach(() => {teamProjectsLimit = 0;+ aiProvidersEnabled = false;edition = 'cloud';createProject.mockClear();});@@ -265,3 +273,34 @@ describe('feature sample', () => {expect(screen.queryByRole('button', { name: /contact sales/i })).toBeNull();});});++describe('AI providers plan lock', () => {+ it('locks the providers page when the plan lacks aiProvidersEnabled', () => {+ render(+ <PlanFeatureSample feature="aiProviders">+ <h1>AI Center providers</h1>+ </PlanFeatureSample>,+ );+ expect(+ screen.getByRole('heading', { name: 'Unlock AI Center' }),+ ).toBeDefined();+ expect(+ screen.queryByRole('heading', { name: 'AI Center providers' }),+ ).toBeNull();+ });++ it('renders the providers page untouched when aiProvidersEnabled is on', () => {+ aiProvidersEnabled = true;+ render(+ <PlanFeatureSample feature="aiProviders">+ <h1>AI Center providers</h1>+ </PlanFeatureSample>,+ );+ expect(+ screen.getByRole('heading', { name: 'AI Center providers' }),+ ).toBeDefined();+ expect(+ screen.queryByRole('heading', { name: 'Unlock AI Center' }),+ ).toBeNull();+ });+});diff --git a/packages/web/test/app/components/sidebar/platform/index.test.tsx b/packages/web/test/app/components/sidebar/platform/index.test.tsxnew file mode 100644index 00000000000..a78cbd8f868--- /dev/null+++ b/packages/web/test/app/components/sidebar/platform/index.test.tsx@@ -0,0 +1,101 @@+/**+ * @vitest-environment jsdom+ */+import { render, screen } from '@testing-library/react';+import * as React from 'react';+import { MemoryRouter } from 'react-router-dom';+import { describe, expect, it, vi } from 'vitest';++import { PlatformSidebar } from '@/app/components/sidebar/platform';++const plan = vi.hoisted(() => ({ aiProvidersEnabled: false }));++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('@/hooks/platform-hooks', () => ({+ platformHooks: {+ useCurrentPlatform: () => ({ platform: { plan } }),+ },+}));++vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: {+ useFlag: () => ({ data: 'cloud' }),+ },+}));++vi.mock('@/hooks/authorization-hooks', () => ({+ useAuthorization: () => ({ checkAccess: () => true }),+}));++vi.mock('@/lib/route-utils', () => ({+ determineDefaultRoute: () => '/',+}));++vi.mock('@/components/ui/scroll-area', () => ({+ ScrollArea: ({ children }: React.PropsWithChildren) => <>{children}</>,+}));++vi.mock('@/components/ui/sidebar-shadcn', () => {+ const Passthrough = ({ children }: React.PropsWithChildren) => (+ <>{children}</>+ );+ return {+ Sidebar: Passthrough,+ SidebarContent: Passthrough,+ SidebarFooter: Passthrough,+ SidebarMenu: Passthrough,+ SidebarHeader: Passthrough,+ SidebarGroup: Passthrough,+ SidebarGroupContent: Passthrough,+ SidebarGroupLabel: Passthrough,+ };+});++vi.mock('@/app/components/sidebar/sidebar-user', () => ({+ SidebarUser: () => null,+}));++vi.mock('@/app/components/sidebar/ap-sidebar-item', () => ({+ ApSidebarItem: ({+ label,+ subItems,+ }: {+ label: string;+ subItems?: { label: string; locked?: boolean }[];+ }) => (+ <ul aria-label={label}>+ {(subItems ?? []).map((subItem) => (+ <li+ key={subItem.label}+ aria-label={+ subItem.locked ? `${subItem.label} locked` : subItem.label+ }+ />+ ))}+ </ul>+ ),+}));++function renderSidebar() {+ render(+ <MemoryRouter>+ <PlatformSidebar />+ </MemoryRouter>,+ );+}++describe('platform sidebar AI Center', () => {+ it('leaves Providers unlocked when aiProvidersEnabled is on', () => {+ plan.aiProvidersEnabled = true;++ renderSidebar();++ expect(screen.queryAllByRole('listitem', { name: 'Providers' })).toEqual([+ expect.any(HTMLLIElement),+ ]);+ expect(+ screen.queryAllByRole('listitem', { name: 'Providers locked' }),+ ).toEqual([]);+ });+});diff --git a/packages/web/test/app/platform/admin-control-clicks.test.tsx b/packages/web/test/app/platform/admin-control-clicks.test.tsxindex 694a41ec662..0345fca1e3e 100644--- a/packages/web/test/app/platform/admin-control-clicks.test.tsx+++ b/packages/web/test/app/platform/admin-control-clicks.test.tsx@@ -25,8 +25,10 @@ vi.mock('@/hooks/platform-hooks', () => ({vi.mock('@/hooks/flags-hooks', () => ({flagsHooks: { useFlag: () => ({ data: ApEdition.CLOUD }) },}));-vi.mock('@/features/billing/stores/manage-plan-dialog-state', () => ({- useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+vi.mock('@/features/billing/hooks/billing-dialog-hooks', () => ({+ billingDialogHooks: {+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+ },}));vi.mock('@/app/components/platform-layout', () => ({PlatformLayout: ({ children }: React.PropsWithChildren) => <>{children}</>,diff --git a/packages/web/test/app/platform/admin-page-view.test.tsx b/packages/web/test/app/platform/admin-page-view.test.tsxindex b606881d63c..de07cd95f45 100644--- a/packages/web/test/app/platform/admin-page-view.test.tsx+++ b/packages/web/test/app/platform/admin-page-view.test.tsx@@ -25,8 +25,10 @@ vi.mock('@/hooks/platform-hooks', () => ({vi.mock('@/hooks/flags-hooks', () => ({flagsHooks: { useFlag: () => ({ data: ApEdition.CLOUD }) },}));-vi.mock('@/features/billing/stores/manage-plan-dialog-state', () => ({- useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+vi.mock('@/features/billing/hooks/billing-dialog-hooks', () => ({+ billingDialogHooks: {+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+ },}));vi.mock('@/app/components/platform-layout', () => ({PlatformLayout: ({ children }: React.PropsWithChildren) => <>{children}</>,diff --git a/packages/web/test/app/platform/admin-telemetry.test.tsx b/packages/web/test/app/platform/admin-telemetry.test.tsxindex c9f7940fbc7..118a1e4573e 100644--- a/packages/web/test/app/platform/admin-telemetry.test.tsx+++ b/packages/web/test/app/platform/admin-telemetry.test.tsx@@ -50,8 +50,10 @@ vi.mock('@/hooks/flags-hooks', () => ({useFlags: () => ({ data: {} }),},}));-vi.mock('@/features/billing/stores/manage-plan-dialog-state', () => ({- useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+vi.mock('@/features/billing/hooks/billing-dialog-hooks', () => ({+ billingDialogHooks: {+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+ },}));vi.mock('@/features/connections', () => ({globalConnectionsQueries: {diff --git a/packages/web/test/app/routes/platform-routes.test.tsx b/packages/web/test/app/routes/platform-routes.test.tsxnew file mode 100644index 00000000000..54014f2970e--- /dev/null+++ b/packages/web/test/app/routes/platform-routes.test.tsx@@ -0,0 +1,81 @@+/**+ * @vitest-environment jsdom+ */+import { render, screen } from '@testing-library/react';+import * as React from 'react';+import { MemoryRouter } from 'react-router-dom';+import { describe, expect, it, vi } from 'vitest';++import { platformRoutes } from '@/app/routes/platform-routes';++const plan = vi.hoisted(() => ({ aiProvidersEnabled: false }));++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('@/hooks/platform-hooks', () => ({+ platformHooks: {+ useCurrentPlatform: () => ({ platform: { plan } }),+ },+}));++vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: {+ useFlag: () => ({ data: 'cloud' }),+ },+}));++vi.mock('@/features/billing', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ billingDialogHooks: {+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+ },+}));++vi.mock('@/app/components/platform-layout', () => ({+ PlatformLayout: ({ children }: React.PropsWithChildren) => <>{children}</>,+}));++vi.mock('@/app/components/page-title', () => ({+ PageTitle: ({ children }: React.PropsWithChildren) => <>{children}</>,+}));++vi.mock('@/app/routes/platform/setup/ai', () => ({+ default: () => <h1>AI Center providers</h1>,+}));++function renderAiCenterRoute() {+ const route = platformRoutes.find(({ path }) => path === '/platform/ai');+ render(+ <MemoryRouter initialEntries={['/platform/ai']}>+ {route?.element}+ </MemoryRouter>,+ );+}++describe('/platform/ai route', () => {+ it('leaves the plan lock to the providers tab when the plan lacks aiProvidersEnabled', async () => {+ plan.aiProvidersEnabled = false;++ renderAiCenterRoute();++ expect(+ await screen.findAllByRole('heading', { name: 'AI Center providers' }),+ ).toEqual([expect.any(HTMLHeadingElement)]);+ expect(+ screen.queryAllByRole('heading', { name: 'Unlock AI Center' }),+ ).toEqual([]);+ });++ it('opens the providers page when aiProvidersEnabled is on', async () => {+ plan.aiProvidersEnabled = true;++ renderAiCenterRoute();++ expect(+ await screen.findAllByRole('heading', { name: 'AI Center providers' }),+ ).toEqual([expect.any(HTMLHeadingElement)]);+ expect(+ screen.queryAllByRole('heading', { name: 'Unlock AI Center' }),+ ).toEqual([]);+ });+});diff --git a/packages/web/test/app/routes/platform/setup/ai/providers-tab-locked.test.tsx b/packages/web/test/app/routes/platform/setup/ai/providers-tab-locked.test.tsxnew file mode 100644index 00000000000..17df16822cc--- /dev/null+++ b/packages/web/test/app/routes/platform/setup/ai/providers-tab-locked.test.tsx@@ -0,0 +1,188 @@+/**+ * @vitest-environment jsdom+ */+import { render, screen } from '@testing-library/react';+import * as React from 'react';+import { MemoryRouter } from 'react-router-dom';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ProvidersTab } from '@/app/routes/platform/setup/ai/providers-tab';++const state = vi.hoisted(() => ({+ aiProvidersEnabled: false,+ providers: [] as Record<string, unknown>[],+}));++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('@tanstack/react-query', () => ({+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),+}));++vi.mock('@/hooks/platform-hooks', () => ({+ platformHooks: {+ useCurrentPlatform: () => ({+ platform: { plan: { aiProvidersEnabled: state.aiProvidersEnabled } },+ }),+ },+}));++vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: { useFlag: () => ({ data: 'cloud' }) },+}));++vi.mock('@/features/billing', () => ({+ PLATFORM_FEATURES: {+ aiProviders: {+ featureKey: 'UNIVERSAL_AI',+ title: 'Unlock AI Center',+ description: 'description',+ tier: 'plus',+ },+ },+ TIER_LABELS: { plus: 'Plus' },+ useUpgradeClick: () => vi.fn(),+ RequestTrial: () => null,+}));++vi.mock('@/features/platform-admin', () => {+ const mutation = () => ({+ mutate: vi.fn(),+ mutateAsync: vi.fn(),+ isPending: false,+ });+ return {+ aiProviderKeys: { configModels: () => [] },+ aiProviderQueries: {+ useAiProviderConfigs: () => ({+ data: state.providers,+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ }),+ },+ aiProviderMutations: {+ useToggleChatProvider: mutation,+ useDeleteAiProvider: mutation,+ useRecheckAiProvider: mutation,+ useUpdateAiProvider: mutation,+ },+ };+});++vi.mock('@/features/projects', () => ({+ projectCollectionUtils: { useAllPlatformProjects: () => ({ data: [] }) },+}));++vi.mock('@/features/agents', () => ({+ SUPPORTED_AI_PROVIDERS: [+ { provider: 'anthropic', name: 'Anthropic', markdown: '', logoUrl: '' },+ ],+}));++vi.mock('@/components/ui/tooltip', () => ({+ Tooltip: ({ children }: React.PropsWithChildren) => <>{children}</>,+ TooltipTrigger: ({ children }: React.PropsWithChildren) => <>{children}</>,+ TooltipContent: () => null,+}));++vi.mock('@/components/custom/delete-dialog', () => ({+ ConfirmationDeleteDialog: () => null,+}));++vi.mock(+ '@/app/routes/platform/setup/ai/providers-tab/connect-provider-dialog',+ () => ({ ConnectProviderDialog: () => null }),+);++vi.mock('@/app/routes/platform/setup/ai/providers-tab/config-detail', () => ({+ ConfigDetail: () => <h1>Key detail</h1>,+}));++function renderTab(path = '/platform/ai') {+ render(+ <MemoryRouter initialEntries={[path]}>+ <ProvidersTab />+ </MemoryRouter>,+ );+}++const ANTHROPIC_KEY = {+ id: 'key-1',+ provider: 'anthropic',+ name: 'Trial Anthropic key',+ enabledForChat: true,+ status: 'active',+ modelScope: 'all',+ modelIds: [],+ projectScope: 'all',+ projectIds: [],+ config: {},+};++beforeEach(() => {+ state.aiProvidersEnabled = false;+ state.providers = [];+});++describe('providers tab on a plan without aiProvidersEnabled', () => {+ it('lists existing keys with delete only and an upgrade note', () => {+ state.providers = [ANTHROPIC_KEY];++ renderTab();++ expect(+ screen.getByText('Your plan does not include Bring your own AI keys'),+ ).toBeDefined();+ expect(screen.getAllByText('Trial Anthropic key').length).toBeGreaterThan(+ 0,+ );+ expect(screen.queryAllByRole('combobox')).toEqual([]);+ expect(screen.getByRole('button', { name: 'Delete' })).toBeDefined();+ expect(screen.queryAllByRole('button', { name: /Add key/ })).toEqual([]);+ expect(screen.queryAllByRole('button', { name: /Trial Anthropic/ })).toEqual(+ [],+ );+ expect(screen.queryAllByText('Also available')).toEqual([]);+ });++ it('does not open the key detail from a deep link', () => {+ state.providers = [ANTHROPIC_KEY];++ renderTab('/platform/ai?config=key-1');++ expect(screen.queryAllByRole('heading', { name: 'Key detail' })).toEqual(+ [],+ );+ });++ it('shows the upgrade sample when there is nothing to delete', () => {+ renderTab();++ expect(+ screen.getByRole('heading', { name: 'Unlock AI Center' }),+ ).toBeDefined();+ expect(+ screen.queryAllByText('Your plan does not include Bring your own AI keys'),+ ).toEqual([]);+ });+});++describe('providers tab on a plan with aiProvidersEnabled', () => {+ it('keeps add, open and connect actions', () => {+ state.aiProvidersEnabled = true;+ state.providers = [ANTHROPIC_KEY];++ renderTab();++ expect(+ screen.getAllByRole('button', { name: /Add key/ }).length,+ ).toBeGreaterThan(0);+ expect(+ screen.queryAllByText('Your plan does not include Bring your own AI keys'),+ ).toEqual([]);+ expect(+ screen.queryAllByRole('heading', { name: 'Unlock AI Center' }),+ ).toEqual([]);+ });+});diff --git a/packages/web/test/features/billing/billing-utils.test.ts b/packages/web/test/features/billing/billing-utils.test.tsindex 58d960d21f8..24baadbba81 100644--- a/packages/web/test/features/billing/billing-utils.test.ts+++ b/packages/web/test/features/billing/billing-utils.test.ts@@ -63,16 +63,16 @@ describe('billingUtils.formatCredits', () => {);});- it('rounds a fractional credit count to a whole credit', () => {+ it('rounds a fractional credit count down to a whole credit', () => {expect(billingUtils.formatCredits(838.822)).toBe(- formatUtils.formatNumber(839),+ formatUtils.formatNumber(838),);- expect(billingUtils.formatCredits(0.4)).toBe(formatUtils.formatNumber(0));+ expect(billingUtils.formatCredits(0.9)).toBe(formatUtils.formatNumber(0));});- it('rounds before choosing compact notation', () => {+ it('rounds down before choosing compact notation', () => {expect(billingUtils.formatCredits(999_999.6)).toBe(- formatUtils.formatNumberCompact(1_000_000),+ formatUtils.formatNumber(999_999),);});});