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
feat(web): gate paid features at the action instead of the page (#15562)
Ahmad Tashf653e029a18a
diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.mdindex 00a16b5ebce..e8a0e431fc7 100644--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md@@ -48,6 +48,7 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def- **`@activepieces/shared` re-exports from `@activepieces/core-execution`, so a partial rebuild produces phantom "has no exported member" errors in unrelated files.** Rebuilding `core/shared` against a stale `core/execution` dist drops those re-exports, and the API typecheck then fails in `ee/agent/*` on symbols like `GetPersonalizationConfigRequest` — which live in `core/execution/src/lib/workers/worker-contract.ts`, not in shared at all. It reads exactly like a bad merge. The dependency order that actually works is `core/utils` → `core/piece-types` → `core/formula` → `core/execution` → `core/shared` → `server/utils` → `pieces/framework` → `core/ai-providers`; skipping a link silently poisons everything downstream of it. The same staleness makes an editor report missing enum members that exist in the source. **There is no api typecheck "error baseline" — rebuild first, then trust it.** A stale `core/shared/dist` reliably yields a handful of `ee/agent` errors that look permanent enough to be waved off as known, which is how a real error hides among them; after `npx turbo run build --filter=@activepieces/shared`, `tsc --noEmit -p packages/server/api/tsconfig.app.json` comes back completely clean. The same staleness invents errors in files a rebase just touched, so during a conflict resolution rebuild before concluding you resolved it wrong.- **To pull a file back out of a PR, restore it from the merge-base, never from `origin/main`.** A PR's diff is computed against the merge-base, so `git checkout origin/main -- <file>` does not "revert" the file — it imports every change `main` made to it since the fork and attributes them to you. Dropping one web file from [#15001](https://github.com/activepieces/activepieces/pull/15001) that way would have silently added 82 insertions / 44 deletions of somebody else's work. `git checkout $(git merge-base origin/main HEAD) -- <file>` makes it byte-identical to where the branch started, so it leaves the diff entirely and merges cleanly instead of conflicting. Verify with `git diff --quiet $(git merge-base origin/main HEAD) -- <file>` before committing, and read `git status` first — a `bun.lock` left dirty by an earlier `bun install` loves to ride along on a commit like this.- **Retargeting a stacked PR to `main` does not drop its base branch — it merges the whole thing.** A PR opened against a long-lived feature branch shows a small diff *relative to that base*, but `gh pr edit --base main` only moves the target; the branch still contains every commit of its old base. [#14593](https://github.com/activepieces/activepieces/pull/14593) read as 2 docs files against `feat/autumn-billing-integration` and as 198 commits / 211 files / +12k lines against `main`. Check with `git diff --stat origin/main...<branch>` **before** retargeting, and if it disagrees with the PR page, cherry-pick that PR's own commits onto `main` and force-push instead. A "conflict" on such a PR is often against the feature base only — those same commits can apply to `main` cleanly.+- **Each link of a stack runs CI against its own base, so verifying the top proves nothing about the ones below it.** A refactor that lands on the bottom branch and is repaired two branches up is green where you tested and red on the PR that actually carries it, and the failure reads as unrelated because the file it names was fine when you last looked at it. Before pushing a stack, check out each branch in turn and run the package's typecheck, lint and full test suite there, not just at the tip; the suites legitimately differ (this stack's tip runs two more web tests than its base). Do the same after any rebase, since a conflict resolved in one replay can leave a lower branch importing something only a higher one defines.- **A deliberately stacked PR is charged only for its own delta, but each link pays its own `@activepieces/shared` bump.** `pr-size-check.ts` diffs `HEAD^1...HEAD^2` on the `pull_request` merge commit precisely so an ancestor PR is not re-counted — a stack member measures the same whether reviewed against `main` or against the PR below it, so splitting a large change into a stack really does buy budget rather than just moving it. Two things the split still costs you. Every PR in the stack that touches `packages/core/shared` needs its **own** version increment (0.158.0 then 0.159.0, not the same bump twice), and `bun.lock` records each workspace's version, so edit that one line **by hand** in each — regenerating sweeps `main`'s pending drift into your diff, per the regenerator trap above. And prove the split is faithful before pushing: tag the pre-split commit, then `git diff <tag>..<stack tip>` must come back empty apart from those intentional version lines. A file that lands partially in one PR and grows in the next (a service that gains its read side, a test file that gains its endpoint cases) is exactly where a hand-split silently drops a hunk.- **A migration-check failure in a stack names the PR that *introduced* the file, which is usually not the branch you are sitting on.** `check-migration-rollback.ts` lists candidates with `git diff --name-only --diff-filter=A origin/$GITHUB_BASE_REF...HEAD`, so a migration is only ever scanned on the stack member that **adds** it; every branch above inherits the file and its CI stays green on that check. So the pasted failure belongs to the lowest link, and editing the file on the tip you happen to have checked out fixes nothing the gate looks at. Confirm ownership before touching anything — `gh pr view <n> --json headRefName` for the branch the number really points at, then `git cat-file -e <branch>:<path>` across the stack for the first branch holding the file — fix it there, and rebase upward. Two things make that cheap: the file is usually byte-identical across the stack (`git diff <lower> <upper> -- <path>` comes back empty), and `git rebase` reports `skipped previously applied commit` for the lower branch's pre-rebase commits, which is the expected signal rather than a lost commit. Verify each link the same way the split rule above does — tag the old tip, then `git diff <tag> <rebased branch>` must show only the intended delta. Hit on PR 15240 (`feat/mcp-activity-recording`) while its own migration read as a failure on `feat/mcp-activity-serve` two links up.- **A decision authored on a long-lived branch will collide on its number.** `brain/decisions/` numbers are assigned once and never reused, but the next free number is only knowable against `main` — two branches in flight both grab it. #14593 carried a `000024` that `main` had since filled, and `000025` too, so it landed as `000026`. Renumber against `main` at merge time and update every referring link; nothing in CI catches a duplicate number or a dead decision link.@@ -75,3 +76,5 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def- **Merging up a stacked chain, a parent's rename reaches a child's call sites as a clean auto-merge — only the typecheck finds it.** Git conflicts on lines both sides edited, so a symbol renamed on the parent merges silently into a child that merely *calls* the old name: `feat/barrier-service` renamed `barrierService.receive` → `receiveSignal`, and `feat/barrier-edges`' `resume-controller.ts` kept calling `.receive(...)` with no conflict marker. Worse, both sides can each be right and still merge wrong — the same commit renamed `findPreCompletedByFlowRunId` while the child had rewritten that function's *body* to fix a real bug, so the conflict exposed only the signature and taking either side whole silently dropped work. Two habits: typecheck **every** branch in the chain after its merge rather than trusting a conflict-free result, and before picking a side run `git log --oneline $(git merge-base HEAD MERGE_HEAD)..HEAD -- <file>` on both to read what each side was actually doing. Stacks here run deep (the waitpoints → process-in-batches chain was 17 PRs), so one missed rename propagates through every branch above it.- **Docs videos belong on `cdn.activepieces.com/videos/docs/`, never in the repo — and `docs/resources/` is the legacy path that suggests otherwise.** Every `<video>` already in the wiki points at that CDN prefix, but `docs/resources/` still holds ~43 MB of in-repo gifs from before the convention, so the tree itself gives mixed signals and a contributor reasonably copies the wrong one. [#15399](https://github.com/activepieces/activepieces/pull/15399) added a fresh `docs/videos/` folder with 155 MB of `.mp4` against an 880 MB `.git`, including one byte-identical duplicate. Nothing in CI catches it: `PR size` exempts unmatched areas and counts lines, not bytes, and a binary blob contributes zero lines. Review the *file list* of a docs PR, not just its diff. Once such a branch is pushed the blobs are already on the remote — dropping them at the tip only keeps them out of `main` if the PR is **squash**-merged and the branch deleted, so a merge commit ships them permanently. Because the blobs stay reachable until the branch is deleted, nobody has to re-request the assets from whoever recorded them — pull them straight back out of history with `git archive <commit> docs/videos | tar -x --strip-components=2 -C <dir>`, picking the commit *before* the removal, which is also how you get them under the post-rename filenames the pages already reference.- **Mintlify-editor PRs arrive with `untitled-page*.mdx` at the docs root and `(1)`/`(2)`-suffixed media, wired into `docs.json` under those names.** The bot commits whatever the web editor autosaved, so pages land as `docs/untitled-page-5.mdx` rather than in the folder their nav group implies, and re-uploaded assets keep the browser's download-collision suffix (`data-flow-(1).mp4`, `01---insert-panel-(1.2x).mp4`). Mintlify's own link check passes — the names are internally consistent — so nothing flags it. Rename the files, fix the `docs.json` entries, then diff the *flattened nav tree* against `main` rather than reading the raw JSON diff: the editor also reindents, which buried a real change (the Enterprise Control `Security` group demoted to a child of `Guides`) inside 242 lines of whitespace churn on that PR.+- **After rewriting a lower branch of a stack, the `--onto` upstream you need is that branch's *old* tip, and `<branch>@{1}` is where to read it.** Every commit above a rewritten branch has to be replayed with `git rebase --onto <new lower tip> <old lower tip> <upper>`, and the old tip stops being reachable by name the moment the rebase finishes. Guessing a SHA from an earlier terminal scroll either fails outright with `invalid upstream` or, worse, succeeds against the wrong base and replays a handful of commits instead of all of them, which surfaces as a pile of conflicts the branch has with itself. `git rev-parse <branch>@{1}` reads it from the reflog every time. Re-run the whole `--onto` chain top-down after any lower-branch amend, and confirm afterwards that `git log --format=%s main..<top>` has no duplicate subjects.+- **Never commit a shared file onto a lower branch of a stack by copying it in from the stack top — you drag the upper branches' edits down with it.** Adding one gotcha bullet to a brain page while sitting on the top branch, then `git checkout <stash-or-top> -- <file>` after switching to the base branch, brings the *whole* file across, so every bullet the upper branches added to that page is silently duplicated onto the base. The commit stat is the tell: a one-line edit that reports six insertions is not a one-line edit. Switch branches first, re-apply the edit against **that branch's own copy** of the file, and re-check the stat before committing.diff --git a/brain/knowledge/engineering/web-feature-anatomy.md b/brain/knowledge/engineering/web-feature-anatomy.mdindex 99e41456eee..3067340f59c 100644--- a/brain/knowledge/engineering/web-feature-anatomy.md+++ b/brain/knowledge/engineering/web-feature-anatomy.md@@ -62,6 +62,12 @@ Every customer-facing surface must be checked on all five edition paths — CE,A default local dev instance runs `edition=ce` (check `/api/v1/flags`), and most of the platform-admin surface is unreachable there — Global Connections, Pieces, Templates, Billing, Usage, Embedding, SSO, Project Roles, API Keys, Secret Managers, Audit Logs and Event Streaming all render `LockedFeatureGuard` instead of their body, and the AI Center's Capabilities tab is not rendered at all. So a change to any of those cannot be seen locally without first flipping the `platform_plan` flags in the dev Postgres; Embedding needs more than that, since `useEmbedSubdomain` is gated on `edition === CLOUD` and so needs `AP_EDITION=cloud` and a restart. Plan for that before promising a screenshot of a gated page.+Running one frontend per edition side by side (a vite port each against its own backend) is the quickest+way to check all of them, but **every port serves the same working tree**, so checking out another branch+changes the code under all three at once. Comparing editions and comparing branches are therefore the same+gesture, and the give-away is a UI that looks a release behind on every port at once rather than on one.+Read the edition off `/api/v1/flags`, not off the port you think you started.+Verify with `npx turbo run lint --filter=web`, or `npm run lint-dev` for the whole repo.## Gotchas@@ -125,4 +131,5 @@ Verify with `npx turbo run lint --filter=web`, or `npm run lint-dev` for the who- **A `.ts` and a `.tsx` of the same name can both sit in the tree, and every importer silently binds to the `.ts`.** `hooks/use-mobile.ts` and `hooks/use-mobile.tsx` were byte-for-byte identical for months: the `.ts` arrived with #11554 and nothing removed the `.tsx` that #11440 had left. Both TypeScript's Node resolution and Vite try `.ts` before `.tsx`, so all five importers of `@/hooks/use-mobile` resolved to the `.ts` and the `.tsx` was unreachable — while still being edited, linted and typechecked like live code. Nothing flags this: the import resolves, tsc is happy, and a `grep` for the symbol shows five healthy importers, which reads as proof the file is *used*. Only a reachability tool sees it. When a file looks dead but its symbol has importers, check for a same-named sibling with the other extension before concluding the tool is wrong.- **`knip` is the reachability check for `packages/web`; `npm run knip` must exit clean.** Config in `knip.json` at the repo root, every rule at its default `error` severity — nothing is muted, so a non-zero exit means real dead code, not noise. Two settings carry the weight. `src/features/*/index.ts` are **entry points**, because a feature barrel is that feature's public surface (see *Feature folder* above) and is meant to export more than today's callers import; without that, reachability reports the convention itself as dead. `ignoreExportsUsedInFile: true` means anything it does report is referenced *nowhere*, not even in its own file. The two `ignore*` lists cover what knip genuinely cannot see: `tailwindcss`/`tw-animate-css` arrive via `@import` in `styles.css` (knip does not follow CSS), and `dwebp`/`sips`/`cwebp` are system binaries shelled out to by `scripts/generate-usecase-images.mjs`.-- **When knip flags an export whose name clearly has live callers, look for a second symbol of that name before concluding knip is wrong.** This codebase repeatedly grew duplicates — something was moved or re-implemented and the old copy stayed — so a `grep` for the symbol finds the *other* one and reads as proof the finding is bogus. Every instance checked was knip being right: `use-mobile.ts` vs `.tsx` (identical files, resolution silently picks `.ts`), `cursor-position-context.tsx` duplicated under `flow-canvas/` and `state/` (two separate `createContext()` calls), `parseAnswerPairs` shared vs a local copy in `assistant-message.tsx`, and `FlowApprovalRequestState`/`PieceSelectorTabConfig` re-exported locally while every consumer imports them from `@activepieces/shared`. knip also resolves this repo's dynamic imports correctly, including `React.lazy(() => import(x))` (needs `default`) and `import(x).then(m => ({default: m.Named}))` (needs the named export) — do not assume it is guessing. Verify a finding by reading the importing file's actual `import` statement, never by counting `grep` hits on the name.\ No newline at end of file+- **When knip flags an export whose name clearly has live callers, look for a second symbol of that name before concluding knip is wrong.** This codebase repeatedly grew duplicates — something was moved or re-implemented and the old copy stayed — so a `grep` for the symbol finds the *other* one and reads as proof the finding is bogus. Every instance checked was knip being right: `use-mobile.ts` vs `.tsx` (identical files, resolution silently picks `.ts`), `cursor-position-context.tsx` duplicated under `flow-canvas/` and `state/` (two separate `createContext()` calls), `parseAnswerPairs` shared vs a local copy in `assistant-message.tsx`, and `FlowApprovalRequestState`/`PieceSelectorTabConfig` re-exported locally while every consumer imports them from `@activepieces/shared`. knip also resolves this repo's dynamic imports correctly, including `React.lazy(() => import(x))` (needs `default`) and `import(x).then(m => ({default: m.Named}))` (needs the named export) — do not assume it is guessing. Verify a finding by reading the importing file's actual `import` statement, never by counting `grep` hits on the name.+- **Rewriting a shared component silently drops whatever props it stops destructuring, and optional props make the compiler complicit.** Replacing `LockedFeatureGuard`'s body took the `RequestTrial` sales form off 17 pages at once: every caller still passed `featureKey` and `showContactSales`, the new component just never read them, and because both stayed `?:` in the props type nothing failed to compile and no call site changed in the diff. The prop a rewrite must not lose is the one to make **required** — the moment `featureKey` was, `tsc` listed exactly the call sites that had dropped it, across all three branches of the stack. When a component's props feed a business surface rather than styling, review the destructure, not the prop list.diff --git a/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.md b/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.mdindex 4e8a0afa8ac..83060a63be2 100644--- a/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.md+++ b/brain/knowledge/platform-editions-ee/ee-platform-plans-billing.md@@ -26,6 +26,9 @@ Billing and entitlements are powered by [Autumn](https://useautumn.com). Each pl- The daily report's directory, service, and telemetry symbols are named `license-key-usage-report`, but its **persisted system-job name is still `billing-usage-report`** (`BILLING_USAGE_REPORT` in `system-jobs/common.ts`), and its emitted event names are unchanged too. Both strings are keys that outlive a deploy — the job name identifies the already-scheduled row, the event names identify history already captured — so renaming either orphans what is out there instead of renaming it. They read as leftovers of the rename; they are not.- Never read entitlements inline from Autumn on a request path — always the `platform_plan` projection + Redis caches (`isBillingEnforced` is a plain Redis read defaulting to `false`, i.e. fail open).- Active flows are unlimited in the new plans (projected `null`); `checkActiveFlowsExceededLimit` still runs on flow enable/publish but only binds when a limit is set.+- **`billedTeamProjectsLimit: 0` hides the create-project control rather than crowning it.** The primary rail's `RailPinnedProjects` renders its create button only when the limit is non-zero, so a plan with no team projects at all shows no button in the rail — only the platform admin table keeps a crowned one. Testing a crowned rail control therefore needs a limit above zero that is fully consumed, not a limit of zero. `null` is unlimited, `0` is none, and the two read alike in a plan row.+- **`openDialog()` from `useManagePlanDialogStore` is a silent no-op on Community, so any upgrade button wired to it is dead there.** `<ManagePlanDialog />` is mounted behind `edition !== ApEdition.COMMUNITY` in all three layouts (`platform-layout`, `project-layout`, `builder-layout`), while the store is a plain Zustand flag that any caller can flip with nothing listening, so the click closes what it was in and shows nothing. Every upgrade surface therefore has to branch on `isCommunity` itself and offer the sales route instead. `FeatureSample`, `FeatureTeaser` and `useTeamProjectLimitGuard` all do; the last of those did not until the team-project limit dialog was fixed, having shipped a dead `Explore plans` on self-hosted installs since well before the platform admin redesign. Check the branch exists whenever you add one.+- **`RequestTrial` lives in `features/billing/components/`, not `app/components/`.** Anything under `features/*` that needs the sales call to action - the plan guards and the upgrade dialog - cannot reach into `app/`, because the `import/no-restricted-paths` zone is one-directional. Keeping it in billing lets both layers use it, since every `app/` caller is importing downward. It exports `FeatureKey`, the union the `activepieces.com/sales` page reads from the query string, and every `PLATFORM_FEATURES` entry carries one so a gated surface can hand over the right key.- Initial plan by edition: CE/EE → `OPEN_SOURCE_PLAN`, Cloud → `AUTUMN_FREE_PLAN`. CE and `TESTING` environments skip enrollment/sync entirely.- **Running billing locally means pointing a local backend at a *console*, not standing up Autumn.** Three gates must all pass or the provider is the empty no-op: `AP_EDITION` must be `cloud` or `ee` (`app.ts` sets `autumnBillingProvider` only there; Community returns `{ total: 0, byProject: [] }`), `AP_ENVIRONMENT` must **not** be `testing` (`triggerLazyBillingProviderSync`/`enrollBillingProviderOnCreate` early-return on it), and Redis must be up (billing reads/writes go through Redis caches). Enrollment is lazy — the first read of a billing/usage route fires `ensureEnrolled` → `enrollFree({ ownerEmail })` against `AUTUMN_CONSOLE_URL`. That prop **defaults to the production console** (`https://console.activepieces.com`), so an unconfigured local box enrolls a *real* customer keyed by the owner email; point it at the testing console instead. A freshly enrolled free customer has no events, so all usage aggregations read `0` until real `flow_run`/`ai`/`chat` credit events are metered for it. To merely eyeball the usage page with real data, `serve --filter=web -- --mode=cloud` against the cloud backend is far less setup than local billing.- **Hand-editing `platform_plan` flags to unlock a feature locally does not stick, and the revert looks like the feature breaking itself.** The lazy entitlement projection above rewrites the plan columns from Autumn on any plan read, so a flag you set by hand survives only until the next sync. Because the throttle is 15 minutes and the web app leaves TanStack Query's `refetchOnWindowFocus` at its default `true`, the trigger in practice is *returning to the tab after a break*: alt-tab quickly and the flag survives, come back later and it is gone — which reads as an intermittent bug in whatever feature the flag gated, not as billing. `triggerLazyBillingProviderSync` is fire-and-forget, so nothing in the request that caused it says so. The clean fix for local work is to null **both** `autumnCustomerId` and `autumnApiKey` on the row: `loadAutumnCreds` returns null only when both are nil, `refreshEntitlements` then returns before its `update()`, and hand-set flags stay put. Null exactly one and you hit the worst case — an `error`-level `Autumn credentials incomplete for an enrolled platform` and every billing call silently no-oping.diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex d3f607d4983..71bafc1268d 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -802,6 +802,7 @@"templates": "templates","secret managers": "secret managers","AI providers": "AI providers",+ "capabilities": "capabilities","AI tools": "AI tools","health metrics": "health metrics","projects": "projects",@@ -2897,5 +2898,152 @@"The input and output were not kept for this call.": "The input and output were not kept for this call.","The input and output are no longer available.": "The input and output are no longer available.","Too large to keep in full — some of it was dropped.": "Too large to keep in full — some of it was dropped.",- "what the call costs": "what the call costs"+ "what the call costs": "what the call costs",+ "Billing & usage": "Billing & usage",+ "Unlock Billing & Usage": "Unlock Billing & Usage",+ "Plan": "Plan",+ "Works with SAML and OIDC providers": "Works with SAML and OIDC providers",+ "Enforce SSO for everyone on the platform": "Enforce SSO for everyone on the platform",+ "Control who can self-serve sign up": "Control who can self-serve sign up",+ "Scope access per project, not per platform": "Scope access per project, not per platform",+ "Keep production flows safe from accidental edits": "Keep production flows safe from accidental edits",+ "Assign roles when you invite someone": "Assign roles when you invite someone",+ "Drive projects, flows and connections from your own tooling": "Drive projects, flows and connections from your own tooling",+ "Scope a key to the platform, not to a person": "Scope a key to the platform, not to a person",+ "Revoke a key without touching anyone’s login": "Revoke a key without touching anyone’s login",+ "AWS, Azure, GCP and HashiCorp Vault": "AWS, Azure, GCP and HashiCorp Vault",+ "Secrets never leave your infrastructure": "Secrets never leave your infrastructure",+ "One secure place to rotate everything": "One secure place to rotate everything",+ "Every user and system action, recorded": "Every user and system action, recorded",+ "Filter by user, project and event type": "Filter by user, project and event type",+ "Export for compliance reviews": "Export for compliance reviews",+ "Stream events to any endpoint": "Stream events to any endpoint",+ "Wire alerts into Slack, PagerDuty or email": "Wire alerts into Slack, PagerDuty or email",+ "Build your own monitoring on top": "Build your own monitoring on top",+ "Create once, use in any project": "Create once, use in any project",+ "Rotate credentials in a single place": "Rotate credentials in a single place",+ "Choose which projects can use each connection": "Choose which projects can use each connection",+ "Publish reusable templates to every project": "Publish reusable templates to every project",+ "One click from template to running flow": "One click from template to running flow",+ "Standardize how your teams automate": "Standardize how your teams automate",+ "Drop the builder into your app with the JS SDK": "Drop the builder into your app with the JS SDK",+ "Authenticate users with signing keys": "Authenticate users with signing keys",+ "Your customers automate without leaving your product": "Your customers automate without leaving your product",+ "Separate flows, connections and members per project": "Separate flows, connections and members per project",+ "Set credit and user quotas per project": "Set credit and user quotas per project",+ "Teams work side by side without stepping on each other": "Teams work side by side without stepping on each other",+ "Read the docs": "Read the docs",+ "Showing and hiding pieces needs a higher plan. You can browse the catalog, but changes won't stick.": "Showing and hiding pieces needs a higher plan. You can browse the catalog, but changes won't stick.",+ "This is an Enterprise feature, available on our paid plans.": "This is an Enterprise feature, available on our paid plans.",+ "AI Center & MCP": "AI Center & MCP",+ "AI credits this month": "AI credits this month",+ "API keys": "API keys",+ "Across {count, plural, =1 {# project} other {# projects}}": "Across {count, plural, =1 {# project} other {# projects}}",+ "Active platform keys": "Active platform keys",+ "All checks passed": "All checks passed",+ "All connected workers match the app release": "All connected workers match the app release",+ "All connections are healthy": "All connections are healthy",+ "Allowed email domains": "Allowed email domains",+ "Any domain": "Any domain",+ "App: disk, RAM and CPU checks passed": "App: disk, RAM and CPU checks passed",+ "App: one or more hardware checks failed": "App: one or more hardware checks failed",+ "Attention": "Attention",+ "Audit logging is not available on your plan": "Audit logging is not available on your plan",+ "Audit logging is recording": "Audit logging is recording",+ "Audit logs": "Audit logs",+ "Build": "Build",+ "Change": "Change",+ "Connections across every project that are expired, revoked or failing.": "Connections across every project that are expired, revoked or failing.",+ "Credentials, secrets, and the record of what happens on the platform.": "Credentials, secrets, and the record of what happens on the platform.",+ "Credits spent on AI steps and chat, out of your plan total.": "Credits spent on AI steps and chat, out of your plan total.",+ "Custom roles on top of the built-in ones.": "Custom roles on top of the built-in ones.",+ "Default model": "Default model",+ "Email and password": "Email and password",+ "Email and password login is enabled alongside Google": "Email and password login is enabled alongside Google",+ "Event streaming": "Event streaming",+ "Every app credential in use across the platform, whether owned by a project or shared globally.": "Every app credential in use across the platform, whether owned by a project or shared globally.",+ "Expose platform tools to external MCP clients": "Expose platform tools to external MCP clients",+ "External vaults connected": "External vaults connected",+ "Forward audit events to your own webhook": "Forward audit events to your own webhook",+ "Global connections": "Global connections",+ "Google sign-in": "Google sign-in",+ "Health of the app, workers, queues and triggers running your automations.": "Health of the app, workers, queues and triggers running your automations.",+ "How people get into this platform. Individual providers are configured under Single sign on.": "How people get into this platform. Individual providers are configured under Single sign on.",+ "Invites sent from any project that have not been accepted yet.": "Invites sent from any project that have not been accepted yet.",+ "Locked": "Locked",+ "Models, assistant capabilities and the MCP server your flows and chat rely on.": "Models, assistant capabilities and the MCP server your flows and chat rely on.",+ "Most used pieces": "Most used pieces",+ "Needs attention": "Needs attention",+ "No API keys issued": "No API keys issued",+ "No allowed email domains set": "No allowed email domains set",+ "No connections yet": "No connections yet",+ "No custom roles. Built-in roles in use.": "No custom roles. Built-in roles in use.",+ "No external vault connected": "No external vault connected",+ "No keys issued": "No keys issued",+ "No pending invitations": "No pending invitations",+ "No provider enabled for chat": "No provider enabled for chat",+ "No provider powers chat yet": "No provider powers chat yet",+ "No workers connected": "No workers connected",+ "Nothing to rotate": "Nothing to rotate",+ "One sign-in method is enabled": "One sign-in method is enabled",+ "Project connections": "Project connections",+ "Project roles": "Project roles",+ "Ready": "Ready",+ "Recommendations based on your current configuration.": "Recommendations based on your current configuration.",+ "Release notes": "Release notes",+ "Restrict domains": "Restrict domains",+ "Review sign-in": "Review sign-in",+ "Runtime": "Runtime",+ "Runtime settings for this instance": "Runtime settings for this instance",+ "SAML connected.": "SAML connected.",+ "SAML not connected yet.": "SAML not connected yet.",+ "Secret managers": "Secret managers",+ "Security checklist": "Security checklist",+ "Shared credentials available to multiple projects": "Shared credentials available to multiple projects",+ "Sign-in policy": "Sign-in policy",+ "Sign-up restricted to {count, plural, =1 {# domain} other {# domains}}": "Sign-up restricted to {count, plural, =1 {# domain} other {# domains}}",+ "Single sign on": "Single sign on",+ "Trigger health across the last 14 days": "Trigger health across the last 14 days",+ "Used by AI steps and the assistant when a flow does not pick a model explicitly.": "Used by AI steps and the assistant when a flow does not pick a model explicitly.",+ "Users & access": "Users & access",+ "Version behind latest; see release notes": "Version behind latest; see release notes",+ "Version unknown": "Version unknown",+ "Version {current} · latest is {latest}": "Version {current} · latest is {latest}",+ "Web search, scraping and image generation for the assistant": "Web search, scraping and image generation for the assistant",+ "Which apps your projects connect to most.": "Which apps your projects connect to most.",+ "Who can sign in, how they sign in, and what they can do inside projects.": "Who can sign in, how they sign in, and what they can do inside projects.",+ "Worker hardware checks unavailable": "Worker hardware checks unavailable",+ "Workers: RAM and CPU checks passed": "Workers: RAM and CPU checks passed",+ "Workers: one or more hardware checks failed": "Workers: one or more hardware checks failed",+ "Workspace": "Workspace",+ "Your plan, credits and how projects consume them.": "Your plan, credits and how projects consume them.",+ "unknown": "unknown",+ "used": "used",+ "{admins, plural, =1 {# admin} other {# admins}} · {members, plural, =1 {# member} other {# members}} · {deactivated} deactivated": "{admins, plural, =1 {# admin} other {# admins}} · {members, plural, =1 {# member} other {# members}} · {deactivated} deactivated",+ "{connected} of {total}": "{connected} of {total}",+ "{count, plural, =1 {# API key is} other {# API keys are}} active": "{count, plural, =1 {# API key is} other {# API keys are}} active",+ "{count, plural, =1 {# connection} other {# connections}}": "{count, plural, =1 {# connection} other {# connections}}",+ "{count, plural, =1 {# domain} other {# domains}}": "{count, plural, =1 {# domain} other {# domains}}",+ "{count, plural, =1 {# machine} other {# machines}} connected": "{count, plural, =1 {# machine} other {# machines}} connected",+ "{count, plural, =1 {# worker is} other {# workers are}} on an incompatible version": "{count, plural, =1 {# worker is} other {# workers are}} on an incompatible version",+ "{count} of 3": "{count} of 3",+ "{credits} credits included": "{credits} credits included",+ "{included} included": "{included} included",+ "{provider} powers chat": "{provider} powers chat",+ "{used} of {total} credits used this period": "{used} of {total} credits used this period",+ "Upgrade to {tier}": "Upgrade to {tier}",+ "Upgrade to unlock": "Upgrade to unlock",+ "Included with the {tier} plan and above.": "Included with the {tier} plan and above.",+ "Favicon": "Favicon",+ "Your platform name, branding and general settings.": "Your platform name, branding and general settings.",+ "Your logo, colors and favicon are part of custom branding.": "Your logo, colors and favicon are part of custom branding.",+ "Group pieces into sets and choose which projects can use each one": "Group pieces into sets and choose which projects can use each one",+ "Piece sets need a higher plan.": "Piece sets need a higher plan.",+ "invitations": "invitations",+ "workers": "workers",+ "health checks": "health checks",+ "billing": "billing",+ "project roles": "project roles",+ "infrastructure status": "infrastructure status",+ "Plans, credits and usage tracking are part of the Enterprise and Cloud editions.": "Plans, credits and usage tracking are part of the Enterprise and Cloud editions."}diff --git a/packages/web/src/app/components/feature-teaser.tsx b/packages/web/src/app/components/feature-teaser.tsxnew file mode 100644index 00000000000..ada0368be07--- /dev/null+++ b/packages/web/src/app/components/feature-teaser.tsx@@ -0,0 +1,138 @@+import { ApEdition, ApFlagId } from '@activepieces/shared';+import { t } from 'i18next';+import { Check, ExternalLink } from 'lucide-react';++import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ FeatureKey,+ RequestTrial,+ useManagePlanDialogStore,+} from '@/features/billing';+import {+ FeatureTier,+ TIER_LABELS,+} from '@/features/billing/utils/feature-tier';+import { flagsHooks } from '@/hooks/flags-hooks';++export function FeatureTeaserContent({+ title,+ description,+ bullets,+ tier,+ documentationUrl,+ videoUrl,+ featureKey,+ showContactSales = true,+}: FeatureTeaserProps) {+ const { openDialog: openManagePlanDialog } = useManagePlanDialogStore();+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);++ const showcase =+ videoUrl === undefined ? null : (+ <video+ autoPlay+ loop+ muted+ playsInline+ className="w-full rounded-lg"+ controls={false}+ src={videoUrl}+ />+ );++ if (edition === ApEdition.COMMUNITY) {+ const docsUrl = documentationUrl ?? ENTERPRISE_DOCUMENTATION_URL;+ return (+ <div className="flex max-w-md flex-col gap-2">+ <h2 className="text-base font-medium">{t(title)}</h2>+ <p className="text-sm text-muted-foreground">+ {t('This is an Enterprise feature, available on our paid plans.')}+ </p>+ <a+ href={docsUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex w-fit items-center gap-1 text-sm font-medium text-primary hover:underline"+ >+ {t('Read the docs')}+ <ExternalLink className="size-3.5" />+ </a>+ {showContactSales && (+ <div className="w-fit pt-2">+ <RequestTrial featureKey={featureKey} />+ </div>+ )}+ {showcase}+ </div>+ );+ }++ return (+ <div className="flex max-w-md flex-col gap-4">+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <h2 className="text-xl font-medium">{t(title)}</h2>+ {tier !== undefined && (+ <Badge variant="outline">{TIER_LABELS[tier]}</Badge>+ )}+ </div>+ <p className="text-sm leading-relaxed text-muted-foreground">+ {t(description)}+ </p>+ </div>++ {bullets !== undefined && bullets.length > 0 && (+ <ul className="flex flex-col gap-2">+ {bullets.map((bullet) => (+ <li key={bullet} className="flex items-start gap-2 text-sm">+ <Check className="mt-0.5 size-4 shrink-0 text-primary" />+ <span>{t(bullet)}</span>+ </li>+ ))}+ </ul>+ )}++ <div className="flex items-center gap-3">+ <Button onClick={() => openManagePlanDialog()}>+ {t('Upgrade plan')}+ </Button>+ {documentationUrl !== undefined && (+ <a+ href={documentationUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"+ >+ {t('Read the docs')}+ <ExternalLink className="size-3.5" />+ </a>+ )}+ </div>++ {showcase}+ </div>+ );+}++export function FeatureTeaser(props: FeatureTeaserProps) {+ return (+ <div className="flex w-full flex-1 flex-col px-6 pt-8">+ <FeatureTeaserContent {...props} />+ </div>+ );+}++const ENTERPRISE_DOCUMENTATION_URL =+ 'https://www.activepieces.com/docs/install/configuration/overview#enterprise-edition-optional';++export type FeatureTeaserProps = {+ featureKey: FeatureKey;+ showContactSales?: boolean;+ title: string;+ description: string;+ bullets?: string[];+ tier?: FeatureTier;+ documentationUrl?: string;+ videoUrl?: string;+};diff --git a/packages/web/src/app/components/locked-feature-guard.tsx b/packages/web/src/app/components/locked-feature-guard.tsxindex e8f2cadbfae..b55edb365a0 100644--- a/packages/web/src/app/components/locked-feature-guard.tsx+++ b/packages/web/src/app/components/locked-feature-guard.tsx@@ -1,23 +1,8 @@-import { ApEdition, ApFlagId } from '@activepieces/shared';-import { t } from 'i18next';import React from 'react';-import { Button } from '@/components/ui/button';-import { useManagePlanDialogStore } from '@/features/billing';-import { flagsHooks } from '@/hooks/flags-hooks';+import { FeatureKey, FeatureTier } from '@/features/billing';-import { FeatureKey, RequestTrial } from './request-trial';--type LockedFeatureGuardProps = {- children: React.ReactNode;- locked: boolean;- lockTitle: string;- lockDescription: string;- lockVideoUrl?: string;- lockDocumentationUrl?: string;- featureKey: FeatureKey;- showContactSales?: boolean;-};+import { FeatureTeaser } from './feature-teaser';export const LockedFeatureGuard = ({children,@@ -26,66 +11,40 @@ export const LockedFeatureGuard = ({lockDescription,lockVideoUrl,lockDocumentationUrl,+ lockBullets,+ lockTier,featureKey,showContactSales = true,}: LockedFeatureGuardProps) => {- const { openDialog: openManagePlanDialog } = useManagePlanDialogStore();- const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);- const isCommunity = edition === ApEdition.COMMUNITY;-if (!locked) {return children;}return (- <div className="flex w-full flex-col items-center justify-center gap-2">- <div className="pt-8 text-center flex flex-col gap-2 justify-center items-center">- <h1 className="text-3xl font-bold">{lockTitle}</h1>- <div className="text-center w-[485px] my-4 flex flex-col gap-2 justify-center items-center">- <p className="text-md leading-relaxed text-muted-foreground">- {lockDescription}- {lockDocumentationUrl && (- <>- {' '}- <a- href={lockDocumentationUrl}- target="_blank"- rel="noopener noreferrer"- className="text-primary underline"- >- Learn more- </a>- </>- )}- </p>+ <FeatureTeaser+ title={lockTitle}+ description={lockDescription}+ bullets={lockBullets}+ tier={lockTier}+ documentationUrl={lockDocumentationUrl}+ videoUrl={lockVideoUrl}+ featureKey={featureKey}+ showContactSales={showContactSales}+ />+ );+};- {isCommunity ? (- showContactSales && (- <div className="my-4">- <RequestTrial featureKey={featureKey} />- </div>- )- ) : (- <div className="my-4">- <Button onClick={() => openManagePlanDialog()}>- {t('Upgrade plan')}- </Button>- </div>- )}- </div>+export default LockedFeatureGuard;- {lockVideoUrl && (- <video- autoPlay- loop- muted- playsInline- className="max-w-[70vh] rounded-lg"- controls={false}- src={lockVideoUrl}- />- )}- </div>- </div>- );+type LockedFeatureGuardProps = {+ children: React.ReactNode;+ featureKey: FeatureKey;+ showContactSales?: boolean;+ locked: boolean;+ lockTitle: string;+ lockDescription: string;+ lockVideoUrl?: string;+ lockDocumentationUrl?: string;+ lockBullets?: string[];+ lockTier?: FeatureTier;};diff --git a/packages/web/src/app/components/project-settings/pieces/index.tsx b/packages/web/src/app/components/project-settings/pieces/index.tsxindex ad456735bf6..2e28f8caf89 100644--- a/packages/web/src/app/components/project-settings/pieces/index.tsx+++ b/packages/web/src/app/components/project-settings/pieces/index.tsx@@ -5,13 +5,13 @@ import { t } from 'i18next';import { Info, Package, Puzzle, Tag, Hash, GitBranch } from 'lucide-react';import { useMemo, useState } from 'react';-import { RequestTrial } from '@/app/components/request-trial';import { DataTable, RowDataWithActions } from '@/components/custom/data-table';import { DataTableColumnHeader } from '@/components/custom/data-table/data-table-column-header';import { DataTableInputPopover } from '@/components/custom/data-table/data-table-input-popover';import { LockedAlert } from '@/components/custom/locked-alert';import { Alert, AlertDescription } from '@/components/ui/alert';import { Badge } from '@/components/ui/badge';+import { RequestTrial } from '@/features/billing';import { pieceSetQueries } from '@/features/piece-sets';import { PieceIcon, piecesHooks } from '@/features/pieces';import { projectCollectionUtils } from '@/features/projects';diff --git a/packages/web/src/app/routes/mcp-server/pieces/pieces-tab.tsx b/packages/web/src/app/routes/mcp-server/pieces/pieces-tab.tsxindex adf8f5565f8..85d41bbb5e0 100644--- a/packages/web/src/app/routes/mcp-server/pieces/pieces-tab.tsx+++ b/packages/web/src/app/routes/mcp-server/pieces/pieces-tab.tsx@@ -8,13 +8,13 @@ import { useDebounce } from 'use-debounce';import { ProjectSettingsDialog } from '@/app/components/project-settings';import { mcpHooks } from '@/app/components/project-settings/mcp-server/utils/mcp-hooks';-import { RequestTrial } from '@/app/components/request-trial';import { LockedAlert } from '@/components/custom/locked-alert';import { SearchInput } from '@/components/custom/search-input';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import { Skeleton } from '@/components/ui/skeleton';import { VirtualizedList } from '@/components/ui/virtualized-list';+import { RequestTrial } from '@/features/billing';import { pieceSetQueries } from '@/features/piece-sets';import { piecesHooks } from '@/features/pieces/hooks/pieces-hooks';import { projectCollectionUtils } from '@/features/projects';diff --git a/packages/web/src/app/routes/platform/infra/workers/index.tsx b/packages/web/src/app/routes/platform/infra/workers/index.tsxindex fe7324018c2..2a6b8ec4a66 100644--- a/packages/web/src/app/routes/platform/infra/workers/index.tsx+++ b/packages/web/src/app/routes/platform/infra/workers/index.tsx@@ -22,8 +22,7 @@ import React from 'react';import { useSearchParams } from 'react-router-dom';import { DashboardPageHeader } from '@/app/components/dashboard-page-header';-import { LockedFeatureGuard } from '@/app/components/locked-feature-guard';-import { RequestTrial } from '@/app/components/request-trial';+import LockedFeatureGuard from '@/app/components/locked-feature-guard';import {Alert,AlertAction,@@ -43,6 +42,7 @@ import {TooltipContent,TooltipTrigger,} from '@/components/ui/tooltip';+import { RequestTrial } from '@/features/billing';import { workersQueries } from '@/features/platform-admin';import { flagsHooks } from '@/hooks/flags-hooks';import { platformHooks } from '@/hooks/platform-hooks';diff --git a/packages/web/src/app/routes/platform/setup/pieces/index.tsx b/packages/web/src/app/routes/platform/setup/pieces/index.tsxindex b938bd0123f..8d3f5e19a3c 100644--- a/packages/web/src/app/routes/platform/setup/pieces/index.tsx+++ b/packages/web/src/app/routes/platform/setup/pieces/index.tsx@@ -20,7 +20,6 @@ import { useSearchParams } from 'react-router-dom';import { toast } from 'sonner';import { DashboardPageHeader } from '@/app/components/dashboard-page-header';-import { RequestTrial } from '@/app/components/request-trial';import { CustomizeSelectorDialog } from '@/app/routes/platform/setup/pieces/customize-selector-dialog';import { DownloadPiecesReportButton } from '@/app/routes/platform/setup/pieces/download-pieces-report';import { PieceActions } from '@/app/routes/platform/setup/pieces/piece-actions';@@ -32,6 +31,7 @@ import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';import { LockedAlert } from '@/components/custom/locked-alert';import { Button } from '@/components/ui/button';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { RequestTrial } from '@/features/billing';import { oauthAppsQueries } from '@/features/connections';import {InstallPieceDialog,diff --git a/packages/web/src/app/routes/platform/users/index.tsx b/packages/web/src/app/routes/platform/users/index.tsxindex 4f314f0ca1c..2549c6530b9 100644--- a/packages/web/src/app/routes/platform/users/index.tsx+++ b/packages/web/src/app/routes/platform/users/index.tsx@@ -4,11 +4,10 @@ import {UserWithMetaInformation,} from '@activepieces/shared';import { t } from 'i18next';-import { User } from 'lucide-react';+import { Crown, User } from 'lucide-react';import { useMemo, useState } from 'react';import { DashboardPageHeader } from '@/app/components/dashboard-page-header';-import { LockedFeatureGuard } from '@/app/components/locked-feature-guard';import { DataTable } from '@/components/custom/data-table';import { UserRoundPlusIcon } from '@/components/icons/user-round-plus';import { Button } from '@/components/ui/button';@@ -37,7 +36,12 @@ export type UserRowData =export default function UsersPage() {const [inviteOpen, setInviteOpen] = useState(false);- const { handleSeatLimitError, seatLimitDialog } = useSeatLimitGuard();+ const {+ isOutOfSeats,+ ensureSeatsAvailable,+ handleSeatLimitError,+ seatLimitDialog,+ } = useSeatLimitGuard();const {data: usersData,@@ -117,12 +121,7 @@ export default function UsersPage() {const columns = createUsersTableColumns();return (- <LockedFeatureGuard- featureKey="USERS"- locked={false}- lockTitle={t('Unlock Users')}- lockDescription={t('Manage your users and their access to your projects')}- >+ <><div className="flex flex-col w-full"><DashboardPageHeadertitle={t('Users')}@@ -150,9 +149,17 @@ export default function UsersPage() {key="invite"className="gap-2"size="sm"- onClick={() => setInviteOpen(true)}+ onClick={() => {+ if (ensureSeatsAvailable(1)) {+ setInviteOpen(true);+ }+ }}>- <UserRoundPlusIcon size={16} />+ {isOutOfSeats ? (+ <Crown className="size-4 shrink-0 text-primary-foreground/90" />+ ) : (+ <UserRoundPlusIcon size={16} />+ )}<span className="text-sm font-medium">{t('Invite')}</span></Button>,]}@@ -175,6 +182,6 @@ export default function UsersPage() {onInviteSuccess={refetch}/>{seatLimitDialog}- </LockedFeatureGuard>+ </>);}diff --git a/packages/web/src/components/custom/data-table/index.tsx b/packages/web/src/components/custom/data-table/index.tsxindex 5d8413b6c55..919457fb1d0 100644--- a/packages/web/src/components/custom/data-table/index.tsx+++ b/packages/web/src/components/custom/data-table/index.tsx@@ -333,6 +333,7 @@ export function DataTable<const scrollContainerRef = useRef<HTMLDivElement>(null);const rows = table.getRowModel().rows;+ const visibleColumnCount = table.getVisibleLeafColumns().length;const virtualizer = useVirtualizer({count: rows.length,getScrollElement: () => scrollContainerRef.current,@@ -422,7 +423,7 @@ export function DataTable<{isLoading ? (<TableRow className="hover:bg-background"><TableCell- colSpan={columns.length}+ colSpan={visibleColumnCount}className="h-24 text-center"><DataTableSkeleton />@@ -434,7 +435,7 @@ export function DataTable<{virtualizer.getVirtualItems().length > 0 && (<tr><td- colSpan={columns.length}+ colSpan={visibleColumnCount}style={{height: virtualizer.getVirtualItems()[0].start,}}@@ -528,7 +529,7 @@ export function DataTable<{virtualizer.getVirtualItems().length > 0 && (<tr><td- colSpan={columns.length}+ colSpan={visibleColumnCount}style={{height:virtualizer.getTotalSize() -@@ -621,7 +622,7 @@ export function DataTable<) : isError ? (<TableRow className="hover:bg-transparent"><TableCell- colSpan={columns.length}+ colSpan={visibleColumnCount}className="h-[350px] text-center"><DataFetchErrorState@@ -633,7 +634,7 @@ export function DataTable<) : (<TableRow className="hover:bg-background"><TableCell- colSpan={columns.length}+ colSpan={visibleColumnCount}className="h-[350px] text-center"><div className="flex flex-col items-center justify-center gap-2">diff --git a/packages/web/src/app/components/request-trial.tsx b/packages/web/src/features/billing/components/request-trial.tsxsimilarity index 100%rename from packages/web/src/app/components/request-trial.tsxrename to packages/web/src/features/billing/components/request-trial.tsxdiff --git a/packages/web/src/features/billing/hooks/use-feature-gate.tsx b/packages/web/src/features/billing/hooks/use-feature-gate.tsxnew file mode 100644index 00000000000..34d32228099--- /dev/null+++ b/packages/web/src/features/billing/hooks/use-feature-gate.tsx@@ -0,0 +1,128 @@+import { ApEdition, ApFlagId } from '@activepieces/shared';+import { t } from 'i18next';+import { Check, Crown, ExternalLink } from 'lucide-react';+import { ReactNode, useState } from 'react';++import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { flagsHooks } from '@/hooks/flags-hooks';++import { FeatureKey } from '../components/request-trial';+import { useManagePlanDialogStore } from '../stores/manage-plan-dialog-state';+import { FeatureTier, TIER_LABELS } from '../utils/feature-tier';++export function useFeatureGate({ locked, feature }: UseFeatureGateParams) {+ const [open, setOpen] = useState(false);++ return {+ locked,+ crown: locked ? (+ <Crown className="size-3.5 shrink-0 text-primary-foreground/90" />+ ) : null,+ open: () => setOpen(true),+ dialog: (+ <UpgradeFeatureDialog open={open} onOpenChange={setOpen} {...feature} />+ ),+ };+}++export function UpgradeFeatureDialog({+ open,+ onOpenChange,+ title,+ description,+ bullets,+ tier,+ documentationUrl,+}: UpgradeFeatureDialogProps) {+ const { openDialog: openManagePlanDialog } = useManagePlanDialogStore();+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);+ const isCommunity = edition === ApEdition.COMMUNITY;+ const docsUrl = documentationUrl ?? ENTERPRISE_DOCUMENTATION_URL;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[28rem]">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ {t(title)}+ {tier !== undefined && !isCommunity && (+ <Badge variant="outline">{TIER_LABELS[tier]}</Badge>+ )}+ </DialogTitle>+ <DialogDescription>+ {isCommunity+ ? t('This is an Enterprise feature, available on our paid plans.')+ : t(description)}+ </DialogDescription>+ </DialogHeader>++ {!isCommunity && bullets !== undefined && bullets.length > 0 && (+ <ul className="flex flex-col gap-2">+ {bullets.map((bullet) => (+ <li key={bullet} className="flex items-start gap-2 text-sm">+ <Check className="mt-0.5 size-4 shrink-0 text-primary" />+ <span>{t(bullet)}</span>+ </li>+ ))}+ </ul>+ )}++ <DialogFooter className="sm:justify-start">+ {isCommunity ? (+ <a+ href={docsUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"+ >+ {t('Read the docs')}+ <ExternalLink className="size-3.5" />+ </a>+ ) : (+ <Button+ onClick={() => {+ onOpenChange(false);+ openManagePlanDialog();+ }}+ >+ {t('Upgrade plan')}+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++const ENTERPRISE_DOCUMENTATION_URL =+ 'https://www.activepieces.com/docs/install/configuration/overview#enterprise-edition-optional';++export type PlatformFeature = {+ featureKey: FeatureKey;+ title: string;+ description: string;+ bullets?: string[];+ tier?: FeatureTier;+ documentationUrl?: string;+ videoUrl?: string;+};++export type UseFeatureGateParams = {+ locked: boolean;+ feature: PlatformFeature;+};++export type UpgradeFeatureDialogProps = PlatformFeature & {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ children?: ReactNode;+};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 08f866246c2..8d95d317913 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@@ -52,15 +52,21 @@ export const useSeatLimitGuard = () => {return true;};- const ensureSeatsAvailable = (additionalSeats: number): boolean => {+ const hasSeatsFor = (additionalSeats: number): boolean => {if (isNil(info) || !info.billingEnforced || isNil(info.plan.usersLimit)) {return true;}- if (additionalSeats > info.plan.usersLimit - info.usage.users) {- openSeatLimit();- return false;+ return additionalSeats <= info.plan.usersLimit - info.usage.users;+ };++ const isOutOfSeats = !hasSeatsFor(1);++ const ensureSeatsAvailable = (additionalSeats: number): boolean => {+ if (hasSeatsFor(additionalSeats)) {+ return true;}- return true;+ openSeatLimit();+ return false;};const seatLimitDialog = isPlatformAdmin ? (@@ -79,7 +85,12 @@ export const useSeatLimitGuard = () => {/>);- return { handleSeatLimitError, ensureSeatsAvailable, seatLimitDialog };+ return {+ isOutOfSeats,+ handleSeatLimitError,+ ensureSeatsAvailable,+ seatLimitDialog,+ };};function ContactAdminSeatsDialog({diff --git a/packages/web/src/features/billing/hooks/use-team-project-limit-guard.tsx b/packages/web/src/features/billing/hooks/use-team-project-limit-guard.tsxindex 7f8ae082528..f753afec5c9 100644--- a/packages/web/src/features/billing/hooks/use-team-project-limit-guard.tsx+++ b/packages/web/src/features/billing/hooks/use-team-project-limit-guard.tsx@@ -1,31 +1,39 @@import { isNil } from '@activepieces/core-utils';-import { ProjectType, ProjectWithLimits } from '@activepieces/shared';+import {+ ApEdition,+ ApFlagId,+ ProjectType,+ ProjectWithLimits,+} from '@activepieces/shared';import { t } from 'i18next';-import { useState } from 'react';+import { Check, LayoutGrid } from 'lucide-react';+import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import {- Dialog,- DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,} from '@/components/ui/dialog';import { useIsPlatformAdmin } from '@/hooks/authorization-hooks';+import { flagsHooks } from '@/hooks/flags-hooks';import { platformHooks } from '@/hooks/platform-hooks';+import { RequestTrial } from '../components/request-trial';import { useManagePlanDialogStore } from '../stores/manage-plan-dialog-state';+import { TIER_LABELS } from '../utils/feature-tier';+import { PLATFORM_FEATURES } from '../utils/platform-features';export const useTeamProjectLimitGuard = ({projects,}: {projects: Pick<ProjectWithLimits, 'type'>[];}) => {- const [isLimitOpen, setIsLimitOpen] = useState(false);const isPlatformAdmin = useIsPlatformAdmin();const { platform } = platformHooks.useCurrentPlatform();const { openDialog } = useManagePlanDialogStore();+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);const limit = platform.plan.billedTeamProjectsLimit;const teamProjectsUsed = projects.filter(@@ -33,22 +41,14 @@ export const useTeamProjectLimitGuard = ({).length;const hasReachedLimit = !isNil(limit) && teamProjectsUsed >= limit;- const ensureTeamProjectAvailable = (): boolean => {- if (!hasReachedLimit) {- return true;- }- setIsLimitOpen(true);- return false;- };-- const teamProjectLimitDialog = (- <TeamProjectLimitDialog- open={isLimitOpen}- onOpenChange={setIsLimitOpen}+ const teamProjectLimitContent = ({ onClose }: { onClose: () => void }) => (+ <TeamProjectLimitContentlimit={limit ?? 0}isPlatformAdmin={isPlatformAdmin}+ isCommunity={edition === ApEdition.COMMUNITY}+ onClose={onClose}onExplorePlans={() => {- setIsLimitOpen(false);+ onClose();openDialog();}}/>@@ -56,67 +56,86 @@ export const useTeamProjectLimitGuard = ({return {hasReachedLimit,- ensureTeamProjectAvailable,- teamProjectLimitDialog,+ teamProjectLimitContent,};};-function TeamProjectLimitDialog({- open,- onOpenChange,+function TeamProjectLimitContent({limit,isPlatformAdmin,+ isCommunity,+ onClose,onExplorePlans,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- limit: number;- isPlatformAdmin: boolean;- onExplorePlans: () => void;-}) {+}: TeamProjectLimitContentProps) {+ const feature = PLATFORM_FEATURES.projects;+ const isFirstTeamProject = limit === 0;+ const showBenefits = isPlatformAdmin && isFirstTeamProject;+return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="max-w-[420px]">- <DialogHeader>- <DialogTitle>- {t("You've reached your team project limit")}- </DialogTitle>- <DialogDescription>- {isPlatformAdmin- ? limit === 0- ? t(- 'Team projects let you group flows and share them with your teammates. Upgrade to add one.',- )- : t(- 'Your plan includes {count, plural, =1 {1 team project} other {# team projects}}. Upgrade to add more.',- { count: limit },- )+ <>+ <DialogHeader>+ <div className="flex size-10 items-center justify-center rounded-full bg-primary/10">+ <LayoutGrid className="size-5 text-primary" />+ </div>+ <DialogTitle className="flex items-center gap-2">+ {showBenefits+ ? t(feature.title)+ : t("You've reached your team project limit")}+ {showBenefits && (+ <Badge variant="outline">{TIER_LABELS[feature.tier]}</Badge>+ )}+ </DialogTitle>+ <DialogDescription>+ {isPlatformAdmin+ ? isFirstTeamProject+ ? t(feature.description): t(- 'Contact a platform admin to upgrade the plan and add more team projects.',- )}- </DialogDescription>- </DialogHeader>- <DialogFooter>- {isPlatformAdmin ? (- <>- <Button- type="button"- variant="outline"- onClick={() => onOpenChange(false)}- >- {t('Cancel')}- </Button>+ 'Your plan includes {count, plural, =1 {1 team project} other {# team projects}}. Upgrade to add more.',+ { count: limit },+ )+ : t(+ 'Contact a platform admin to upgrade the plan and add more team projects.',+ )}+ </DialogDescription>+ </DialogHeader>+ {showBenefits && (+ <ul className="flex flex-col gap-2">+ {feature.bullets.map((bullet) => (+ <li key={bullet} className="flex items-start gap-2 text-sm">+ <Check className="mt-0.5 size-4 shrink-0 text-primary" />+ <span>{t(bullet)}</span>+ </li>+ ))}+ </ul>+ )}+ <DialogFooter>+ {isPlatformAdmin ? (+ <>+ <Button type="button" variant="outline" onClick={onClose}>+ {t('Cancel')}+ </Button>+ {isCommunity ? (+ <RequestTrial featureKey={feature.featureKey} />+ ) : (<Button type="button" onClick={onExplorePlans}>{t('Explore plans')}</Button>- </>- ) : (- <Button type="button" onClick={() => onOpenChange(false)}>- {t('Got it')}- </Button>- )}- </DialogFooter>- </DialogContent>- </Dialog>+ )}+ </>+ ) : (+ <Button type="button" onClick={onClose}>+ {t('Got it')}+ </Button>+ )}+ </DialogFooter>+ </>);}++type TeamProjectLimitContentProps = {+ limit: number;+ isPlatformAdmin: boolean;+ isCommunity: boolean;+ onClose: () => void;+ onExplorePlans: () => void;+};diff --git a/packages/web/src/features/billing/index.ts b/packages/web/src/features/billing/index.tsindex 954f1ab8d8d..0a56444bd4d 100644--- a/packages/web/src/features/billing/index.ts+++ b/packages/web/src/features/billing/index.ts@@ -30,3 +30,10 @@ export {} from './components/plan-selector-utils';export { useManagePlanDialogStore } from './stores/manage-plan-dialog-state';export { AutomaticTrialActivation } from './components/automatic-trial-activation';+export { useFeatureGate, UpgradeFeatureDialog } from './hooks/use-feature-gate';+export type { PlatformFeature } from './hooks/use-feature-gate';+export { RequestTrial } from './components/request-trial';+export type { FeatureKey } from './components/request-trial';+export { TIER_LABELS } from './utils/feature-tier';+export type { FeatureTier } from './utils/feature-tier';+export { PLATFORM_FEATURES } from './utils/platform-features';diff --git a/packages/web/src/features/billing/utils/feature-tier.ts b/packages/web/src/features/billing/utils/feature-tier.tsnew file mode 100644index 00000000000..6a3442b8957--- /dev/null+++ b/packages/web/src/features/billing/utils/feature-tier.ts@@ -0,0 +1,6 @@+export const TIER_LABELS: Record<FeatureTier, string> = {+ team: 'Team',+ enterprise: 'Enterprise',+};++export type FeatureTier = 'team' | 'enterprise';diff --git a/packages/web/src/features/billing/utils/platform-features.ts b/packages/web/src/features/billing/utils/platform-features.tsnew file mode 100644index 00000000000..be4e7e213fe--- /dev/null+++ b/packages/web/src/features/billing/utils/platform-features.ts@@ -0,0 +1,145 @@+import { PlatformFeature } from '../hooks/use-feature-gate';++export const PLATFORM_FEATURES = {+ projects: {+ featureKey: 'PROJECTS',+ title: 'Unlock Projects',+ description:+ 'Orchestrate your automation teams across projects with their own flows, connections and usage quotas',+ tier: 'team',+ bullets: [+ 'Separate flows, connections and members per project',+ 'Set credit and user quotas per project',+ 'Teams work side by side without stepping on each other',+ ],+ },+ sso: {+ featureKey: 'SSO',+ title: 'Enable Single Sign On',+ description:+ 'Let your users sign in with your current SSO provider or give them self serve sign up access',+ tier: 'team',+ bullets: [+ 'Works with SAML and OIDC providers',+ 'Enforce SSO for everyone on the platform',+ 'Control who can self-serve sign up',+ ],+ },+ projectRoles: {+ featureKey: 'CUSTOM_ROLES',+ title: 'Project Role Management',+ description:+ 'Define custom roles and permissions to control what your team members can access and modify',+ tier: 'team',+ bullets: [+ 'Scope access per project, not per platform',+ 'Keep production flows safe from accidental edits',+ 'Assign roles when you invite someone',+ ],+ },+ globalConnections: {+ featureKey: 'GLOBAL_CONNECTIONS',+ title: 'Enable Global Connections',+ description: 'Manage platform-wide connections to external systems.',+ tier: 'team',+ bullets: [+ 'Create once, use in any project',+ 'Rotate credentials in a single place',+ 'Choose which projects can use each connection',+ ],+ },+ apiKeys: {+ featureKey: 'API',+ title: 'Enable API Keys',+ description: 'Create and manage API keys to access Activepieces APIs.',+ tier: 'team',+ bullets: [+ 'Drive projects, flows and connections from your own tooling',+ 'Scope a key to the platform, not to a person',+ 'Revoke a key without touching anyone’s login',+ ],+ },+ secretManagers: {+ featureKey: 'SECRET_MANAGERS',+ title: 'Enable Secret Managers',+ description: 'Manage your secrets from a single and secure place',+ tier: 'enterprise',+ bullets: [+ 'AWS, Azure, GCP and HashiCorp Vault',+ 'Secrets never leave your infrastructure',+ 'One secure place to rotate everything',+ ],+ },+ auditLogs: {+ featureKey: 'AUDIT_LOGS',+ title: 'Unlock Audit Logs',+ description:+ 'Comply with internal and external security policies by tracking activities done within your account',+ tier: 'enterprise',+ bullets: [+ 'Every user and system action, recorded',+ 'Filter by user, project and event type',+ 'Export for compliance reviews',+ ],+ },+ eventStreaming: {+ featureKey: 'EVENT_DESTINATIONS',+ title: 'Unlock Event Streaming',+ description:+ 'Forward every audit event we emit to a webhook, then handle it in a flow.',+ tier: 'enterprise',+ bullets: [+ 'Stream events to any endpoint',+ 'Wire alerts into Slack, PagerDuty or email',+ 'Build your own monitoring on top',+ ],+ },+ templates: {+ featureKey: 'TEMPLATES',+ title: 'Unlock Templates',+ description:+ 'Convert the most common automations into reusable templates 1 click away from your users',+ tier: 'enterprise',+ bullets: [+ 'Publish reusable templates to every project',+ 'One click from template to running flow',+ 'Standardize how your teams automate',+ ],+ },+ embedding: {+ featureKey: 'SIGNING_KEYS',+ title: 'Unlock Embedding Through JS SDK',+ description: 'Enable signing keys to access embedding functionalities.',+ tier: 'enterprise',+ bullets: [+ 'Drop the builder into your app with the JS SDK',+ 'Authenticate users with signing keys',+ 'Your customers automate without leaving your product',+ ],+ },+ branding: {+ featureKey: 'BRANDING',+ title: 'Unlock Branding',+ description: 'Your name, logo and colors across the entire experience.',+ tier: 'enterprise',+ bullets: [+ 'Custom logo, icon, favicon and colors',+ 'Branded emails and sign-in pages',+ 'Your product, not ours',+ ],+ },+ pieces: {+ featureKey: 'PIECES',+ title: 'Unlock Piece Management',+ description:+ 'Curate which pieces your users see, hide the rest, and add your own private pieces.',+ tier: 'enterprise',+ bullets: [+ 'Show only the pieces that matter to your users',+ 'Ship private pieces for internal systems',+ 'Keep the catalog on-brand and focused',+ ],+ },+} satisfies Record<string, PlatformFeature>;++export type PlatformFeatureId = keyof typeof PLATFORM_FEATURES;diff --git a/packages/web/src/features/platform-admin/hooks/api-key-hooks.ts b/packages/web/src/features/platform-admin/hooks/api-key-hooks.tsindex 67d51f1619e..f9a3e25ec5c 100644--- a/packages/web/src/features/platform-admin/hooks/api-key-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/api-key-hooks.ts@@ -1,5 +1,7 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { platformHooks } from '@/hooks/platform-hooks';+import { apiKeyApi } from '../api/api-key-api';export const apiKeyKeys = {@@ -7,13 +9,16 @@ export const apiKeyKeys = {};export const apiKeyQueries = {- useApiKeys: () =>- useQuery({+ useApiKeys: () => {+ const { platform } = platformHooks.useCurrentPlatform();+ return useQuery({queryKey: apiKeyKeys.all,gcTime: 0,staleTime: 0,queryFn: () => apiKeyApi.list(),- }),+ enabled: platform.plan.apiKeysEnabled,+ });+ },};export const apiKeyMutations = {diff --git a/packages/web/src/features/platform-admin/hooks/signing-key-hooks.ts b/packages/web/src/features/platform-admin/hooks/signing-key-hooks.tsindex c7ce28f1c94..7ac5ecf5792 100644--- a/packages/web/src/features/platform-admin/hooks/signing-key-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/signing-key-hooks.ts@@ -4,6 +4,8 @@ import {} from '@activepieces/shared';import { useMutation, useQuery } from '@tanstack/react-query';+import { platformHooks } from '@/hooks/platform-hooks';+import { signingKeyApi } from '../api/signing-key-api';export const signingKeyKeys = {@@ -11,13 +13,16 @@ export const signingKeyKeys = {};export const signingKeyQueries = {- useSigningKeys: () =>- useQuery({+ useSigningKeys: () => {+ const { platform } = platformHooks.useCurrentPlatform();+ return useQuery({queryKey: signingKeyKeys.all,gcTime: 0,staleTime: 0,queryFn: () => signingKeyApi.list(),- }),+ enabled: platform.plan.embeddingEnabled,+ });+ },};export const signingKeyMutations = {diff --git a/packages/web/src/features/projects/components/create-project-button.tsx b/packages/web/src/features/projects/components/create-project-button.tsxindex e668b8bdd43..41bbae7dc9c 100644--- a/packages/web/src/features/projects/components/create-project-button.tsx+++ b/packages/web/src/features/projects/components/create-project-button.tsx@@ -1,12 +1,17 @@import { ProjectWithLimits } from '@activepieces/shared';import { t } from 'i18next';-import { Plus } from 'lucide-react';+import { Crown, Plus } from 'lucide-react';+import React from 'react';import { AnimatedIconButton } from '@/components/custom/animated-icon-button';import { PlusIcon } from '@/components/icons/plus';import { Button } from '@/components/ui/button';import { SidebarMenuButton } from '@/components/ui/sidebar-shadcn';-import { useTeamProjectLimitGuard } from '@/features/billing';+import {+ PLATFORM_FEATURES,+ useFeatureGate,+ useTeamProjectLimitGuard,+} from '@/features/billing';import { cn } from '@/lib/utils';import { NewProjectDialog } from './new-project-dialog';@@ -17,31 +22,35 @@ export function CreateProjectButton({onCreate,className,}: CreateProjectButtonProps) {- const {- hasReachedLimit,- ensureTeamProjectAvailable,- teamProjectLimitDialog,- } = useTeamProjectLimitGuard({ projects });+ const { hasReachedLimit, teamProjectLimitContent } = useTeamProjectLimitGuard(+ { projects },+ );+ const projectsGate = useFeatureGate({+ locked: hasReachedLimit,+ feature: PLATFORM_FEATURES.projects,+ });const trigger = triggerFor({variant,className,- onClick: hasReachedLimit ? () => ensureTeamProjectAvailable() : undefined,+ crown: projectsGate.crown,+ locked: projectsGate.locked,});return (- <>- {hasReachedLimit ? (- trigger- ) : (- <NewProjectDialog onCreate={onCreate}>{trigger}</NewProjectDialog>- )}- {teamProjectLimitDialog}- </>+ <NewProjectDialog+ onCreate={onCreate}+ gate={{+ locked: hasReachedLimit,+ content: teamProjectLimitContent,+ }}+ >+ {trigger}+ </NewProjectDialog>);}-function triggerFor({ variant, className, onClick }: TriggerForParams) {+function triggerFor({ variant, className, crown, locked }: TriggerForParams) {switch (variant) {case 'icon':return (@@ -49,19 +58,22 @@ function triggerFor({ variant, className, onClick }: TriggerForParams) {variant="ghost"size="icon"className={cn('h-6 w-6 hover:bg-accent', className)}- onClick={onClick}>- <Plus />+ {locked ? <Crown className="text-primary" /> : <Plus />}</Button>);case 'full':- return (+ return crown ? (+ <Button size="sm" className={cn('has-[>svg]:px-2.5', className)}>+ {crown}+ {t('New Project')}+ </Button>+ ) : (<AnimatedIconButtonicon={PlusIcon}iconSize={16}size="sm"className={className}- onClick={onClick}>{t('New Project')}</AnimatedIconButton>@@ -70,9 +82,12 @@ function triggerFor({ variant, className, onClick }: TriggerForParams) {return (<SidebarMenuButtonclassName={cn('text-muted-foreground gap-2', className)}- onClick={onClick}>- <Plus className="size-4" />+ {locked ? (+ <Crown className="size-4 text-primary" />+ ) : (+ <Plus className="size-4" />+ )}<span>{t('Add team project')}</span></SidebarMenuButton>);@@ -84,7 +99,8 @@ type CreateProjectButtonVariant = 'icon' | 'full' | 'sidebar-menu';type TriggerForParams = {variant: CreateProjectButtonVariant;className?: string;- onClick?: () => void;+ crown: React.ReactNode;+ locked: boolean;};type CreateProjectButtonProps = {diff --git a/packages/web/src/features/projects/components/new-project-dialog.tsx b/packages/web/src/features/projects/components/new-project-dialog.tsxindex d3c7753d60d..09286a20169 100644--- a/packages/web/src/features/projects/components/new-project-dialog.tsx+++ b/packages/web/src/features/projects/components/new-project-dialog.tsx@@ -7,6 +7,7 @@ import {import { zodResolver } from '@hookform/resolvers/zod';import { useQueryClient } from '@tanstack/react-query';import { t } from 'i18next';+import { Crown } from 'lucide-react';import { useState } from 'react';import { useForm } from 'react-hook-form';import { z } from 'zod';@@ -43,10 +44,16 @@ import { userHooks } from '@/hooks/user-hooks';type NewProjectDialogProps = {children: React.ReactNode;onCreate?: (project: ProjectWithLimits) => void;+ gate?: {+ locked: boolean;+ content: (args: { onClose: () => void }) => React.ReactNode;+ };};export const NewProjectDialog = (props: NewProjectDialogProps) => {const [open, setOpen] = useState(false);+ const [blockedOnSubmit, setBlockedOnSubmit] = useState(false);+ const showGate = props.gate?.locked === true || blockedOnSubmit;const { platform } = platformHooks.useCurrentPlatform();const globalConnectionsEnabled = platform.plan.globalConnectionsEnabled;@@ -58,28 +65,53 @@ export const NewProjectDialog = (props: NewProjectDialogProps) => {const globalConnections = globalConnectionsPage?.data ?? [];+ const changeOpen = (next: boolean) => {+ setOpen(next);+ if (!next) {+ setBlockedOnSubmit(false);+ }+ };+return (- <Dialog key={open ? 'open' : 'closed'} open={open} onOpenChange={setOpen}>+ <Dialog+ key={open ? 'open' : 'closed'}+ open={open}+ onOpenChange={changeOpen}+ ><DialogTrigger asChild>{props.children}</DialogTrigger><DialogContent>- <DialogHeader>- <DialogTitle>{t('Create Project')}</DialogTitle>- <DialogDescription>- {t(- 'Set up a new project to organize your automations and connections.',+ {showGate && props.gate !== undefined ? (+ props.gate.content({ onClose: () => changeOpen(false) })+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>{t('Create Project')}</DialogTitle>+ <DialogDescription>+ {t(+ 'Set up a new project to organize your automations and connections.',+ )}+ </DialogDescription>+ </DialogHeader>+ {(!isLoadingConnections || !globalConnectionsEnabled) && (+ <NewProjectForm+ setOpen={setOpen}+ globalConnections={globalConnections}+ globalConnectionsEnabled={globalConnectionsEnabled}+ onCreate={props.onCreate}+ gate={+ props.gate === undefined+ ? undefined+ : {+ locked: props.gate.locked,+ onBlocked: () => setBlockedOnSubmit(true),+ }+ }+ />)}- </DialogDescription>- </DialogHeader>- {(!isLoadingConnections || !globalConnectionsEnabled) && (- <NewProjectForm- setOpen={setOpen}- globalConnections={globalConnections}- globalConnectionsEnabled={globalConnectionsEnabled}- onCreate={props.onCreate}- />- )}- {isLoadingConnections && globalConnectionsEnabled && (- <SkeletonList numberOfItems={3} className="h-10" />+ {isLoadingConnections && globalConnectionsEnabled && (+ <SkeletonList numberOfItems={3} className="h-10" />+ )}+ </>)}</DialogContent></Dialog>@@ -91,10 +123,12 @@ const NewProjectForm = ({setOpen,globalConnections,globalConnectionsEnabled,-}: Omit<NewProjectDialogProps, 'children'> & {+ gate,+}: Omit<NewProjectDialogProps, 'children' | 'gate'> & {setOpen: (open: boolean) => void;globalConnections: AppConnectionWithoutSensitiveData[];globalConnectionsEnabled: boolean;+ gate?: { locked: boolean; onBlocked: () => void };}) => {const queryClient = useQueryClient();const { platform } = platformHooks.useCurrentPlatform();@@ -271,9 +305,14 @@ const NewProjectForm = ({onClick={(e) => {e.stopPropagation();e.preventDefault();+ if (gate?.locked === true) {+ gate.onBlocked();+ return;+ }form.handleSubmit(handleCreate)(e);}}>+ {gate?.locked === true && <Crown className="size-3.5 shrink-0" />}{t('Create Project')}</Button></DialogFooter>diff --git a/packages/web/test/app/billing/feature-gating.test.tsx b/packages/web/test/app/billing/feature-gating.test.tsxnew file mode 100644index 00000000000..2253645177c--- /dev/null+++ b/packages/web/test/app/billing/feature-gating.test.tsx@@ -0,0 +1,244 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable jest-dom/prefer-in-document -- @testing-library/jest-dom is not a dependency of packages/web */+/* eslint-disable testing-library/no-container, testing-library/no-node-access -- <video> has no implicit ARIA role */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { render, screen, fireEvent } from '@testing-library/react';+import * as React from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++let teamProjectsLimit: number | null = 0;+let edition = 'cloud';+const createProject = vi.fn();++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('lucide-react', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ Crown: (props: Record<string, unknown>) =>+ React.createElement('span', { ...props, 'data-testid': 'crown' }),+}));++vi.mock('@/hooks/platform-hooks', () => ({+ platformHooks: {+ useCurrentPlatform: () => ({+ platform: {+ plan: {+ billedTeamProjectsLimit: teamProjectsLimit,+ globalConnectionsEnabled: false,+ },+ },+ }),+ },+}));+vi.mock('@/hooks/user-hooks', () => ({+ userHooks: {+ getCurrentUserPlatformRole: () => 'ADMIN',+ useCurrentUser: () => ({ data: undefined }),+ },+}));+vi.mock('@/hooks/authorization-hooks', () => ({+ useIsPlatformAdmin: () => true,+}));+vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: {+ useFlag: () => ({ data: edition }),+ useFlags: () => ({ data: {} }),+ },+}));+vi.mock('@/features/billing/stores/manage-plan-dialog-state', () => ({+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+}));+vi.mock('@/features/billing', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useManagePlanDialogStore: () => ({ openDialog: vi.fn() }),+}));+vi.mock('@/features/connections', () => ({+ globalConnectionsQueries: {+ useGlobalConnections: () => ({ data: { data: [] }, isLoading: false }),+ },+}));+vi.mock('@/features/projects', () => ({+ projectCollectionUtils: {+ invalidate: vi.fn(),+ useCreateProject: () => ({ mutate: createProject, isPending: false }),+ },+}));+vi.mock('@/components/custom/global-connection-utils', () => ({+ DefaultTag: () => null,+}));+vi.mock('@/components/custom/multi-select-piece-property', () => ({+ MultiSelectPieceProperty: () => null,+}));+vi.mock('@/components/ui/sonner', () => ({ internalErrorToast: vi.fn() }));+vi.mock('@/components/custom/animated-icon-button', () => ({+ AnimatedIconButton: ({+ children,+ icon: _icon,+ iconSize: _iconSize,+ ...rest+ }: React.PropsWithChildren<Record<string, unknown>>) => (+ <button {...rest} data-testid="new-project-trigger">+ {children}+ </button>+ ),+}));+vi.mock('@/components/icons/plus', () => ({ PlusIcon: () => null }));+vi.mock('@/components/ui/sidebar-shadcn', () => ({+ SidebarMenuButton: ({+ children,+ ...rest+ }: React.PropsWithChildren<Record<string, unknown>>) => (+ <button {...rest}>{children}</button>+ ),+}));++import { FeatureTeaser } from '@/app/components/feature-teaser';+import { CreateProjectButton } from '@/features/projects/components/create-project-button';++const LIMIT_REACHED_COPY = "You've reached your team project limit";+const SHOWCASE_VIDEO =+ 'https://cdn.activepieces.com/videos/showcase/api-keys.mp4';++const renderWithQueryClient = (ui: React.ReactElement) =>+ render(+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ {ui}+ </QueryClientProvider>,+ );++const usedTeamProjects = (count: number) =>+ Array.from({ length: count }, () => ({ type: 'TEAM' })) as never;++beforeEach(() => {+ teamProjectsLimit = 0;+ edition = 'cloud';+ createProject.mockClear();+});++describe('create project gating', () => {+ it('crowns the button when the plan includes no team projects', () => {+ teamProjectsLimit = 0;+ renderWithQueryClient(+ <CreateProjectButton variant="full" projects={usedTeamProjects(0)} />,+ );+ expect(screen.getByTestId('crown')).toBeDefined();+ });++ it('crowns the button when the team project allowance is used up', () => {+ teamProjectsLimit = 3;+ renderWithQueryClient(+ <CreateProjectButton variant="full" projects={usedTeamProjects(3)} />,+ );+ expect(screen.getByTestId('crown')).toBeDefined();+ });++ it('crowns every variant, including the sidebar rail', () => {+ teamProjectsLimit = 0;+ renderWithQueryClient(+ <CreateProjectButton variant="icon" projects={usedTeamProjects(0)} />,+ );+ expect(screen.getByTestId('crown')).toBeDefined();+ });++ it('refuses on the click instead of after the form is filled in', () => {+ teamProjectsLimit = 3;+ renderWithQueryClient(+ <CreateProjectButton variant="full" projects={usedTeamProjects(3)} />,+ );+ fireEvent.click(screen.getByRole('button', { name: /new project/i }));+ expect(screen.getByText(LIMIT_REACHED_COPY)).toBeDefined();+ expect(screen.queryAllByRole('textbox')).toHaveLength(0);+ expect(createProject).not.toHaveBeenCalled();+ });++ it('offers contact sales instead of a dead upgrade button on community', () => {+ edition = 'ce';+ teamProjectsLimit = 1;+ renderWithQueryClient(+ <CreateProjectButton variant="full" projects={usedTeamProjects(1)} />,+ );+ fireEvent.click(screen.getByRole('button', { name: /new project/i }));+ expect(screen.getByRole('button', { name: /contact sales/i })).toBeDefined();+ expect(screen.queryByRole('button', { name: /explore plans/i })).toBeNull();+ });++ it('keeps explore plans where the plan dialog is actually mounted', () => {+ edition = 'cloud';+ teamProjectsLimit = 1;+ renderWithQueryClient(+ <CreateProjectButton variant="full" projects={usedTeamProjects(1)} />,+ );+ fireEvent.click(screen.getByRole('button', { name: /new project/i }));+ expect(screen.getByRole('button', { name: /explore plans/i })).toBeDefined();+ expect(screen.queryByRole('button', { name: /contact sales/i })).toBeNull();+ });++ it('still opens the form when the plan has room', () => {+ teamProjectsLimit = 3;+ renderWithQueryClient(+ <CreateProjectButton variant="full" projects={usedTeamProjects(1)} />,+ );+ fireEvent.click(screen.getByRole('button', { name: /new project/i }));+ expect(screen.queryByText(LIMIT_REACHED_COPY)).toBeNull();+ expect(screen.queryAllByRole('textbox').length).toBeGreaterThan(0);+ });+});++describe('feature teaser', () => {+ it('plays the showcase video on community, same as every other edition', () => {+ edition = 'ce';+ const { container } = render(+ <FeatureTeaser+ featureKey="API"+ title="Enable API Keys"+ description=""+ videoUrl={SHOWCASE_VIDEO}+ />,+ );+ expect(container.querySelector('video')?.getAttribute('src')).toBe(+ SHOWCASE_VIDEO,+ );+ });++ it('offers contact sales on community, as the locked page did before', () => {+ edition = 'ce';+ render(+ <FeatureTeaser featureKey="API" title="Enable API Keys" description="" />,+ );+ expect(screen.getByRole('button', { name: /contact sales/i })).toBeDefined();+ });++ it('drops contact sales only where the caller opts out', () => {+ edition = 'ce';+ render(+ <FeatureTeaser+ featureKey="BILLING"+ title="Enable Billing"+ description=""+ showContactSales={false}+ />,+ );+ expect(screen.queryByRole('button', { name: /contact sales/i })).toBeNull();+ });++ it('plays the showcase video on cloud', () => {+ edition = 'cloud';+ const { container } = render(+ <FeatureTeaser+ featureKey="API"+ title="Enable API Keys"+ description=""+ videoUrl={SHOWCASE_VIDEO}+ />,+ );+ expect(container.querySelector('video')?.getAttribute('src')).toBe(+ SHOWCASE_VIDEO,+ );+ });+});