Skip to content

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

feat(analytics): track onboarding, invitations and billing lifecycle in PostHog (#15535)

moaaz1c950a94cc8e
diff --git a/brain/knowledge/data-storage-observability/index.md b/brain/knowledge/data-storage-observability/index.md
index a2a84c97205..75a895c7ef6 100644
--- a/brain/knowledge/data-storage-observability/index.md
+++ b/brain/knowledge/data-storage-observability/index.md
@@ -65,6 +65,19 @@ Gotchas:
- The Google `USER_SIGNED_UP` audit event is gated on `signedUp` too; before that it fired on every login.
- SAML users are never stamped: they are provisioned by their platform admin, not by a campaign link.
+### Product Lifecycle Telemetry
+
+Server-side PostHog events for the moments between sign-up and payment: `onboarding.completed` (name step done), `invite.sent` / `invite.accepted`, `checkout.started`, `plan.changed`, `plan.cancelled`, `plan.reactivated`, `trial.started`, plus `flow.published` from the service so API and approval publishes count too. Billing events are emitted by `platform-plan-telemetry.ts`; the entitlement refresh in `autumn-utils.ts` compares the plan before and after and emits `trial.started` or `plan.changed` when it changed, skipping free plans (`FREE`, `FREE_LEGACY`, `APPSUMO`). Platforms are PostHog groups (`groupIdentify`, type `platform`) set on creation and refreshed on plan change. Every event, person and group carries `deployment` (`DeploymentKind`: cloud, self_hosted, dev) because self-hosted instances report into the same project.
+
+Gotchas:
+- Pre-login email-code events are keyed by the identity id; `aliasIdentity` merges that person into the user once the user exists, and `trackForIdentity` in `passwordless-auth.service.ts` switches to the user id as soon as one exists for identity+platform.
+- Billing and onboarding events are in `CLOUD_ONLY_TELEMETRY_EVENTS`; the tracked-events catalog on the platform settings page hides groups whose events are all cloud-only, so `billing` never shows on self-hosted.
+- In a development environment the web sends nothing to PostHog unless `localStorage.ap_posthog_dev` is `'1'`.
+- **The event is `plan.changed`, not `plan.upgraded`** — the entitlement refresh only knows the plan differs, not which way, so a downgrade reaches the same code path. Direction is derived in PostHog from the `previousPlan` and `plan` properties. A trial converting to paid emits **nothing**: it is the same `planId` with the trial simply ended, so the plan-equality check returns early, and no previous trialing state is persisted anywhere to compare against (`trialEndsAt` comes from the live Autumn subscription, `platform_plan` has no trial column, and the customer state cache holds only balances).
+- **`flow.published` is emitted once, by `flowService`** — the browser capture in `flow-hooks.tsx` was removed when the service emit landed, because the two fired on exactly the same UI publishes. The service emit also counts publishes no user pressed Publish for: the connection-swap republish in `app-connection.handler.ts` and the git-sync project-release import both dispatch `LOCK_AND_PUBLISH`.
+- **A platform group's `name` only leaves Cloud** (`pickPlatformGroupPii`): a self-hosted platform name is usually the customer's company name, the same reason `pickTelemetryPii` exists. The group itself is still created on every edition, so `plan`, `createdAt` and `deployment` stay groupable off Cloud.
+- **Google and SAML emit `signed.in` only for a returning user**, in the `else` branch of the `signedUp` check, mirroring the password path where sign-up emits `signed.up` and only a later sign-in emits `signed.in`. Emitting it on every claim made SSO sign-in counts run high against password.
+
### Flow Failure Alerts (EE)
Email on flow-run failure. First failure per flowVersion per 24h window sends; rest suppressed via Redis counter `flow_fail_count:<flowVersionId>` (1-day TTL). Personal projects: single owner-only receiver toggle; team projects: any number of receivers. Platform admins can bulk sub/unsub across projects (max 5 concurrent). Receivers stored/compared lowercase. Edition check (`paidEditions`) in service, no plan flag. No Issues feature — email links straight to the run page. EE/Cloud only.
diff --git a/bun.lock b/bun.lock
index 2466e08667f..1f058068c03 100644
--- a/bun.lock
+++ b/bun.lock
@@ -165,7 +165,7 @@
},
"packages/core/shared": {
"name": "@activepieces/shared",
- "version": "0.177.0",
+ "version": "0.178.0",
"dependencies": {
"@activepieces/core-execution": "workspace:*",
"@activepieces/core-formula": "workspace:*",
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index 303ade598a5..83ebd6e2415 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.177.0",
+ "version": "0.178.0",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/core/common/telemetry.ts b/packages/core/shared/src/lib/core/common/telemetry.ts
index 7f0ca282d4e..de495f92ef6 100644
--- a/packages/core/shared/src/lib/core/common/telemetry.ts
+++ b/packages/core/shared/src/lib/core/common/telemetry.ts
@@ -28,6 +28,45 @@ type SignInSubmitted = {
method: 'email'
}
+type OnboardingCompleted = {
+ userId: UserId
+ platformId: string
+}
+
+type PlanChange = {
+ platformId: string
+ plan: string
+ previousPlan?: string
+}
+
+type CheckoutStarted = {
+ platformId: string
+ plan: string
+}
+
+type TrialStarted = {
+ platformId: string
+ plan: string
+ trialEndsAt: string
+}
+
+type InviteSent = {
+ platformId: string
+ type: 'platform' | 'project'
+ role?: string
+}
+
+type InviteAccepted = {
+ platformId: string
+ type: 'platform' | 'project'
+}
+
+type SalesHandoffClicked = {
+ featureKey?: string
+ plan?: string
+ surface: string
+}
+
type SignInFailed = {
errorCode: string
}
@@ -119,6 +158,15 @@ export enum TelemetryEventName {
PIECE_SELECTOR_SEARCH = 'piece.selector.search',
MCP_TOOL_CALLED = 'mcp.tool.called',
MCP_SERVER_CONNECTED = 'mcp.server.connected',
+ ONBOARDING_COMPLETED = 'onboarding.completed',
+ CHECKOUT_STARTED = 'checkout.started',
+ PLAN_CHANGED = 'plan.changed',
+ PLAN_CANCELLED = 'plan.cancelled',
+ PLAN_REACTIVATED = 'plan.reactivated',
+ TRIAL_STARTED = 'trial.started',
+ INVITE_SENT = 'invite.sent',
+ INVITE_ACCEPTED = 'invite.accepted',
+ SALES_HANDOFF_CLICKED = 'sales.handoff.clicked',
}
export type TelemetryEvent =
@@ -142,8 +190,24 @@ export type TelemetryEvent =
| BaseTelemetryEvent<TelemetryEventName.PIECE_SELECTOR_SEARCH, PieceSelectorSearch>
| BaseTelemetryEvent<TelemetryEventName.MCP_TOOL_CALLED, McpToolCalled>
| BaseTelemetryEvent<TelemetryEventName.MCP_SERVER_CONNECTED, McpServerConnected>
+ | BaseTelemetryEvent<TelemetryEventName.ONBOARDING_COMPLETED, OnboardingCompleted>
+ | BaseTelemetryEvent<TelemetryEventName.CHECKOUT_STARTED, CheckoutStarted>
+ | BaseTelemetryEvent<TelemetryEventName.PLAN_CHANGED, PlanChange>
+ | BaseTelemetryEvent<TelemetryEventName.PLAN_CANCELLED, PlanChange>
+ | BaseTelemetryEvent<TelemetryEventName.PLAN_REACTIVATED, PlanChange>
+ | BaseTelemetryEvent<TelemetryEventName.TRIAL_STARTED, TrialStarted>
+ | BaseTelemetryEvent<TelemetryEventName.INVITE_SENT, InviteSent>
+ | BaseTelemetryEvent<TelemetryEventName.INVITE_ACCEPTED, InviteAccepted>
+ | BaseTelemetryEvent<TelemetryEventName.SALES_HANDOFF_CLICKED, SalesHandoffClicked>
export const CLOUD_ONLY_TELEMETRY_EVENTS: ReadonlySet<TelemetryEventName> = new Set([
+ TelemetryEventName.ONBOARDING_COMPLETED,
+ TelemetryEventName.CHECKOUT_STARTED,
+ TelemetryEventName.PLAN_CHANGED,
+ TelemetryEventName.PLAN_CANCELLED,
+ TelemetryEventName.PLAN_REACTIVATED,
+ TelemetryEventName.TRIAL_STARTED,
+ TelemetryEventName.SALES_HANDOFF_CLICKED,
TelemetryEventName.SIGNED_UP,
TelemetryEventName.SIGNED_IN,
TelemetryEventName.SIGN_UP_SUBMITTED,
@@ -160,3 +224,9 @@ export const CLOUD_ONLY_TELEMETRY_EVENTS: ReadonlySet<TelemetryEventName> = new
])
export const isCloudOnlyTelemetryEvent = (name: TelemetryEventName): boolean => CLOUD_ONLY_TELEMETRY_EVENTS.has(name)
+
+export enum DeploymentKind {
+ CLOUD = 'cloud',
+ SELF_HOSTED = 'self_hosted',
+ DEV = 'dev',
+}
diff --git a/packages/server/api/src/app/authentication/authentication.controller.ts b/packages/server/api/src/app/authentication/authentication.controller.ts
index 6d2d4340e78..72f3d54c81b 100644
--- a/packages/server/api/src/app/authentication/authentication.controller.ts
+++ b/packages/server/api/src/app/authentication/authentication.controller.ts
@@ -123,6 +123,17 @@ export const authenticationController: FastifyPluginAsyncZod = async (
method: attributionUtils.signUpMethodFromProvider({ provider }),
attribution: request.body.attribution,
}), request.log)
+ rejectedPromiseHandler(telemetry(request.log).trackUser({
+ userId: response.id,
+ platformId: response.platformId,
+ event: {
+ name: TelemetryEventName.ONBOARDING_COMPLETED,
+ payload: {
+ userId: response.id,
+ platformId: response.platformId,
+ },
+ },
+ }), request.log)
}
return response
diff --git a/packages/server/api/src/app/authentication/passwordless-auth.service.ts b/packages/server/api/src/app/authentication/passwordless-auth.service.ts
index 18b536ea803..bdf0fdb6f03 100644
--- a/packages/server/api/src/app/authentication/passwordless-auth.service.ts
+++ b/packages/server/api/src/app/authentication/passwordless-auth.service.ts
@@ -1,6 +1,6 @@
import { ActivepiecesError, ErrorCode, isNil } from '@activepieces/core-utils'
import { cryptoUtils } from '@activepieces/server-utils'
-import { ApFlagId, OtpType, TelemetryEventName, UserIdentity, UserIdentityProvider } from '@activepieces/shared'
+import { ApFlagId, OtpType, TelemetryEvent, TelemetryEventName, UserIdentity, UserIdentityProvider } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { flagService } from '../flags/flag.service'
import { rejectedPromiseHandler } from '../helper/promise-handler'
@@ -85,13 +85,14 @@ export const passwordlessAuthService = (log: FastifyBaseLogger) => ({
const preferredPlatformId = isNil(platformId)
? await authenticationService(log).selectCloudSignInPlatformId({ identityId: verifiedIdentity.id })
: platformId
- rejectedPromiseHandler(telemetry(log).trackIdentity({
+ rejectedPromiseHandler(trackForIdentity({
identityId: verifiedIdentity.id,
platformId: preferredPlatformId,
event: {
name: TelemetryEventName.EMAIL_CODE_VERIFIED,
payload: { needsNameStep: isNil(preferredPlatformId) },
},
+ log,
}), log)
if (!isNil(platformId)) {
@@ -106,6 +107,7 @@ export const passwordlessAuthService = (log: FastifyBaseLogger) => ({
identity: verifiedIdentity,
platformId,
})
+ rejectedPromiseHandler(telemetry(log).aliasIdentity({ identityId: verifiedIdentity.id, userId: user.id, platformId }), log)
await userInvitationsService(log).provisionUserInvitation({ email })
const response = await authenticationUtils(log).getProjectAndToken({
userId: user.id,
@@ -121,6 +123,7 @@ export const passwordlessAuthService = (log: FastifyBaseLogger) => ({
identity: verifiedIdentity,
platformId: preferredPlatformId,
})
+ rejectedPromiseHandler(telemetry(log).aliasIdentity({ identityId: verifiedIdentity.id, userId: user.id, platformId: preferredPlatformId }), log)
const response = await authenticationUtils(log).getProjectAndToken({
userId: user.id,
platformId: preferredPlatformId,
@@ -153,16 +156,26 @@ async function trackEmailCodeRequested({ identityId, platformId, isNewIdentity,
const preferredPlatformId = isNil(platformId)
? await authenticationService(log).selectCloudSignInPlatformId({ identityId })
: platformId
- await telemetry(log).trackIdentity({
+ await trackForIdentity({
identityId,
platformId: preferredPlatformId,
event: {
name: TelemetryEventName.EMAIL_CODE_REQUESTED,
payload: { isNewIdentity },
},
+ log,
})
}
+async function trackForIdentity({ identityId, platformId, event, log }: TrackForIdentityParams): Promise<void> {
+ const user = isNil(platformId) ? null : await userService(log).getOneByIdentityAndPlatform({ identityId, platformId })
+ if (!isNil(user) && !isNil(platformId)) {
+ await telemetry(log).trackUser({ userId: user.id, platformId, event })
+ return
+ }
+ await telemetry(log).trackIdentity({ identityId, platformId, event })
+}
+
async function assertPlatformAuthIsOpenTo({ email, platformId, log }: PlatformGateParams): Promise<void> {
await authenticationUtils(log).assertEmailAuthIsEnabled({
platformId,
@@ -190,6 +203,13 @@ type TrackEmailCodeRequestedParams = {
log: FastifyBaseLogger
}
+type TrackForIdentityParams = {
+ identityId: string
+ platformId: string | null
+ event: TelemetryEvent
+ log: FastifyBaseLogger
+}
+
type RequestCodeParams = {
email: string
platformId: string | null
diff --git a/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.ts b/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.ts
index 40471087639..85670ea5c61 100644
--- a/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.ts
+++ b/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.ts
@@ -1,5 +1,5 @@
import { isNil } from '@activepieces/core-utils'
-import { ApplicationEventName, ClaimTokenRequest, SignUpMethod, ThirdPartyAuthnProviderEnum } from '@activepieces/shared'
+import { ApplicationEventName, ClaimTokenRequest, SignUpMethod, TelemetryEventName, ThirdPartyAuthnProviderEnum } from '@activepieces/shared'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { z } from 'zod'
import { securityAccess } from '../../../core/security/authorization/fastify-security'
@@ -51,6 +51,19 @@ const federatedAuthnController: FastifyPluginAsyncZod = async (app) => {
attribution: req.body.attribution,
}), req.log)
}
+ else if (!isNil(response.platformId)) {
+ rejectedPromiseHandler(telemetry(req.log).trackUser({
+ userId: response.id,
+ platformId: response.platformId,
+ event: {
+ name: TelemetryEventName.SIGNED_IN,
+ payload: {
+ userId: response.id,
+ platformId: response.platformId,
+ },
+ },
+ }), req.log)
+ }
return response
})
}
diff --git a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-controller.ts b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-controller.ts
index 97a6321cfae..8cc16f2f2d3 100644
--- a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-controller.ts
+++ b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-controller.ts
@@ -1,12 +1,14 @@
import { assertNotNullOrUndefined } from '@activepieces/core-utils'
-import { ApplicationEventName, PrincipalType } from '@activepieces/shared'
+import { ApplicationEventName, PrincipalType, TelemetryEventName } from '@activepieces/shared'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { z } from 'zod'
import { securityAccess } from '../../../core/security/authorization/fastify-security'
import { applicationEvents } from '../../../helper/application-events'
import { networkUtils } from '../../../helper/network-utils'
+import { rejectedPromiseHandler } from '../../../helper/promise-handler'
import { system } from '../../../helper/system/system'
import { AppSystemProp } from '../../../helper/system/system-props'
+import { telemetry } from '../../../helper/telemetry.utils'
import { platformUtils } from '../../../platform/platform.utils'
import { platformMustHaveFeatureEnabled } from '../ee-authorization'
import { authnSsoSamlService } from './authn-sso-saml-service'
@@ -43,6 +45,17 @@ export const authnSsoSamlController: FastifyPluginAsyncZod = async (app) => {
source: 'sso',
},
})
+ rejectedPromiseHandler(telemetry(req.log).trackUser({
+ userId: response.id,
+ platformId,
+ event: {
+ name: TelemetryEventName.SIGNED_IN,
+ payload: {
+ userId: response.id,
+ platformId,
+ },
+ },
+ }), req.log)
return res.redirect(url.toString())
})
diff --git a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts
index e67ac8f9f6b..c368b506457 100644
--- a/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts
+++ b/packages/server/api/src/app/ee/flows/flow-approval/flow-approval-request.service.ts
@@ -1,4 +1,4 @@
-import { ActivepiecesError, apId, ApId, ApplicationEventName, Cursor, ErrorCode, Flow, FlowApprovalRequest, FlowApprovalRequestState, FlowOperationType, FlowStatus, FlowVersionState, isNil, PlatformId, PopulatedFlowApprovalRequest, Principal, PrincipalType, ProjectId, SeekPage, UserId } from '@activepieces/shared'
+import { ActivepiecesError, apId, ApId, ApplicationEventName, Cursor, ErrorCode, Flow, FlowApprovalRequest, FlowApprovalRequestState, FlowOperationType, FlowStatus, FlowVersionState, isNil, PlatformId, PopulatedFlowApprovalRequest, Principal, PrincipalType, ProjectId, SeekPage, TelemetryEventName, UserId } from '@activepieces/shared'
import { FastifyBaseLogger, FastifyRequest } from 'fastify'
import { repoFactory } from '../../../core/db/repo-factory'
import { transaction } from '../../../core/db/transaction'
@@ -9,6 +9,8 @@ import { applicationEvents } from '../../../helper/application-events'
import { buildPaginator } from '../../../helper/pagination/build-paginator'
import { paginationHelper } from '../../../helper/pagination/pagination-utils'
import { Order } from '../../../helper/pagination/paginator'
+import { rejectedPromiseHandler } from '../../../helper/promise-handler'
+import { telemetry } from '../../../helper/telemetry.utils'
import { triggerSourceService } from '../../../trigger/trigger-source/trigger-source-service'
import { FlowApprovalRequestEntity } from './flow-approval-request.entity'
@@ -124,6 +126,13 @@ export const flowApprovalRequestService = (log: FastifyBaseLogger) => ({
projectId: approval.projectId,
newStatus: approval.requestedStatus,
})
+ rejectedPromiseHandler(telemetry(log).trackProject({
+ projectId: approval.projectId,
+ event: {
+ name: TelemetryEventName.FLOW_PUBLISHED,
+ payload: { flowId: flow.id },
+ },
+ }), log)
applicationEvents(log).sendUserEvent(request, {
action: ApplicationEventName.FLOW_APPROVAL_GRANTED,
data: {
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.ts
index 6dc59a97d44..9e5005a7ff3 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
@@ -23,7 +23,8 @@ import { AppSystemProp } from '../../../../helper/system/system-props'
import { AppSumoAction, CancellationFeedback, CreditUsage, CreditUsageSource } from '../../../../platform/billing-provider'
import { platformService } from '../../../../platform/platform.service'
import { userService } from '../../../../user/user-service'
-import { platformPlanService } from '../platform-plan.service'
+import { platformPlanTelemetry } from '../platform-plan-telemetry'
+import { platformPlanRepo, platformPlanService } from '../platform-plan.service'
const AUTUMN_CONSOLE_URL = system.getOrThrow(AppSystemProp.AUTUMN_CONSOLE_URL).replace(/\/+$/, '')
const edition = system.getEdition()
@@ -162,10 +163,18 @@ export const autumnUtils = {
}
const customer = await client.getCustomer({ expand: ['subscriptions.plan', 'purchases.plan'] })
const entitlements = toAutumnEntitlements(customer)
+ const previousPlan = await platformPlanRepo().findOneBy({ platformId })
await platformPlanService(log).update({ platformId, ...autumnUtils.mapAutumnFeaturesToPlatformPlan(entitlements) })
await autumnUtils.writeCustomerStateCaches({ platformId, customer, grantedFeatureIds: entitlements.grantedFeatureIds })
await autumnUtils.invalidateBillingOverview(platformId)
await autumnUtils.provisionLicenseKeyIfPaid(log, platformId, entitlements.planId)
+ const currentSubscription = autumnUtils.selectCurrentBaseSubscription(autumnUtils.toBaseSubscriptions(customer))
+ rejectedPromiseHandler(platformPlanTelemetry(log).onEntitlementsRefreshed({
+ platformId,
+ previousPlan: previousPlan?.plan ?? null,
+ plan: entitlements.planId,
+ trialEndsAt: isNil(currentSubscription?.trialEndsAt) ? null : new Date(currentSubscription.trialEndsAt).toISOString(),
+ }), log)
},
async provisionLicenseKeyIfPaid(log: FastifyBaseLogger, platformId: string, planId: string | null): Promise<void> {
if (isNil(planId) || planId === PlanName.FREE || planId === PlanName.APPSUMO || planId === PlanName.FREE_LEGACY) {
diff --git a/packages/server/api/src/app/ee/platform/platform-plan/platform-plan-telemetry.ts b/packages/server/api/src/app/ee/platform/platform-plan/platform-plan-telemetry.ts
new file mode 100644
index 00000000000..65de4577258
--- /dev/null
+++ b/packages/server/api/src/app/ee/platform/platform-plan/platform-plan-telemetry.ts
@@ -0,0 +1,122 @@
+import { isNil } from '@activepieces/core-utils'
+import { PlanName, TelemetryEventName } from '@activepieces/shared'
+import { FastifyBaseLogger } from 'fastify'
+import { distributedStore } from '../../../database/redis-connections'
+import { telemetry } from '../../../helper/telemetry.utils'
+import { platformService } from '../../../platform/platform.service'
+import { platformPlanRepo } from './platform-plan.service'
+
+export const platformPlanTelemetry = (log: FastifyBaseLogger) => ({
+ async onCheckoutStarted({ platformId, planId }: CheckoutStartedParams): Promise<void> {
+ await telemetry(log).trackPlatform({
+ platformId,
+ event: {
+ name: TelemetryEventName.CHECKOUT_STARTED,
+ payload: { platformId, plan: planId },
+ },
+ })
+ },
+
+ async onCancelled({ platformId }: PlanActionParams): Promise<void> {
+ const plan = await currentPlanName({ platformId })
+ await telemetry(log).trackPlatform({
+ platformId,
+ event: {
+ name: TelemetryEventName.PLAN_CANCELLED,
+ payload: { platformId, plan },
+ },
+ })
+ },
+
+ async onReactivated({ platformId }: PlanActionParams): Promise<void> {
+ const plan = await currentPlanName({ platformId })
+ await telemetry(log).trackPlatform({
+ platformId,
+ event: {
+ name: TelemetryEventName.PLAN_REACTIVATED,
+ payload: { platformId, plan },
+ },
+ })
+ },
+
+ async onEntitlementsRefreshed({ platformId, previousPlan, plan, trialEndsAt }: EntitlementsRefreshedParams): Promise<void> {
+ if (plan === previousPlan) {
+ return
+ }
+ const platform = await platformService(log).getOneOrThrow(platformId)
+ await telemetry(log).identifyPlatformGroup({
+ platformId,
+ properties: { name: platform.name, plan, createdAt: platform.created },
+ })
+ if (isNil(plan) || FREE_PLANS.has(plan)) {
+ return
+ }
+ await distributedStore.runOnceWithin(
+ planChangeKey({ platformId, previousPlan, plan }),
+ PLAN_CHANGE_ONCE_SECONDS,
+ () => trackPlanChange({ platformId, previousPlan, plan, trialEndsAt, log }),
+ )
+ },
+})
+
+async function trackPlanChange({ platformId, previousPlan, plan, trialEndsAt, log }: TrackPlanChangeParams): Promise<void> {
+ const trialing = !isNil(trialEndsAt) && new Date(trialEndsAt).getTime() > Date.now()
+ if (trialing) {
+ await telemetry(log).trackPlatform({
+ platformId,
+ event: {
+ name: TelemetryEventName.TRIAL_STARTED,
+ payload: { platformId, plan, trialEndsAt },
+ },
+ })
+ return
+ }
+ await telemetry(log).trackPlatform({
+ platformId,
+ event: {
+ name: TelemetryEventName.PLAN_CHANGED,
+ payload: { platformId, plan, previousPlan: previousPlan ?? undefined },
+ },
+ })
+}
+
+function planChangeKey({ platformId, previousPlan, plan }: PlanChangeKeyParams): string {
+ return `telemetry:plan-change:${platformId}:${previousPlan ?? 'none'}:${plan}`
+}
+
+async function currentPlanName({ platformId }: PlanActionParams): Promise<string> {
+ const platformPlan = await platformPlanRepo().findOneBy({ platformId })
+ return platformPlan?.plan ?? UNKNOWN_PLAN
+}
+
+const UNKNOWN_PLAN = 'unknown'
+
+const PLAN_CHANGE_ONCE_SECONDS = 24 * 60 * 60
+
+const FREE_PLANS: ReadonlySet<string> = new Set([PlanName.FREE, PlanName.FREE_LEGACY, PlanName.APPSUMO])
+
+type PlanActionParams = {
+ platformId: string
+}
+
+type CheckoutStartedParams = PlanActionParams & {
+ planId: string
+}
+
+type EntitlementsRefreshedParams = {
+ platformId: string
+ previousPlan: string | null
+ plan: string | null
+ trialEndsAt: string | null
+}
+
+type PlanChangeKeyParams = {
+ platformId: string
+ previousPlan: string | null
+ plan: string
+}
+
+type TrackPlanChangeParams = PlanChangeKeyParams & {
+ trialEndsAt: string | null
+ log: FastifyBaseLogger
+}
diff --git a/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.controller.ts b/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.controller.ts
index f3feaabf649..689dbc8b67a 100644
--- a/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.controller.ts
+++ b/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.controller.ts
@@ -7,9 +7,11 @@ import { z } from 'zod'
import { securityAccess } from '../../../core/security/authorization/fastify-security'
import { getEntitlementsForceRefreshKey } from '../../../database/redis/keys'
import { distributedStore } from '../../../database/redis-connections'
+import { rejectedPromiseHandler } from '../../../helper/promise-handler'
import { billingProvider } from '../../../platform/billing-provider'
import { platformService } from '../../../platform/platform.service'
import { userService } from '../../../user/user-service'
+import { platformPlanTelemetry } from './platform-plan-telemetry'
import { platformPlanService } from './platform-plan.service'
const FORCE_REFRESH_DEDUP_SECONDS = 60
@@ -54,6 +56,7 @@ export const platformPlanController: FastifyPluginAsyncZod = async (app) => {
planId: request.body.planId,
successUrl: request.body.successUrl,
})
+ rejectedPromiseHandler(platformPlanTelemetry(request.log).onCheckoutStarted({ platformId, planId: request.body.planId }), request.log)
await refreshWhenAppliedImmediately({ log: request.log, platformId, checkoutUrl: result.checkoutUrl })
return result
})
@@ -69,6 +72,7 @@ export const platformPlanController: FastifyPluginAsyncZod = async (app) => {
canceledByEmail: await resolveActorEmail(request.log, request.principal.id),
},
})
+ rejectedPromiseHandler(platformPlanTelemetry(request.log).onCancelled({ platformId }), request.log)
await provider.refreshEntitlements(platformId)
})
@@ -76,6 +80,7 @@ export const platformPlanController: FastifyPluginAsyncZod = async (app) => {
const platformId = request.principal.platform.id
const provider = billingProvider.get(request.log)
await provider.reactivateSubscription({ platformId })
+ rejectedPromiseHandler(platformPlanTelemetry(request.log).onReactivated({ platformId }), request.log)
await provider.refreshEntitlements(platformId)
})
diff --git a/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.service.ts b/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.service.ts
index e4656264276..bc341fe6a12 100644
--- a/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.service.ts
+++ b/packages/server/api/src/app/ee/platform/platform-plan/platform-plan.service.ts
@@ -55,9 +55,10 @@ export const platformPlanService = (log: FastifyBaseLogger) => ({
return platformPlan
},
- async onPlatformCreated(platformId: string): Promise<void> {
- await createInitialBilling(platformId)
+ async onPlatformCreated(platformId: string): Promise<PlatformPlan> {
+ const platformPlan = await createInitialBilling(platformId)
await enrollBillingProviderOnCreate(platformId, log)
+ return platformPlan
},
async update(params: UpdatePlatformBillingParams): Promise<PlatformPlan> {
diff --git a/packages/server/api/src/app/flows/flow/flow.service.ts b/packages/server/api/src/app/flows/flow/flow.service.ts
index 8a5af5b4700..9a4dc341685 100644
--- a/packages/server/api/src/app/flows/flow/flow.service.ts
+++ b/packages/server/api/src/app/flows/flow/flow.service.ts
@@ -524,6 +524,13 @@ export const flowService = (log: FastifyBaseLogger) => ({
})
const { websocketService } = await import('../../core/websockets.service')
websocketService.notifyWorkers().flowPublished({ flowId: publishedFlow.id, flowVersionId: publishedFlow.version.id, projectId: publishedFlow.projectId })
+ rejectedPromiseHandler(telemetry(log).trackProject({
+ projectId,
+ event: {
+ name: TelemetryEventName.FLOW_PUBLISHED,
+ payload: { flowId: id },
+ },
+ }), log)
return publishedFlow
},
diff --git a/packages/server/api/src/app/helper/telemetry.utils.ts b/packages/server/api/src/app/helper/telemetry.utils.ts
index b491aa3a6e7..3dfd1bc999f 100644
--- a/packages/server/api/src/app/helper/telemetry.utils.ts
+++ b/packages/server/api/src/app/helper/telemetry.utils.ts
@@ -1,6 +1,6 @@
import { AIProviderName, isNil, ProjectId, spreadIfDefined, UserId } from '@activepieces/core-utils'
import { apVersionUtil } from '@activepieces/server-utils'
-import { ApEdition, AppInstance, AttributionParams, attributionUtils, DeploymentConfig, FlowRunStatus, GetDiagnosticsResponse, GetSystemHealthChecksResponse, isCloudOnlyTelemetryEvent, MachineInformation, pickTelemetryPii, RunEnvironment, SignUpMethod, TelemetryEvent, User, UserIdentity } from '@activepieces/shared'
+import { ApEdition, ApEnvironment, AppInstance, AttributionParams, attributionUtils, DeploymentConfig, DeploymentKind, FlowRunStatus, GetDiagnosticsResponse, GetSystemHealthChecksResponse, isCloudOnlyTelemetryEvent, MachineInformation, pickTelemetryPii, RunEnvironment, SignUpMethod, TelemetryEvent, User, UserIdentity } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { PostHog } from 'posthog-node'
import { platformConfigurationService } from '../platform/platform-configuration.service'
@@ -57,6 +57,30 @@ export const telemetry = (log: FastifyBaseLogger) => ({
},
})
},
+ async aliasIdentity({ identityId, userId, platformId }: AliasIdentityParams): Promise<void> {
+ if (system.getEdition() !== ApEdition.CLOUD) {
+ return
+ }
+ if (!await platformConfigurationService(log).isProductTelemetryEnabled({ platformId })) {
+ return
+ }
+ getPostHog().alias({ distinctId: userId, alias: identityId })
+ },
+ async identifyPlatformGroup({ platformId, properties }: IdentifyPlatformGroupParams): Promise<void> {
+ if (!await platformConfigurationService(log).isProductTelemetryEnabled({ platformId })) {
+ return
+ }
+ getPostHog().groupIdentify({
+ groupType: PLATFORM_GROUP_TYPE,
+ groupKey: platformId,
+ properties: {
+ ...pickPlatformGroupPii(properties),
+ plan: properties.plan,
+ createdAt: properties.createdAt,
+ deployment: getDeploymentKind(),
+ },
+ })
+ },
async trackPlatform({ platformId, event }: TrackPlatformParams): Promise<void> {
if (!await platformConfigurationService(log).isProductTelemetryEnabled({ platformId })) {
return
@@ -149,10 +173,30 @@ async function getMetadata() {
activepiecesVersion: currentVersion,
activepiecesEnvironment: system.get(AppSystemProp.ENVIRONMENT),
activepiecesEdition: edition,
+ deployment: getDeploymentKind(),
source_site: 'product',
}
}
+function pickPlatformGroupPii(properties: PlatformGroupProperties): { name?: string } {
+ if (system.getEdition() !== ApEdition.CLOUD) {
+ return {}
+ }
+ return { name: properties.name }
+}
+
+function getDeploymentKind(): DeploymentKind {
+ if (system.getEdition() === ApEdition.CLOUD) {
+ return DeploymentKind.CLOUD
+ }
+ if (system.get(AppSystemProp.ENVIRONMENT) === ApEnvironment.DEVELOPMENT) {
+ return DeploymentKind.DEV
+ }
+ return DeploymentKind.SELF_HOSTED
+}
+
+const PLATFORM_GROUP_TYPE = 'platform'
+
export enum LicenseKeyPostHogEvents {
AI_USAGE_PER_RUN = 'ai_usage_per_run',
CHAT_MESSAGE = 'chat_message',
@@ -242,6 +286,23 @@ type IdentifySignUpParams = {
attribution: AttributionParams | undefined
}
+type AliasIdentityParams = {
+ identityId: string
+ userId: UserId
+ platformId: string
+}
+
+export type PlatformGroupProperties = {
+ name: string
+ plan: string | null
+ createdAt: string
+}
+
+type IdentifyPlatformGroupParams = {
+ platformId: string
+ properties: PlatformGroupProperties
+}
+
type TrackPlatformParams = {
platformId: string
event: TelemetryEvent
diff --git a/packages/server/api/src/app/platform/platform.service.ts b/packages/server/api/src/app/platform/platform.service.ts
index 8c9cfaa686b..4fa1c71567f 100644
--- a/packages/server/api/src/app/platform/platform.service.ts
+++ b/packages/server/api/src/app/platform/platform.service.ts
@@ -11,6 +11,7 @@ import { platformPlanService } from '../ee/platform/platform-plan/platform-plan.
import { defaultTheme } from '../flags/theme'
import { rejectedPromiseHandler } from '../helper/promise-handler'
import { system } from '../helper/system/system'
+import { telemetry } from '../helper/telemetry.utils'
import { projectService } from '../project/project-service'
import { userService } from '../user/user-service'
import { billingProvider } from './billing-provider'
@@ -73,7 +74,14 @@ export const platformService = (log: FastifyBaseLogger) => ({
platformId: savedPlatform.id,
})
- await platformPlanService(log).onPlatformCreated(savedPlatform.id)
+ const platformPlan = await platformPlanService(log).onPlatformCreated(savedPlatform.id)
+ const { error: telemetryError } = await tryCatch(() => telemetry(log).identifyPlatformGroup({
+ platformId: savedPlatform.id,
+ properties: { name: savedPlatform.name, plan: platformPlan.plan ?? null, createdAt: savedPlatform.created },
+ }))
+ if (!isNil(telemetryError)) {
+ log.warn({ error: telemetryError, platform: { id: savedPlatform.id } }, 'Failed to identify the platform group')
+ }
log.info({ platform: { id: savedPlatform.id }, ownerId }, 'Platform created')
return stripFederatedAuth(savedPlatform)
@@ -113,7 +121,7 @@ export const platformService = (log: FastifyBaseLogger) => ({
if (invalidatePreviousTokens) {
await rotateTokenVersion(identityId)
}
- await reportSignup({ identityId, user: owner, projectId: personalProject.id, log })
+ await reportSignup({ identityId, user: owner, platformId: platform.id, projectId: personalProject.id, log })
const response = await authenticationUtils(log).getProjectAndToken({
userId: owner.id,
platformId: platform.id,
@@ -301,17 +309,18 @@ async function linkOwnerToPlatform({ ownerId, platformId, identityId, name, inva
log,
})
if (!isNil(response.projectId)) {
- rejectedPromiseHandler(reportSignup({ identityId, user: owner, projectId: response.projectId, log }), log)
+ rejectedPromiseHandler(reportSignup({ identityId, user: owner, platformId, projectId: response.projectId, log }), log)
}
return { response, provisioned: true }
}
-async function reportSignup({ identityId, user, projectId, log }: ReportSignupParams): Promise<void> {
+async function reportSignup({ identityId, user, platformId, projectId, log }: ReportSignupParams): Promise<void> {
await authenticationUtils(log).sendTelemetry({
identity: await userIdentityService(log).getOneOrFail({ id: identityId }),
user,
projectId,
})
+ rejectedPromiseHandler(telemetry(log).aliasIdentity({ identityId, userId: user.id, platformId }), log)
}
function isSameTokenVersion(current: string | undefined, caller: string | undefined): boolean {
@@ -461,6 +470,7 @@ type FinishExistingPlatformParams = {
type ReportSignupParams = {
identityId: string
user: User
+ platformId: string
projectId: string
log: FastifyBaseLogger
}
diff --git a/packages/server/api/src/app/user-invitations/user-invitation.module.ts b/packages/server/api/src/app/user-invitations/user-invitation.module.ts
index 05648a7956a..fec93c87f7e 100644
--- a/packages/server/api/src/app/user-invitations/user-invitation.module.ts
+++ b/packages/server/api/src/app/user-invitations/user-invitation.module.ts
@@ -1,5 +1,5 @@
import { ActivepiecesError, assertNotNullOrUndefined, ErrorCode, isNil, Permission, ProjectRole, SeekPage } from '@activepieces/core-utils'
-import { InvitationStatus, InvitationType, ListUserInvitationsRequest, Principal, PrincipalType, SendUserInvitationRequest, SERVICE_KEY_SECURITY_OPENAPI, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'
+import { InvitationStatus, InvitationType, ListUserInvitationsRequest, Principal, PrincipalType, SendUserInvitationRequest, SERVICE_KEY_SECURITY_OPENAPI, TelemetryEvent, TelemetryEventName, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'
import { FastifyBaseLogger, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { StatusCodes } from 'http-status-codes'
@@ -12,6 +12,8 @@ import { platformMustBeOwnedByCurrentUser, platformMustHaveFeatureEnabled, proje
import { assertRoleHasPermission } from '../ee/authentication/project-role/rbac-middleware'
import { platformPlanService } from '../ee/platform/platform-plan/platform-plan.service'
import { projectRoleService } from '../ee/projects/project-role/project-role.service'
+import { rejectedPromiseHandler } from '../helper/promise-handler'
+import { telemetry } from '../helper/telemetry.utils'
import { projectService } from '../project/project-service'
import { userService } from '../user/user-service'
import { INVITATION_EXPIRY_SECONDS, userInvitationsService } from './user-invitation.service'
@@ -64,6 +66,19 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {
userInvitation: userInvitationRecord,
invitationExpirySeconds: INVITATION_EXPIRY_SECONDS,
})
+ rejectedPromiseHandler(trackInviteSent({
+ principal: request.principal,
+ platformId,
+ event: {
+ name: TelemetryEventName.INVITE_SENT,
+ payload: {
+ platformId,
+ type: type === InvitationType.PLATFORM ? 'platform' : 'project',
+ role: type === InvitationType.PLATFORM ? request.body.platformRole ?? undefined : projectRole?.name,
+ },
+ },
+ log: request.log,
+ }), request.log)
await reply.status(StatusCodes.CREATED).send(invitation)
})
@@ -185,6 +200,14 @@ async function assertPrincipalHasPermissionToProject<R extends Principal & { pla
}
+async function trackInviteSent({ principal, platformId, event, log }: TrackInviteSentParams): Promise<void> {
+ if (principal.type === PrincipalType.USER) {
+ await telemetry(log).trackUser({ userId: principal.id, platformId, event })
+ return
+ }
+ await telemetry(log).trackPlatform({ platformId, event })
+}
+
const ListUserInvitationsRequestParams = {
config: {
security: securityAccess.publicPlatform([PrincipalType.USER, PrincipalType.SERVICE], {
@@ -245,3 +268,10 @@ const UpsertUserInvitationRequestParams = {
},
},
}
+
+type TrackInviteSentParams = {
+ principal: Principal
+ platformId: string
+ event: TelemetryEvent
+ log: FastifyBaseLogger
+}
diff --git a/packages/server/api/src/app/user-invitations/user-invitation.service.ts b/packages/server/api/src/app/user-invitations/user-invitation.service.ts
index 71e345be23b..77ac9d4b385 100644
--- a/packages/server/api/src/app/user-invitations/user-invitation.service.ts
+++ b/packages/server/api/src/app/user-invitations/user-invitation.service.ts
@@ -1,5 +1,5 @@
import { ActivepiecesError, apId, assertEqual, assertNotNullOrUndefined, ErrorCode, isNil, SeekPage, spreadIfDefined } from '@activepieces/core-utils'
-import { InvitationStatus, InvitationType, PlatformRole, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'
+import { InvitationStatus, InvitationType, PlatformRole, TelemetryEventName, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'
import dayjs from 'dayjs'
import { FastifyBaseLogger } from 'fastify'
import { EntityManager, IsNull, ObjectLiteral, SelectQueryBuilder } from 'typeorm'
@@ -13,6 +13,8 @@ import { domainHelper } from '../helper/domain-helper'
import { JwtAudience, jwtUtils } from '../helper/jwt-utils'
import { buildPaginator } from '../helper/pagination/build-paginator'
import { paginationHelper } from '../helper/pagination/pagination-utils'
+import { rejectedPromiseHandler } from '../helper/promise-handler'
+import { telemetry } from '../helper/telemetry.utils'
import { platformService } from '../platform/platform.service'
import { projectService } from '../project/project-service'
import { userService } from '../user/user-service'
@@ -235,9 +237,22 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({
},
async accept({ invitationId, platformId }: AcceptParams): Promise<AcceptResult> {
const invitation = await this.getOneOrThrow({ id: invitationId, platformId })
+ const firstAcceptance = invitation.status !== InvitationStatus.ACCEPTED
await repo().update(invitation.id, {
status: InvitationStatus.ACCEPTED,
})
+ if (firstAcceptance) {
+ rejectedPromiseHandler(telemetry(log).trackPlatform({
+ platformId,
+ event: {
+ name: TelemetryEventName.INVITE_ACCEPTED,
+ payload: {
+ platformId,
+ type: invitation.type === InvitationType.PLATFORM ? 'platform' : 'project',
+ },
+ },
+ }), log)
+ }
const identity = await userIdentityService(log).getIdentityByEmail(invitation.email)
if (isNil(identity)) {
return { registered: false }
diff --git a/packages/server/api/test/integration/ce/platform/first-platform-provisioning.test.ts b/packages/server/api/test/integration/ce/platform/first-platform-provisioning.test.ts
index 62bb065e798..439b556767d 100644
--- a/packages/server/api/test/integration/ce/platform/first-platform-provisioning.test.ts
+++ b/packages/server/api/test/integration/ce/platform/first-platform-provisioning.test.ts
@@ -18,6 +18,8 @@ vi.mock('../../../../src/app/helper/telemetry.utils', async (importOriginal) =>
trackProject: vi.fn().mockResolvedValue(undefined),
trackIdentity: vi.fn().mockResolvedValue(undefined),
trackUser: vi.fn().mockResolvedValue(undefined),
+ aliasIdentity: vi.fn().mockResolvedValue(undefined),
+ identifyPlatformGroup: vi.fn().mockResolvedValue(undefined),
}),
}
})
diff --git a/packages/server/api/test/unit/app/authentication/passwordless-auth-telemetry.test.ts b/packages/server/api/test/unit/app/authentication/passwordless-auth-telemetry.test.ts
new file mode 100644
index 00000000000..c9214add7bf
--- /dev/null
+++ b/packages/server/api/test/unit/app/authentication/passwordless-auth-telemetry.test.ts
@@ -0,0 +1,125 @@
+import { TelemetryEventName } from '@activepieces/shared'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const {
+ mockTrackUser,
+ mockTrackIdentity,
+ mockGetIdentityByEmail,
+ mockGetOneByIdentityAndPlatform,
+ mockSelectCloudSignInPlatformId,
+} = vi.hoisted(() => ({
+ mockTrackUser: vi.fn().mockResolvedValue(undefined),
+ mockTrackIdentity: vi.fn().mockResolvedValue(undefined),
+ mockGetIdentityByEmail: vi.fn(),
+ mockGetOneByIdentityAndPlatform: vi.fn(),
+ mockSelectCloudSignInPlatformId: vi.fn(),
+}))
+
+vi.mock('../../../../src/app/authentication/lib/turnstile', () => ({
+ turnstile: { assertSolved: vi.fn().mockResolvedValue(undefined) },
+}))
+
+vi.mock('../../../../src/app/authentication/lib/zerobounce', () => ({
+ zerobounce: { maySignUp: vi.fn().mockResolvedValue(true) },
+}))
+
+vi.mock('../../../../src/app/authentication/otp/otp-service', () => ({
+ otpService: vi.fn(() => ({ createAndSend: vi.fn().mockResolvedValue(undefined) })),
+}))
+
+vi.mock('../../../../src/app/authentication/user-identity/user-identity-service', () => ({
+ userIdentityService: vi.fn(() => ({
+ getIdentityByEmail: mockGetIdentityByEmail,
+ create: vi.fn(),
+ })),
+}))
+
+vi.mock('../../../../src/app/user/user-service', () => ({
+ userService: vi.fn(() => ({ getOneByIdentityAndPlatform: mockGetOneByIdentityAndPlatform })),
+}))
+
+vi.mock('../../../../src/app/authentication/authentication.service', () => ({
+ authenticationService: vi.fn(() => ({ selectCloudSignInPlatformId: mockSelectCloudSignInPlatformId })),
+}))
+
+vi.mock('../../../../src/app/helper/telemetry.utils', () => ({
+ telemetry: vi.fn(() => ({ trackUser: mockTrackUser, trackIdentity: mockTrackIdentity })),
+}))
+
+import { passwordlessAuthService } from '../../../../src/app/authentication/passwordless-auth.service'
+
+const mockLog = {
+ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(),
+ child: vi.fn(), fatal: vi.fn(), trace: vi.fn(), silent: vi.fn(), level: 'info',
+} as unknown as Parameters<typeof passwordlessAuthService>[0]
+
+const EMAIL = '[email protected]'
+const IDENTITY = { id: 'identity-1', email: EMAIL }
+
+async function requestCodeAndFlush(): Promise<void> {
+ await passwordlessAuthService(mockLog).requestCode({
+ email: EMAIL,
+ platformId: null,
+ captchaToken: 'token',
+ remoteIp: '127.0.0.1',
+ })
+ await new Promise((resolve) => setImmediate(resolve))
+}
+
+describe('passwordless auth telemetry distinct id', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetIdentityByEmail.mockResolvedValue(IDENTITY)
+ mockSelectCloudSignInPlatformId.mockResolvedValue('platform-1')
+ })
+
+ it('keys the event on the identity id while no user exists yet', async () => {
+ mockGetOneByIdentityAndPlatform.mockResolvedValue(null)
+
+ await requestCodeAndFlush()
+
+ expect(mockTrackUser).not.toHaveBeenCalled()
+ expect(mockTrackIdentity).toHaveBeenCalledWith({
+ identityId: 'identity-1',
+ platformId: 'platform-1',
+ event: {
+ name: TelemetryEventName.EMAIL_CODE_REQUESTED,
+ payload: { isNewIdentity: false },
+ },
+ })
+ })
+
+ it('switches to the user id as soon as a user exists for identity and platform', async () => {
+ mockGetOneByIdentityAndPlatform.mockResolvedValue({ id: 'user-1' })
+
+ await requestCodeAndFlush()
+
+ expect(mockTrackIdentity).not.toHaveBeenCalled()
+ expect(mockTrackUser).toHaveBeenCalledWith({
+ userId: 'user-1',
+ platformId: 'platform-1',
+ event: {
+ name: TelemetryEventName.EMAIL_CODE_REQUESTED,
+ payload: { isNewIdentity: false },
+ },
+ })
+ })
+
+ it('keys the event on the identity id when no platform can be resolved', async () => {
+ mockSelectCloudSignInPlatformId.mockResolvedValue(null)
+ mockGetOneByIdentityAndPlatform.mockResolvedValue({ id: 'user-1' })
+
+ await requestCodeAndFlush()
+
+ expect(mockGetOneByIdentityAndPlatform).not.toHaveBeenCalled()
+ expect(mockTrackUser).not.toHaveBeenCalled()
+ expect(mockTrackIdentity).toHaveBeenCalledWith({
+ identityId: 'identity-1',
+ platformId: null,
+ event: {
+ name: TelemetryEventName.EMAIL_CODE_REQUESTED,
+ payload: { isNewIdentity: false },
+ },
+ })
+ })
+})
diff --git a/packages/server/api/test/unit/app/ee/platform-plan/free-legacy-comp.test.ts b/packages/server/api/test/unit/app/ee/platform-plan/free-legacy-comp.test.ts
index 4517f0d0431..0d1c0bcd401 100644
--- a/packages/server/api/test/unit/app/ee/platform-plan/free-legacy-comp.test.ts
+++ b/packages/server/api/test/unit/app/ee/platform-plan/free-legacy-comp.test.ts
@@ -30,6 +30,12 @@ vi.mock('../../../../../src/app/ee/platform/platform-plan/platform-plan.service'
}),
}))
+vi.mock('../../../../../src/app/ee/platform/platform-plan/platform-plan-telemetry', () => ({
+ platformPlanTelemetry: () => ({
+ onEntitlementsRefreshed: vi.fn(),
+ }),
+}))
+
vi.mock('../../../../../src/app/database/redis-connections', () => ({
distributedLock: () => ({
runExclusive: async ({ fn }: { fn: () => Promise<unknown> }) => fn(),
diff --git a/packages/server/api/test/unit/app/helper/telemetry-cloud-only-events.test.ts b/packages/server/api/test/unit/app/helper/telemetry-cloud-only-events.test.ts
index d97f963169a..594eebb3f5f 100644
--- a/packages/server/api/test/unit/app/helper/telemetry-cloud-only-events.test.ts
+++ b/packages/server/api/test/unit/app/helper/telemetry-cloud-only-events.test.ts
@@ -1,14 +1,15 @@
-import { ApEdition, TelemetryEventName } from '@activepieces/shared'
+import { ApEdition, TelemetryEvent, TelemetryEventName } from '@activepieces/shared'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { mockCapture, mockGetEdition, mockIsProductTelemetryEnabled } = vi.hoisted(() => ({
- mockCapture: vi.fn(),
+const { mockCapture, mockAlias, mockGetEdition, mockIsProductTelemetryEnabled } = vi.hoisted(() => ({
+ mockCapture: vi.fn<(message: CapturedMessage) => void>(),
+ mockAlias: vi.fn(),
mockGetEdition: vi.fn(),
mockIsProductTelemetryEnabled: vi.fn().mockResolvedValue(true),
}))
vi.mock('posthog-node', () => ({
- PostHog: vi.fn(() => ({ capture: mockCapture, identify: vi.fn(), flush: vi.fn(), shutdown: vi.fn() })),
+ PostHog: vi.fn(() => ({ capture: mockCapture, alias: mockAlias, identify: vi.fn(), groupIdentify: vi.fn(), flush: vi.fn(), shutdown: vi.fn() })),
}))
vi.mock('../../../../src/app/platform/platform-configuration.service', () => ({
@@ -18,11 +19,11 @@ vi.mock('../../../../src/app/platform/platform-configuration.service', () => ({
}))
vi.mock('../../../../src/app/platform/platform.service', () => ({
- platformService: vi.fn(() => ({ getOneOrThrow: vi.fn() })),
+ platformService: vi.fn(() => ({ getOneOrThrow: vi.fn().mockResolvedValue({ ownerId: 'owner-1' }) })),
}))
vi.mock('../../../../src/app/project/project-service', () => ({
- projectService: vi.fn(() => ({ getOne: vi.fn() })),
+ projectService: vi.fn(() => ({ getOne: vi.fn().mockResolvedValue({ id: 'project-1', ownerId: 'owner-1', platformId: 'platform-1' }) })),
}))
vi.mock('../../../../src/app/helper/system/system', () => ({
@@ -60,9 +61,35 @@ const trackFlowCreated = (edition: ApEdition) => {
})
}
+const trackPlanUpgraded = (edition: ApEdition) => {
+ mockGetEdition.mockReturnValue(edition)
+ return telemetry(mockLog).trackPlatform({
+ platformId: 'platform-1',
+ event: {
+ name: TelemetryEventName.PLAN_CHANGED,
+ payload: { platformId: 'platform-1', plan: 'plus', previousPlan: 'free' },
+ },
+ })
+}
+
+const CLOUD_ONLY_BILLING_AND_ONBOARDING_EVENTS: TelemetryEvent[] = [
+ { name: TelemetryEventName.ONBOARDING_COMPLETED, payload: { userId: 'user-1', platformId: 'platform-1' } },
+ { name: TelemetryEventName.CHECKOUT_STARTED, payload: { platformId: 'platform-1', plan: 'plus' } },
+ { name: TelemetryEventName.PLAN_CHANGED, payload: { platformId: 'platform-1', plan: 'plus', previousPlan: 'free' } },
+ { name: TelemetryEventName.PLAN_CANCELLED, payload: { platformId: 'platform-1', plan: 'plus' } },
+ { name: TelemetryEventName.PLAN_REACTIVATED, payload: { platformId: 'platform-1', plan: 'plus' } },
+ { name: TelemetryEventName.TRIAL_STARTED, payload: { platformId: 'platform-1', plan: 'plus', trialEndsAt: '2030-01-01T00:00:00.000Z' } },
+ { name: TelemetryEventName.SALES_HANDOFF_CLICKED, payload: { surface: 'plan-selector' } },
+]
+
+const capturedEventNames = (): string[] => mockCapture.mock.calls.map(([message]) => message.event)
+
+const capturedDistinctIds = (): string[] => mockCapture.mock.calls.map(([message]) => message.distinctId)
+
describe('cloud-only telemetry events', () => {
beforeEach(() => {
mockCapture.mockClear()
+ mockAlias.mockClear()
mockIsProductTelemetryEnabled.mockResolvedValue(true)
})
@@ -70,7 +97,7 @@ describe('cloud-only telemetry events', () => {
await trackSignedIn(ApEdition.CLOUD)
expect(mockCapture).toHaveBeenCalledTimes(1)
- expect(mockCapture.mock.calls[0][0].event).toBe(TelemetryEventName.SIGNED_IN)
+ expect(capturedEventNames()).toEqual([TelemetryEventName.SIGNED_IN])
})
it.each([ApEdition.COMMUNITY, ApEdition.ENTERPRISE])(
@@ -82,13 +109,28 @@ describe('cloud-only telemetry events', () => {
},
)
+ it('should send a billing event on cloud attributed to the platform owner', async () => {
+ await trackPlanUpgraded(ApEdition.CLOUD)
+
+ expect(capturedEventNames()).toEqual([TelemetryEventName.PLAN_CHANGED])
+ expect(capturedDistinctIds()).toEqual(['owner-1'])
+ })
+
+ it.each(CLOUD_ONLY_BILLING_AND_ONBOARDING_EVENTS)('should treat $name as cloud-only', async (event) => {
+ mockGetEdition.mockReturnValue(ApEdition.ENTERPRISE)
+
+ await telemetry(mockLog).trackUser({ userId: 'user-1', platformId: 'platform-1', event })
+
+ expect(mockCapture).not.toHaveBeenCalled()
+ })
+
it.each([ApEdition.CLOUD, ApEdition.COMMUNITY, ApEdition.ENTERPRISE])(
'should still send a product event on %s',
async (edition) => {
await trackFlowCreated(edition)
expect(mockCapture).toHaveBeenCalledTimes(1)
- expect(mockCapture.mock.calls[0][0].event).toBe(TelemetryEventName.CREATED_FLOW)
+ expect(capturedEventNames()).toEqual([TelemetryEventName.CREATED_FLOW])
},
)
@@ -99,4 +141,76 @@ describe('cloud-only telemetry events', () => {
expect(mockCapture).not.toHaveBeenCalled()
})
+
+ it('should stamp every event with the deployment kind', async () => {
+ await trackFlowCreated(ApEdition.CLOUD)
+
+ expect(mockCapture.mock.calls[0][0].properties.deployment).toBe('cloud')
+ })
+})
+
+describe('identity-level tracking', () => {
+ beforeEach(() => {
+ mockCapture.mockClear()
+ mockAlias.mockClear()
+ mockIsProductTelemetryEnabled.mockResolvedValue(true)
+ })
+
+ it('should send platform-less identity events with the identity id as distinct_id', async () => {
+ mockGetEdition.mockReturnValue(ApEdition.CLOUD)
+
+ await telemetry(mockLog).trackIdentity({
+ identityId: 'identity-1',
+ platformId: null,
+ event: { name: TelemetryEventName.EMAIL_CODE_REQUESTED, payload: { isNewIdentity: true } },
+ })
+
+ expect(capturedDistinctIds()).toEqual(['identity-1'])
+ })
+
+ it('should keep the identity id as distinct_id when a platform is known', async () => {
+ mockGetEdition.mockReturnValue(ApEdition.CLOUD)
+
+ await telemetry(mockLog).trackIdentity({
+ identityId: 'identity-1',
+ platformId: 'platform-1',
+ event: { name: TelemetryEventName.EMAIL_CODE_VERIFIED, payload: { needsNameStep: false } },
+ })
+
+ expect(capturedDistinctIds()).toEqual(['identity-1'])
+ })
+
+ it('should drop platform-less identity events outside cloud', async () => {
+ mockGetEdition.mockReturnValue(ApEdition.ENTERPRISE)
+
+ await telemetry(mockLog).trackIdentity({
+ identityId: 'identity-1',
+ platformId: null,
+ event: { name: TelemetryEventName.EMAIL_CODE_REQUESTED, payload: { isNewIdentity: true } },
+ })
+
+ expect(mockCapture).not.toHaveBeenCalled()
+ })
+
+ it('should alias the identity onto the user on cloud', async () => {
+ mockGetEdition.mockReturnValue(ApEdition.CLOUD)
+
+ await telemetry(mockLog).aliasIdentity({ identityId: 'identity-1', userId: 'user-1', platformId: 'platform-1' })
+
+ expect(mockAlias).toHaveBeenCalledWith({ distinctId: 'user-1', alias: 'identity-1' })
+ })
+
+ it('should not alias outside cloud', async () => {
+ mockGetEdition.mockReturnValue(ApEdition.ENTERPRISE)
+
+ await telemetry(mockLog).aliasIdentity({ identityId: 'identity-1', userId: 'user-1', platformId: 'platform-1' })
+
+ expect(mockAlias).not.toHaveBeenCalled()
+ })
})
+
+type CapturedMessage = {
+ event: string
+ distinctId: string
+ properties: Record<string, unknown>
+}
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index 0a5a8d089e2..49b6e8b3c3d 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -2881,6 +2881,15 @@
"Searched the step picker": "Searched the step picker",
"MCP server connected": "MCP server connected",
"MCP tool called": "MCP tool called",
+ "Onboarding completed": "Onboarding completed",
+ "Invitation sent": "Invitation sent",
+ "Invitation accepted": "Invitation accepted",
+ "Checkout started": "Checkout started",
+ "Plan changed": "Plan changed",
+ "Plan cancelled": "Plan cancelled",
+ "Plan reactivated": "Plan reactivated",
+ "Trial started": "Trial started",
+ "Contacted sales": "Contacted sales",
"Accounts and sign-in": "Accounts and sign-in",
"Emailed sign-in codes": "Emailed sign-in codes",
"Flows and the builder": "Flows and the builder",
diff --git a/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsx b/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsx
index 45b2bf49d19..f829eff9906 100644
--- a/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsx
+++ b/packages/web/src/app/builder/flow-canvas/widgets/publish-flow-reminder-widget.tsx
@@ -82,7 +82,6 @@ const PublishFlowReminderWidget = () => {
const { mutateAsync: publish } = flowHooks.useChangeFlowStatus({
flowId: flow.id,
change: 'publish',
- requiresApproval,
onSuccess: (updatedFlow: PopulatedFlow) => {
setFlow(updatedFlow);
setVersion(updatedFlow.version);
diff --git a/packages/web/src/app/routes/platform/infra/configurations/tracked-events-catalog.ts b/packages/web/src/app/routes/platform/infra/configurations/tracked-events-catalog.ts
index cae959f9b88..92fce54d31d 100644
--- a/packages/web/src/app/routes/platform/infra/configurations/tracked-events-catalog.ts
+++ b/packages/web/src/app/routes/platform/infra/configurations/tracked-events-catalog.ts
@@ -3,7 +3,14 @@ import {
TelemetryEventName,
} from '@activepieces/shared';
import { t } from 'i18next';
-import { Layers, LucideIcon, Mail, User, Workflow } from 'lucide-react';
+import {
+ CreditCard,
+ Layers,
+ LucideIcon,
+ Mail,
+ User,
+ Workflow,
+} from 'lucide-react';
const buildEventLabels = (): Record<TelemetryEventName, TrackedEvent> => ({
[TelemetryEventName.SIGNED_UP]: {
@@ -86,6 +93,42 @@ const buildEventLabels = (): Record<TelemetryEventName, TrackedEvent> => ({
group: 'mcp',
label: t('MCP tool called'),
},
+ [TelemetryEventName.ONBOARDING_COMPLETED]: {
+ group: 'accounts',
+ label: t('Onboarding completed'),
+ },
+ [TelemetryEventName.INVITE_SENT]: {
+ group: 'accounts',
+ label: t('Invitation sent'),
+ },
+ [TelemetryEventName.INVITE_ACCEPTED]: {
+ group: 'accounts',
+ label: t('Invitation accepted'),
+ },
+ [TelemetryEventName.CHECKOUT_STARTED]: {
+ group: 'billing',
+ label: t('Checkout started'),
+ },
+ [TelemetryEventName.PLAN_CHANGED]: {
+ group: 'billing',
+ label: t('Plan changed'),
+ },
+ [TelemetryEventName.PLAN_CANCELLED]: {
+ group: 'billing',
+ label: t('Plan cancelled'),
+ },
+ [TelemetryEventName.PLAN_REACTIVATED]: {
+ group: 'billing',
+ label: t('Plan reactivated'),
+ },
+ [TelemetryEventName.TRIAL_STARTED]: {
+ group: 'billing',
+ label: t('Trial started'),
+ },
+ [TelemetryEventName.SALES_HANDOFF_CLICKED]: {
+ group: 'billing',
+ label: t('Contacted sales'),
+ },
});
const buildGroups = (): TrackedEventGroup[] => {
@@ -95,6 +138,7 @@ const buildGroups = (): TrackedEventGroup[] => {
{ id: 'emailCodes', title: t('Emailed sign-in codes'), icon: Mail },
{ id: 'flows', title: t('Flows and the builder'), icon: Workflow },
{ id: 'mcp', title: t('MCP'), icon: Layers },
+ { id: 'billing', title: t('Billing'), icon: CreditCard },
];
return definitions
.map((definition) => ({
@@ -112,7 +156,12 @@ const buildGroups = (): TrackedEventGroup[] => {
export const trackedEventsCatalog = { buildEventLabels, buildGroups };
-export type TrackedEventGroupId = 'accounts' | 'emailCodes' | 'flows' | 'mcp';
+export type TrackedEventGroupId =
+ | 'accounts'
+ | 'emailCodes'
+ | 'flows'
+ | 'mcp'
+ | 'billing';
export type TrackedEvent = {
group: TrackedEventGroupId;
diff --git a/packages/web/src/components/providers/telemetry-provider.tsx b/packages/web/src/components/providers/telemetry-provider.tsx
index e7416f675bd..763581d1760 100644
--- a/packages/web/src/components/providers/telemetry-provider.tsx
+++ b/packages/web/src/components/providers/telemetry-provider.tsx
@@ -1,7 +1,9 @@
-import { isNil } from '@activepieces/core-utils';
+import { isNil, tryCatchSync } from '@activepieces/core-utils';
import {
ApEdition,
+ ApEnvironment,
ApFlagId,
+ DeploymentKind,
isCloudOnlyTelemetryEvent,
pickTelemetryPii,
TelemetryEvent,
@@ -30,13 +32,14 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {
const { data: flagCurrentVersion } = flagsHooks.useFlag<string>(
ApFlagId.CURRENT_VERSION,
);
- const { data: flagEnvironment } = flagsHooks.useFlag<string>(
+ const { data: flagEnvironment } = flagsHooks.useFlag<ApEnvironment>(
ApFlagId.ENVIRONMENT,
);
const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);
const { embedState } = useEmbedding();
const isCloud = edition === ApEdition.CLOUD;
+ const isDevEnvironment = flagEnvironment === ApEnvironment.DEVELOPMENT;
const isPreLoginCloudFunnel =
isNil(currentUser) &&
isCloud &&
@@ -44,9 +47,14 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {
const isSignedInWithAnalyticsOn =
!isNil(currentUser) &&
(isCloud || configuration?.isProductTelemetryEnabled === true);
+ const devTelemetryAllowed =
+ isPosthogDevOptIn() || (!isRunningCloudInDevMode && !isDevEnvironment);
const telemetryEnabled =
- (isPreLoginCloudFunnel || isSignedInWithAnalyticsOn) &&
- !isRunningCloudInDevMode;
+ (isPreLoginCloudFunnel || isSignedInWithAnalyticsOn) && devTelemetryAllowed;
+ const deployment = resolveDeploymentKind({
+ edition,
+ environment: flagEnvironment,
+ });
const posthogInitialized = useRef(false);
@@ -96,12 +104,12 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {
});
// Tag events so the shared project separates product from marketing traffic.
- posthog.register({ source_site: 'product' });
+ posthog.register({ source_site: 'product', deployment });
if (isCloud && isInRecordingSample(posthog.get_distinct_id())) {
posthog.startSessionRecording();
}
- }, [telemetryEnabled, embedState.isEmbedded, edition, isCloud]);
+ }, [telemetryEnabled, embedState.isEmbedded, edition, isCloud, deployment]);
useEffect(() => {
if (!posthogInitialized.current) {
@@ -111,6 +119,7 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {
activepiecesEdition: edition ?? ApEdition.COMMUNITY,
activepiecesVersion: flagCurrentVersion ?? UNKNOWN_FLAG_VALUE,
activepiecesEnvironment: flagEnvironment ?? UNKNOWN_FLAG_VALUE,
+ deployment,
});
}, [
telemetryEnabled,
@@ -118,6 +127,7 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {
embedState.isEmbedded,
flagCurrentVersion,
flagEnvironment,
+ deployment,
]);
useEffect(() => {
@@ -153,6 +163,7 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {
}),
activepiecesVersion: currentVersion,
activepiecesEnvironment: environment,
+ deployment,
});
if (currentUser.platformId) {
@@ -181,6 +192,8 @@ const UNKNOWN_FLAG_VALUE = '0.0.0';
const RECORDING_SAMPLE_RATE = 0.1;
+const POSTHOG_DEV_OPT_IN_KEY = 'ap_posthog_dev';
+
function isInRecordingSample(distinctId: string): boolean {
let hash = 5381;
for (let i = 0; i < distinctId.length; i++) {
@@ -189,6 +202,29 @@ function isInRecordingSample(distinctId: string): boolean {
return (hash >>> 0) / 0xffffffff < RECORDING_SAMPLE_RATE;
}
+function isPosthogDevOptIn(): boolean {
+ const { data } = tryCatchSync(
+ () => localStorage.getItem(POSTHOG_DEV_OPT_IN_KEY) === '1',
+ );
+ return data === true;
+}
+
+function resolveDeploymentKind({
+ edition,
+ environment,
+}: {
+ edition: ApEdition | null | undefined;
+ environment: ApEnvironment | null | undefined;
+}): DeploymentKind {
+ if (edition === ApEdition.CLOUD) {
+ return DeploymentKind.CLOUD;
+ }
+ if (environment === ApEnvironment.DEVELOPMENT) {
+ return DeploymentKind.DEV;
+ }
+ return DeploymentKind.SELF_HOSTED;
+}
+
interface TelemetryContextType {
capture: (event: TelemetryEvent) => void;
}
diff --git a/packages/web/src/features/billing/components/plan-selector-utils.ts b/packages/web/src/features/billing/components/plan-selector-utils.ts
index b78022472fc..500147584a4 100644
--- a/packages/web/src/features/billing/components/plan-selector-utils.ts
+++ b/packages/web/src/features/billing/components/plan-selector-utils.ts
@@ -4,7 +4,7 @@ import { t } from 'i18next';
const FREE_PLAN_ID = 'free';
const ANNUAL_INTERVAL = 'year';
-const SALES_URL = 'https://activepieces.com/sales';
+const SALES_URL = 'https://www.activepieces.com/sales?ap_cta=app_plan_selector';
function stripPlanInterval(name: string): string {
return name.replace(/\s*\((annual|monthly|yearly)\)\s*/i, '').trim();
diff --git a/packages/web/src/features/billing/components/plan-selector.tsx b/packages/web/src/features/billing/components/plan-selector.tsx
index 5dd6b6bcdc9..a41bd6e1771 100644
--- a/packages/web/src/features/billing/components/plan-selector.tsx
+++ b/packages/web/src/features/billing/components/plan-selector.tsx
@@ -1,9 +1,10 @@
import { isNil } from '@activepieces/core-utils';
-import { PurchasablePlan } from '@activepieces/shared';
+import { PurchasablePlan, TelemetryEventName } from '@activepieces/shared';
import { t } from 'i18next';
import { Check, Info } 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';
@@ -350,6 +351,7 @@ function PlanCta({
onKeepPlan,
onDowngrade,
}: PlanCtaProps) {
+ const { capture } = useTelemetry();
if (isEnterprise) {
return (
<Button variant="default" className="w-full bg-foreground" asChild>
@@ -357,6 +359,12 @@ function PlanCta({
href={planSelectorUtils.SALES_URL}
target="_blank"
rel="noopener noreferrer"
+ onClick={() =>
+ capture({
+ name: TelemetryEventName.SALES_HANDOFF_CLICKED,
+ payload: { plan: 'enterprise', surface: 'plan_selector' },
+ })
+ }
>
{t('Talk to sales')}
</a>
diff --git a/packages/web/src/features/billing/components/request-trial.tsx b/packages/web/src/features/billing/components/request-trial.tsx
index 1d3b2f49fb1..0de625dc1a7 100644
--- a/packages/web/src/features/billing/components/request-trial.tsx
+++ b/packages/web/src/features/billing/components/request-trial.tsx
@@ -1,9 +1,13 @@
import { isNil } from '@activepieces/core-utils';
-import { UserWithMetaInformation } from '@activepieces/shared';
+import {
+ TelemetryEventName,
+ UserWithMetaInformation,
+} from '@activepieces/shared';
import { t } from 'i18next';
import { AnimatedIconButton } from '@/components/custom/animated-icon-button';
import { SendIcon } from '@/components/icons/send';
+import { useTelemetry } from '@/components/providers/telemetry-provider';
import { userHooks } from '@/hooks/user-hooks';
import { telemetryUtils } from '@/lib/telemetry-utils';
@@ -13,13 +17,19 @@ export const RequestTrial = ({
buttonSize = 'default',
}: RequestTrialProps) => {
const { data: currentUser } = userHooks.useCurrentUser();
+ const { capture } = useTelemetry();
- const handleClick = () =>
+ const handleClick = () => {
+ capture({
+ name: TelemetryEventName.SALES_HANDOFF_CLICKED,
+ payload: { featureKey, surface: 'locked_feature' },
+ });
window.open(
buildSalesUrl({ currentUser, featureKey }),
'_blank',
'noopener noreferrer',
);
+ };
return (
<AnimatedIconButton
diff --git a/packages/web/src/features/flows/hooks/flow-hooks.tsx b/packages/web/src/features/flows/hooks/flow-hooks.tsx
index 5342b0e3042..6614599eb6b 100644
--- a/packages/web/src/features/flows/hooks/flow-hooks.tsx
+++ b/packages/web/src/features/flows/hooks/flow-hooks.tsx
@@ -16,7 +16,6 @@ import {
FlowTrigger,
FlowTriggerType,
Template,
- TelemetryEventName,
UncategorizedFolderId,
UpdateRunProgressRequest,
} from '@activepieces/shared';
@@ -32,7 +31,6 @@ import { toast } from 'sonner';
import { useApErrorDialogStore } from '@/components/custom/ap-error-dialog/ap-error-dialog-store';
import { useSocket } from '@/components/providers/socket-provider';
-import { useTelemetry } from '@/components/providers/telemetry-provider';
import { internalErrorToast } from '@/components/ui/sonner';
import { flowRunsApi } from '@/features/flow-runs/api/flow-runs-api';
import { triggerStatusErrorUtils } from '@/features/flows/utils/trigger-status-error';
@@ -72,7 +70,6 @@ export const flowHooks = {
useChangeFlowStatus: ({
flowId,
change,
- requiresApproval,
onSuccess,
setIsPublishing,
}: UseChangeFlowStatusParams) => {
@@ -84,7 +81,6 @@ export const flowHooks = {
);
const { openDialog } = useApErrorDialogStore();
const queryClient = useQueryClient();
- const { capture } = useTelemetry();
return useMutation({
mutationFn: async () => {
if (change === 'publish') {
@@ -111,12 +107,6 @@ export const flowHooks = {
queryKey: ['flow-approval-requests'],
});
setIsPublishing?.(false);
- if (!requiresApproval) {
- capture({
- name: TelemetryEventName.FLOW_PUBLISHED,
- payload: { flowId: flow.id },
- });
- }
}
onSuccess?.(flow);
},
@@ -603,7 +593,6 @@ export const flowHooks = {
type UseChangeFlowStatusParams = {
flowId: string;
change: 'publish' | FlowStatus;
- requiresApproval?: boolean;
onSuccess: (flow: PopulatedFlow) => void;
setIsPublishing?: (isPublishing: boolean) => void;
};
diff --git a/packages/web/test/app/routes/platform/infra/configurations/tracked-events-catalog.test.ts b/packages/web/test/app/routes/platform/infra/configurations/tracked-events-catalog.test.ts
index 6b7de5df851..5c5af46c21d 100644
--- a/packages/web/test/app/routes/platform/infra/configurations/tracked-events-catalog.test.ts
+++ b/packages/web/test/app/routes/platform/infra/configurations/tracked-events-catalog.test.ts
@@ -20,7 +20,9 @@ describe('trackedEventsCatalog', () => {
it('lists every self-hosted event under exactly one group', () => {
const selfHosted = Object.entries(trackedEventsCatalog.buildEventLabels())
- .filter(([name]) => !isCloudOnlyTelemetryEvent(name as TelemetryEventName))
+ .filter(
+ ([name]) => !isCloudOnlyTelemetryEvent(name as TelemetryEventName),
+ )
.map(([, event]) => event.label);
const listed = trackedEventsCatalog
.buildGroups()
@@ -41,11 +43,23 @@ describe('trackedEventsCatalog', () => {
expect(listed).toEqual(expect.not.arrayContaining(cloudOnly));
});
- it('drops the account groups once every event in them is cloud-only', () => {
- const groupIds = trackedEventsCatalog.buildGroups().map((group) => group.id);
+ it('drops a group once every event in it is cloud-only', () => {
+ const groupIds = trackedEventsCatalog
+ .buildGroups()
+ .map((group) => group.id);
expect(groupIds).not.toContain('emailCodes');
- expect(groupIds).not.toContain('accounts');
- expect(groupIds).toEqual(['flows', 'mcp']);
+ expect(groupIds).not.toContain('billing');
+ expect(groupIds).toEqual(['accounts', 'flows', 'mcp']);
+ });
+
+ it('keeps only the self-hosted invitation events in the accounts group', () => {
+ const accounts = trackedEventsCatalog
+ .buildGroups()
+ .find((group) => group.id === 'accounts');
+
+ expect(accounts?.labels.sort()).toEqual(
+ ['Invitation accepted', 'Invitation sent'].sort(),
+ );
});
});