diff --git a/apps/docs/content/docs/platform/costs.mdx b/apps/docs/content/docs/platform/costs.mdx
index 549c78e5d85..5b6141895d1 100644
--- a/apps/docs/content/docs/platform/costs.mdx
+++ b/apps/docs/content/docs/platform/costs.mdx
@@ -21,7 +21,7 @@ A billable workflow run can include:
| Hosted tools | Operation charges when using Sim-provided provider keys |
| Sandbox runtime | Applicable runtime charges, such as a Pi sandbox |
-Sim-hosted models and tools are available on paid plans. On the Free plan, add your own provider keys under **Settings → BYOK**; a run that needs a Sim-hosted key fails with an upgrade message instead.
+Sim-hosted models and tools, and Chat with Sim, are available on paid plans. On the Free plan, add your own provider keys under **Settings → BYOK**; a run that needs a Sim-hosted key fails with an upgrade message instead. Free credits cover run charges, code execution, knowledge base indexing, and AI-assisted editing in the workflow editor.
With your own provider keys, you pay the provider directly for those calls. The workflow base charge and unrelated hosted-tool or sandbox usage still apply. Local Ollama or vLLM inference avoids an external model API charge, but still needs infrastructure and any enabled Sim run charge.
diff --git a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx
index c8a01fcc5c1..79826d5337a 100644
--- a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx
+++ b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx
@@ -22,7 +22,7 @@ const formatCredits = (credits: number) => credits.toLocaleString('en-US')
const PRICING_FAQS = [
{
question: 'Is Sim free?',
- answer: `Yes. The Free plan costs $0 and includes ${formatCredits(DEFAULT_FREE_CREDITS * CREDITS_PER_DOLLAR)} one-time credits, one workspace, and all ${INTEGRATION_COUNT_LABEL} integrations, with no credit card required. On Free, models and tools run on your own provider keys; Sim-hosted keys come with paid plans. Sim is also open source, so you can self-host it for free.`,
+ answer: `Yes. The Free plan costs $0 and includes ${formatCredits(DEFAULT_FREE_CREDITS * CREDITS_PER_DOLLAR)} one-time credits, one workspace, and all ${INTEGRATION_COUNT_LABEL} integrations, with no credit card required. On Free, models and tools run on your own provider keys, and the credits cover runs, code execution, knowledge base indexing, and AI-assisted editing. Sim-hosted models and tools, and Chat with Sim, come with paid plans. Sim is also open source, so you can self-host it for free.`,
},
{
question: 'Does Sim have a free trial?',
diff --git a/apps/sim/app/api/billing/end-trial/route.ts b/apps/sim/app/api/billing/end-trial/route.ts
new file mode 100644
index 00000000000..7fcdba31a51
--- /dev/null
+++ b/apps/sim/app/api/billing/end-trial/route.ts
@@ -0,0 +1,21 @@
+import { billingEndTrialContract } from '@/lib/api/contracts/subscription'
+import {
+ defineInternalJsonRoute,
+ internalOrchestrationErrorPolicy,
+ internalRateLimits,
+ internalSessionAuth,
+} from '@/lib/api/server/routes'
+import { endProTrial, proTrialOperations } from '@/lib/billing/application/pro-trial'
+
+export const dynamic = 'force-dynamic'
+
+export const POST = defineInternalJsonRoute({
+ contract: billingEndTrialContract,
+ auth: internalSessionAuth,
+ operation: proTrialOperations.end,
+ rateLimit: internalRateLimits.user({ bucketName: 'billing-end-trial' }),
+ errorPolicy: internalOrchestrationErrorPolicy,
+ mapInput: () => ({}),
+ useCase: endProTrial,
+ present: (data) => data,
+})
diff --git a/apps/sim/app/api/billing/route.test.ts b/apps/sim/app/api/billing/route.test.ts
index 5db43b9f13d..f047b050a47 100644
--- a/apps/sim/app/api/billing/route.test.ts
+++ b/apps/sim/app/api/billing/route.test.ts
@@ -7,10 +7,13 @@ import {
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { mockGetCreditBalanceForEntity } = vi.hoisted(() => ({
+const { mockGetCreditBalanceForEntity, mockIsProTrialEligible } = vi.hoisted(() => ({
mockGetCreditBalanceForEntity: vi.fn(),
+ mockIsProTrialEligible: vi.fn(),
}))
+vi.mock('@/lib/billing/trial', () => ({ isProTrialEligible: mockIsProTrialEligible }))
+
vi.mock('@/lib/billing/core/billing', () => billingCoreMock)
vi.mock('@/lib/billing/core/organization', () => billingOrganizationMock)
@@ -142,6 +145,7 @@ describe('GET /api/billing', () => {
mockGetOrganizationBillingData.mockResolvedValue(ACTIVE_ORG_BILLING)
mockGetOrganizationSubscription.mockResolvedValue(ACTIVE_ORG_SUBSCRIPTION)
mockGetCreditBalanceForEntity.mockResolvedValue(17)
+ mockIsProTrialEligible.mockResolvedValue(false)
})
it('keeps account billing personal even when an organization ID is supplied', async () => {
diff --git a/apps/sim/app/api/billing/route.ts b/apps/sim/app/api/billing/route.ts
index 6c0092f5622..fb946745efa 100644
--- a/apps/sim/app/api/billing/route.ts
+++ b/apps/sim/app/api/billing/route.ts
@@ -21,6 +21,7 @@ import {
import { getCreditBalanceForEntity } from '@/lib/billing/credits/balance'
import { isPaid } from '@/lib/billing/plan-helpers'
import { resolveBillingInterval } from '@/lib/billing/subscriptions/utils'
+import { isProTrialEligible } from '@/lib/billing/trial'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
const logger = createLogger('UnifiedBillingAPI')
@@ -59,9 +60,10 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
}
if (context === 'user') {
- const [personalBilling, upgradeWorkspaceId] = await Promise.all([
+ const [personalBilling, upgradeWorkspaceId, proTrialEligible] = await Promise.all([
getPersonalBillingSummary(session.user.id, dbReplica),
getUpgradeWorkspaceId({ type: 'user', id: session.user.id }),
+ isProTrialEligible(session.user.id, dbReplica),
])
let organizationMembership: { id: string; role: 'owner' | 'admin' | 'member' } | undefined
@@ -89,6 +91,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
data: {
...personalBilling,
upgradeWorkspaceId,
+ proTrialEligible,
...(organizationMembership ? { organization: organizationMembership } : {}),
},
})
diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/chat-plan-notice.tsx b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/chat-plan-notice.tsx
new file mode 100644
index 00000000000..dab8bb8de51
--- /dev/null
+++ b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/chat-plan-notice.tsx
@@ -0,0 +1,59 @@
+'use client'
+
+import { useRouter } from 'next/navigation'
+import { CHAT_PLAN_REQUIRED_UPGRADE } from '@/lib/billing/chat-plan'
+import { PRO_TRIAL_DAYS } from '@/lib/billing/constants'
+import { rememberSettingsReturnUrl } from '@/lib/navigation/settings-return'
+import { useChatPlanRequired } from '@/app/workspace/[workspaceId]/home/hooks/use-chat-plan-required'
+import { usePlanUpgradeLink } from '@/app/workspace/[workspaceId]/home/hooks/use-plan-upgrade-link'
+import { useWorkspaceHostContext } from '@/app/workspace/[workspaceId]/providers/workspace-host-provider'
+import { useSubscriptionData } from '@/hooks/queries/subscription'
+
+/**
+ * Says up front, above an empty composer, that this workspace's plan does not include Chat, so a
+ * free payer learns it before typing rather than from the modal a send opens.
+ */
+export function ChatPlanNotice() {
+ if (!useChatPlanRequired()) return null
+ return
+}
+
+function ChatPlanNoticeContent() {
+ const router = useRouter()
+ const hostContext = useWorkspaceHostContext()
+ const { href, opensInNewTab, canManageBilling, unavailableMessage } = usePlanUpgradeLink(
+ CHAT_PLAN_REQUIRED_UPGRADE
+ )
+ const isPersonalWorkspace = !hostContext.hostOrganizationId
+ // Only a personal checkout starts the trial, so the offer is the viewer's own.
+ const { data: viewerBilling } = useSubscriptionData({
+ enabled: canManageBilling && isPersonalWorkspace,
+ })
+ const offersTrial = isPersonalWorkspace && viewerBilling?.data?.proTrialEligible === true
+
+ const openUpgrade = () => {
+ if (opensInNewTab) {
+ window.open(href, '_blank', 'noopener,noreferrer')
+ return
+ }
+ rememberSettingsReturnUrl(href)
+ router.push(href)
+ }
+
+ return (
+
+ Chat with Sim is included with paid plans.{' '}
+ {canManageBilling ? (
+
+ {offersTrial ? `Start a ${PRO_TRIAL_DAYS}-day free trial` : 'Upgrade your plan'}
+
+ ) : (
+ unavailableMessage
+ )}
+
+ )
+}
diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/index.ts b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/index.ts
new file mode 100644
index 00000000000..60edaf2cd0a
--- /dev/null
+++ b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/index.ts
@@ -0,0 +1 @@
+export { ChatPlanNotice } from './chat-plan-notice'
diff --git a/apps/sim/app/workspace/[workspaceId]/home/home.tsx b/apps/sim/app/workspace/[workspaceId]/home/home.tsx
index 1e3523389f6..e3b0ad509cb 100644
--- a/apps/sim/app/workspace/[workspaceId]/home/home.tsx
+++ b/apps/sim/app/workspace/[workspaceId]/home/home.tsx
@@ -21,6 +21,7 @@ import {
} from '@/lib/mothership/events'
import { captureEvent } from '@/lib/posthog/client'
import { persistImportedWorkflow } from '@/lib/workflows/operations/import-export'
+import { ChatPlanNotice } from '@/app/workspace/[workspaceId]/home/components/chat-plan-notice'
import { ChatResourcePanel } from '@/app/workspace/[workspaceId]/home/components/chat-resource-panel'
import { RESOURCE_HEADER_CLASSES } from '@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-tabs/resource-tab-controls'
import { SuggestedActions } from '@/app/workspace/[workspaceId]/home/components/suggested-actions'
@@ -441,6 +442,7 @@ function HomeContent({ chatId, userName, userId }: HomeProps) {
What should we get done{firstName ? `, ${firstName}` : ''}?
+
)}
+ {isTrialing && !isOrganizationScope && canManageBilling && !isCancelledAtPeriodEnd && (
+
+
+ End the trial and start paying today
+
+
+ endProTrial.mutate(undefined, {
+ onSuccess: () => toast.success('Your paid plan has started'),
+ onError: (error) =>
+ toast.error("Couldn't start your paid plan", {
+ description: getErrorMessage(error, 'Please try again.'),
+ }),
+ })
+ }
+ >
+ Start paid plan
+
+
+ )}
+
{subscription.isPaid && weeklyRefreshDollars > 0 && (
Weekly refresh
diff --git a/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts b/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts
index 9b48675f6eb..1cf18f023b4 100644
--- a/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts
+++ b/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts
@@ -28,6 +28,7 @@ export const ENTERPRISE_PLAN_CREDITS: PlanCredits = {
export const PRO_PLAN_FEATURES: readonly string[] = [
'Chat with Sim',
+ 'Sim-hosted models & tools',
`${DEFAULT_BILLING_CONCURRENCY_LIMITS.pro.toLocaleString('en-US')} concurrent executions`,
'Invite teammates',
'Higher rate limits',
@@ -37,6 +38,7 @@ export const PRO_PLAN_FEATURES: readonly string[] = [
export const MAX_PLAN_FEATURES: readonly string[] = [
'Chat with Sim',
+ 'Sim-hosted models & tools',
`${DEFAULT_BILLING_CONCURRENCY_LIMITS.team.toLocaleString('en-US')} concurrent executions`,
'Invite teammates',
'Sim Mailer, KB Live Sync & Sandboxes',
diff --git a/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx b/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx
index e1b1a87974b..92d9e6f4063 100644
--- a/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx
+++ b/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx
@@ -37,6 +37,7 @@ import {
upgradeReasonParam,
upgradeUrlKeys,
} from '@/app/workspace/[workspaceId]/upgrade/search-params'
+import { useSubscriptionData } from '@/hooks/queries/subscription'
import { useFullscreenOriginStore } from '@/stores/fullscreen-origin/store'
/** The demo form, so a sales booking passes the same spam checks as every other. */
@@ -66,9 +67,14 @@ export function Upgrade({ workspaceId }: UpgradeProps) {
...upgradeUrlKeys,
})
const [showAllFeatures, setShowAllFeatures] = useState(false)
-
const header = reason ? UPGRADE_REASON_COPY[reason].header : DEFAULT_UPGRADE_HEADER
const canManageBilling = canManageWorkspaceBilling(hostContext, session?.user?.id)
+ // The trial is a personal checkout, so only a payer viewing their own workspace can start one.
+ const isPersonalWorkspace = !hostContext.hostOrganizationId
+ const { data: viewerBilling } = useSubscriptionData({
+ enabled: canManageBilling && isPersonalWorkspace,
+ })
+ const proTrialEligible = isPersonalWorkspace && viewerBilling?.data?.proTrialEligible === true
const handleBack = useCallback(() => {
router.replace(origin ?? `/workspace/${workspaceId}`)
@@ -172,7 +178,10 @@ export function Upgrade({ workspaceId }: UpgradeProps) {
}
}
- return { ...cta, onClick }
+ // Only a personal Pro checkout starts the trial, so only that card says so.
+ const startsTrial =
+ card === 'pro' && cta.intent === 'upgrade' && checkoutTarget === 'pro' && proTrialEligible
+ return { ...cta, ...(startsTrial ? { label: 'Start free trial' } : {}), onClick }
}
const proCta = resolveCta('pro')
diff --git a/apps/sim/background/schedule-execution.ts b/apps/sim/background/schedule-execution.ts
index eeabc810762..237d6a68a9a 100644
--- a/apps/sim/background/schedule-execution.ts
+++ b/apps/sim/background/schedule-execution.ts
@@ -16,6 +16,7 @@ import {
assertBillingAttributionSnapshot,
type BillingAttributionSnapshot,
} from '@/lib/billing/core/attribution'
+import { isHostedKeyPaidPlanFailure } from '@/lib/billing/core/hosted-key-access'
import { classifyTransientAdmissionFailure } from '@/lib/core/admission/transient-failure'
import type { AsyncExecutionCorrelation } from '@/lib/core/async-jobs/types'
import {
@@ -98,7 +99,8 @@ function resetScheduleInfraRetryCount(): Pick
{
+ const needsPaidPlan = isHostedKeyPaidPlanFailure(params.failureMessage)
+ const outcome = await applyScheduleUpdate(
+ params.scheduleId,
+ buildScheduleFailureUpdate(params.now, params.nextRunAt, { disable: needsPaidPlan }),
+ params.requestId,
+ params.context,
+ {
+ expectedLastQueuedAt: params.expectedLastQueuedAt,
+ disableReason: needsPaidPlan ? 'paid_plan_required' : 'consecutive_failures',
+ }
+ )
+ return { updated: outcome.updated, disabled: outcome.status === 'disabled' }
+}
+
type RunWorkflowResult =
| {
status: 'skip'
@@ -1192,11 +1223,15 @@ export async function executeScheduleJob(
const nextRunAt = calculateNextRunTime(payload, executionResult.blocks)
- await updateClaimedSchedule(
- buildScheduleFailureUpdate(now, nextRunAt),
- `Error updating schedule ${payload.scheduleId} after failure`,
- 'consecutive_failures'
- )
+ await applyScheduleRunFailureUpdate({
+ scheduleId: payload.scheduleId,
+ now,
+ nextRunAt,
+ expectedLastQueuedAt: claimedAt,
+ requestId,
+ context: `Error updating schedule ${payload.scheduleId} after failure`,
+ failureMessage: executionResult.executionResult.error,
+ })
} catch (error: unknown) {
logger.error(
`Error executing scheduled workflow ${payload.workflowId}`,
@@ -1206,11 +1241,15 @@ export async function executeScheduleJob(
const nextRunAt = await determineNextRunAfterError(payload, now, requestId)
- await updateClaimedSchedule(
- buildScheduleFailureUpdate(now, nextRunAt),
- `Error updating schedule ${payload.scheduleId} after execution error`,
- 'consecutive_failures'
- )
+ await applyScheduleRunFailureUpdate({
+ scheduleId: payload.scheduleId,
+ now,
+ nextRunAt,
+ expectedLastQueuedAt: claimedAt,
+ requestId,
+ context: `Error updating schedule ${payload.scheduleId} after execution error`,
+ failureMessage: toError(error).message,
+ })
}
} catch (error: unknown) {
try {
diff --git a/apps/sim/components/emails/auth/welcome-email.tsx b/apps/sim/components/emails/auth/welcome-email.tsx
index 654fa4c80a7..3bd4dbf7576 100644
--- a/apps/sim/components/emails/auth/welcome-email.tsx
+++ b/apps/sim/components/emails/auth/welcome-email.tsx
@@ -37,7 +37,7 @@ export function WelcomeEmail({ userName }: WelcomeEmailProps) {
- You're on the Community plan with 1,000 credits to get started.
+ You're on the Free plan with 1,000 credits to get started.
)
diff --git a/apps/sim/components/emails/billing/constants.ts b/apps/sim/components/emails/billing/constants.ts
index e415986a82d..6a78174af51 100644
--- a/apps/sim/components/emails/billing/constants.ts
+++ b/apps/sim/components/emails/billing/constants.ts
@@ -1,5 +1,6 @@
/** Pro plan features shown in billing upgrade emails */
export const proFeatures = [
+ { label: 'Sim-hosted models & tools', desc: 'no API keys needed' },
{ label: '6,000 credits/month', desc: 'included' },
{ label: '+2,000 weekly refresh', desc: 'credits per week' },
{ label: '150 runs/min', desc: 'sync executions' },
diff --git a/apps/sim/components/emails/billing/credits-exhausted-email.tsx b/apps/sim/components/emails/billing/credits-exhausted-email.tsx
index 1f497129da7..3607fa3b475 100644
--- a/apps/sim/components/emails/billing/credits-exhausted-email.tsx
+++ b/apps/sim/components/emails/billing/credits-exhausted-email.tsx
@@ -2,6 +2,7 @@ import { Text } from '@react-email/components'
import { baseStyles } from '@/components/emails/_styles'
import { ProFeaturesBox } from '@/components/emails/billing/pro-features-box'
import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components'
+import { PRO_TRIAL_DAYS } from '@/lib/billing/constants'
import { dollarsToCredits } from '@/lib/billing/credits/conversion'
interface CreditsExhaustedEmailProps {
@@ -29,6 +30,10 @@ export function CreditsExhaustedEmail({
+
+ Eligible new Pro subscribers start with a {PRO_TRIAL_DAYS}-day free trial.
+
+
Upgrade to Pro
diff --git a/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx b/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx
index ae67b56d9ee..09038d448ba 100644
--- a/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx
+++ b/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx
@@ -2,6 +2,7 @@ import { Text } from '@react-email/components'
import { baseStyles } from '@/components/emails/_styles'
import { ProFeaturesBox } from '@/components/emails/billing/pro-features-box'
import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components'
+import { PRO_TRIAL_DAYS } from '@/lib/billing/constants'
import { dollarsToCredits } from '@/lib/billing/credits/conversion'
interface FreeTierUpgradeEmailProps {
@@ -33,6 +34,10 @@ export function FreeTierUpgradeEmail({
+
+ Eligible new Pro subscribers start with a {PRO_TRIAL_DAYS}-day free trial.
+
+
Upgrade to Pro
diff --git a/apps/sim/components/emails/billing/index.ts b/apps/sim/components/emails/billing/index.ts
index eab1c008435..c1de4893854 100644
--- a/apps/sim/components/emails/billing/index.ts
+++ b/apps/sim/components/emails/billing/index.ts
@@ -5,6 +5,8 @@ export { EnterpriseSubscriptionEmail } from './enterprise-subscription-email'
export { FreeTierUpgradeEmail } from './free-tier-upgrade-email'
export { LimitThresholdEmail } from './limit-threshold-email'
export { PaymentFailedEmail } from './payment-failed-email'
+export { PlanEndedEmail } from './plan-ended-email'
export { PlanWelcomeEmail } from './plan-welcome-email'
+export { TrialEndingEmail } from './trial-ending-email'
export { UsageLimitReachedEmail } from './usage-limit-reached-email'
export { UsageThresholdEmail } from './usage-threshold-email'
diff --git a/apps/sim/components/emails/billing/plan-ended-email.tsx b/apps/sim/components/emails/billing/plan-ended-email.tsx
new file mode 100644
index 00000000000..f20e0939419
--- /dev/null
+++ b/apps/sim/components/emails/billing/plan-ended-email.tsx
@@ -0,0 +1,40 @@
+import { Text } from '@react-email/components'
+import { baseStyles } from '@/components/emails/_styles'
+import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components'
+
+interface PlanEndedEmailProps {
+ planName: string
+ userName?: string
+ upgradeLink: string
+}
+
+/**
+ * Sent once when a paid plan ends and its payer is back on Free, because workflows built on Sim's
+ * hosted models and tools stop working without warning otherwise.
+ */
+export function PlanEndedEmail({ planName, userName, upgradeLink }: PlanEndedEmailProps) {
+ return (
+
+ {userName ? `Hi ${userName},` : 'Hi,'}
+
+
+ Your {planName} plan has ended, and you're now on the Free
+ plan. Sim-hosted models and tools and Chat with Sim are no longer available, so workflows
+ and schedules that use them will fail.
+
+
+
+ To keep them running, add your own provider keys under Settings → BYOK, or pick a plan
+ again.
+
+
+ View plans
+
+
+
+ Sent once when a paid plan ends.
+
+ )
+}
+
+export default PlanEndedEmail
diff --git a/apps/sim/components/emails/billing/trial-ending-email.tsx b/apps/sim/components/emails/billing/trial-ending-email.tsx
new file mode 100644
index 00000000000..3b8bb966fc5
--- /dev/null
+++ b/apps/sim/components/emails/billing/trial-ending-email.tsx
@@ -0,0 +1,50 @@
+import { Text } from '@react-email/components'
+import { baseStyles } from '@/components/emails/_styles'
+import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components'
+
+interface TrialEndingEmailProps {
+ planName: string
+ userName?: string
+ /** When the trial converts, already formatted for display. */
+ endsOn: string
+ /** What the card is charged when the trial converts, already formatted (e.g. `$25/month`). */
+ price: string
+ billingLink: string
+}
+
+/** Sent a few days before a free trial converts, so the charge is never a surprise. */
+export function TrialEndingEmail({
+ planName,
+ userName,
+ endsOn,
+ price,
+ billingLink,
+}: TrialEndingEmailProps) {
+ return (
+
+ {userName ? `Hi ${userName},` : 'Hi,'}
+
+
+ Your {planName} free trial ends on{' '}
+ {endsOn} . Your card will then be charged{' '}
+ {price} , and the plan's full credits replace the trial allowance.
+
+
+
+ Nothing to do if you want to keep {planName}. To stop before the charge, cancel in Settings
+ → Subscription before {endsOn}.
+
+
+ Manage subscription
+
+
+
+ Sent once, a few days before your trial ends.
+
+ )
+}
+
+export default TrialEndingEmail
diff --git a/apps/sim/components/emails/render.ts b/apps/sim/components/emails/render.ts
index ca80b2478f5..8008c48070e 100644
--- a/apps/sim/components/emails/render.ts
+++ b/apps/sim/components/emails/render.ts
@@ -15,7 +15,9 @@ import {
FreeTierUpgradeEmail,
LimitThresholdEmail,
PaymentFailedEmail,
+ PlanEndedEmail,
PlanWelcomeEmail,
+ TrialEndingEmail,
UsageLimitReachedEmail,
UsageThresholdEmail,
} from '@/components/emails/billing'
@@ -225,6 +227,24 @@ export async function renderPlanWelcomeEmail(params: {
return await render(PlanWelcomeEmail(params))
}
+export async function renderTrialEndingEmail(params: {
+ planName: string
+ userName?: string
+ endsOn: string
+ price: string
+ billingLink: string
+}): Promise {
+ return await render(TrialEndingEmail(params))
+}
+
+export async function renderPlanEndedEmail(params: {
+ planName: string
+ userName?: string
+ upgradeLink: string
+}): Promise {
+ return await render(PlanEndedEmail(params))
+}
+
export async function renderWelcomeEmail(userName?: string): Promise {
return await render(WelcomeEmail({ userName }))
}
diff --git a/apps/sim/components/emails/subjects.ts b/apps/sim/components/emails/subjects.ts
index 284342f7e21..16860f7c6e3 100644
--- a/apps/sim/components/emails/subjects.ts
+++ b/apps/sim/components/emails/subjects.ts
@@ -108,6 +108,15 @@ export function getPlanWelcomeSubject(planDisplayName: string, isTrial = false):
: `Your ${planDisplayName} plan is now active on Sim`
}
+/** Names the date so the reminder reads as a deadline in the inbox. */
+export function getTrialEndingSubject(planDisplayName: string, endsOn: string): string {
+ return `Your ${planDisplayName} free trial ends ${endsOn}`
+}
+
+export function getPlanEndedSubject(planDisplayName: string): string {
+ return `Your ${planDisplayName} plan has ended on Sim`
+}
+
/** Echoes the sender's own subject line so the reply threads correctly. */
export function getRequestConfirmationSubject(userSubject: string, requestType?: string): string {
return requestType
diff --git a/apps/sim/hooks/queries/subscription.ts b/apps/sim/hooks/queries/subscription.ts
index e5067c542fb..3c49be5f8ef 100644
--- a/apps/sim/hooks/queries/subscription.ts
+++ b/apps/sim/hooks/queries/subscription.ts
@@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { requestJson } from '@/lib/api/client/request'
import type { ContractBodyInput } from '@/lib/api/contracts'
import {
+ billingEndTrialContract,
createBillingPortalContract,
getInvoicesContract,
getUserUsageLimitContract,
@@ -218,3 +219,19 @@ export function useOpenBillingPortal() {
},
})
}
+
+/**
+ * Ends the viewer's own Pro free trial now. The card is charged by Stripe and the webhooks raise
+ * the trial allowance to the plan's, so every billing read is refetched once the call returns.
+ */
+export function useEndProTrial() {
+ const queryClient = useQueryClient()
+ return useMutation({
+ mutationFn: () => requestJson(billingEndTrialContract, { body: {} }),
+ onSettled: () =>
+ Promise.all([
+ queryClient.invalidateQueries({ queryKey: subscriptionKeys.all }),
+ invalidateWorkspaceUsage(queryClient),
+ ]),
+ })
+}
diff --git a/apps/sim/lib/api/contracts/subscription.ts b/apps/sim/lib/api/contracts/subscription.ts
index f89591f340b..5b189a47ccf 100644
--- a/apps/sim/lib/api/contracts/subscription.ts
+++ b/apps/sim/lib/api/contracts/subscription.ts
@@ -87,6 +87,8 @@ export const subscriptionBillingDataSchema = z
billingBlockedReason: z.enum(['payment_failed', 'dispute']).nullable(),
blockedByOrgOwner: z.boolean(),
upgradeWorkspaceId: workspaceIdSchema.nullable(),
+ /** The viewer may still start Pro's free trial at checkout. Personal context only. */
+ proTrialEligible: z.boolean().optional(),
organization: z
.object({
id: z.string(),
@@ -374,6 +376,17 @@ export const billingSwitchPlanContract = defineRouteContract({
},
})
+/** Ends the caller's own Pro free trial now, so the card is charged and the full plan starts. */
+export const billingEndTrialContract = defineRouteContract({
+ method: 'POST',
+ path: '/api/billing/end-trial',
+ body: z.object({}),
+ response: {
+ mode: 'json',
+ schema: z.object({ success: z.literal(true) }),
+ },
+})
+
export const billingUpdateCostContract = defineRouteContract({
method: 'POST',
path: '/api/billing/update-cost',
diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts
index 973727dbc09..159405ec3c6 100644
--- a/apps/sim/lib/auth/auth.ts
+++ b/apps/sim/lib/auth/auth.ts
@@ -122,6 +122,7 @@ import {
handleInvoicePaymentFailed,
handleInvoicePaymentSucceeded,
} from '@/lib/billing/webhooks/invoices'
+import { handleTrialWillEnd } from '@/lib/billing/webhooks/plan-notices'
import {
handleSubscriptionCreated,
handleSubscriptionDeleted,
@@ -1927,6 +1928,10 @@ export const auth = betterAuth({
await handleAbandonedCheckout(event)
break
}
+ case 'customer.subscription.trial_will_end': {
+ await handleTrialWillEnd(event.data.object)
+ break
+ }
case 'charge.dispute.created': {
await handleChargeDispute(event)
break
diff --git a/apps/sim/lib/billing/application/pro-trial.ts b/apps/sim/lib/billing/application/pro-trial.ts
new file mode 100644
index 00000000000..b00a030b23d
--- /dev/null
+++ b/apps/sim/lib/billing/application/pro-trial.ts
@@ -0,0 +1,54 @@
+import { getHighestPriorityPersonalSubscription } from '@/lib/billing/core/plan'
+import { requireStripeClient } from '@/lib/billing/stripe-client'
+import { isTrialingSubscription } from '@/lib/billing/subscriptions/utils'
+import { assertOperationCapability, type OperationUseCase } from '@/lib/core/application'
+import { OrchestrationError } from '@/lib/core/orchestration/types'
+import type { UserAccountOperation } from '@/lib/users/application/operations'
+import { authorizeAccountPreferences } from '@/lib/users/application/preferences-authorization'
+
+/** Session-only: ending a trial charges the account's own card, so no delegation may do it. */
+function defineProTrialOperation(id: Id) {
+ const operation = {
+ id,
+ capability: 'none',
+ principalKinds: Object.freeze(['session'] as const),
+ } satisfies UserAccountOperation
+ assertOperationCapability(operation)
+ return Object.freeze(operation)
+}
+
+export const proTrialOperations = {
+ // permission-group-exempt: ending your own personal trial is an account act, not a workspace act.
+ end: defineProTrialOperation('billing.trial.end'),
+} as const
+
+/**
+ * Ends the caller's own Pro free trial now. Stripe charges the card for the first paid period,
+ * and the subscription webhooks replace the trial allowance with the plan's. Only the account's
+ * own trialing personal subscription qualifies; nobody else's trial can be ended this way.
+ */
+export const endProTrial: OperationUseCase<
+ typeof proTrialOperations.end,
+ Record,
+ { success: true }
+> = {
+ operation: proTrialOperations.end,
+ async execute({ principal }) {
+ const userId = await authorizeAccountPreferences(principal, proTrialOperations.end)
+ const subscription = await getHighestPriorityPersonalSubscription(userId, { onError: 'throw' })
+ if (
+ !subscription ||
+ subscription.referenceId !== userId ||
+ !isTrialingSubscription(subscription) ||
+ !subscription.stripeSubscriptionId
+ ) {
+ throw new OrchestrationError('conflict', 'There is no free trial to end on this account')
+ }
+ await requireStripeClient().subscriptions.update(
+ subscription.stripeSubscriptionId,
+ { trial_end: 'now' },
+ { idempotencyKey: `end-trial-early:${subscription.stripeSubscriptionId}` }
+ )
+ return { success: true }
+ },
+}
diff --git a/apps/sim/lib/billing/chat-plan.ts b/apps/sim/lib/billing/chat-plan.ts
index 2b87add362f..3c960688fc4 100644
--- a/apps/sim/lib/billing/chat-plan.ts
+++ b/apps/sim/lib/billing/chat-plan.ts
@@ -1,3 +1,5 @@
+import { PRO_TRIAL_DAYS } from '@/lib/billing/constants'
+
/** The upgrade card's `reason` for a payer whose plan does not include Chat. */
export const CHAT_PLAN_REQUIRED_REASON = 'plan_required' as const
@@ -10,5 +12,5 @@ export const CHAT_PLAN_REQUIRED_REASON = 'plan_required' as const
export const CHAT_PLAN_REQUIRED_UPGRADE = {
reason: CHAT_PLAN_REQUIRED_REASON,
action: 'upgrade_plan',
- message: 'Chat is included on paid plans. Upgrade your plan to talk to Sim.',
+ message: `Chat is included on paid plans, and Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers. Upgrade your plan to talk to Sim.`,
} as const
diff --git a/apps/sim/lib/billing/core/hosted-key-access.ts b/apps/sim/lib/billing/core/hosted-key-access.ts
index ce82cde328b..8ed028e9927 100644
--- a/apps/sim/lib/billing/core/hosted-key-access.ts
+++ b/apps/sim/lib/billing/core/hosted-key-access.ts
@@ -1,9 +1,21 @@
+import { PRO_TRIAL_DAYS } from '@/lib/billing/constants'
import { resolveWorkspaceBillingPayer } from '@/lib/billing/core/attribution'
import { payerHasPaidAccess } from '@/lib/billing/core/chat-access'
import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade'
import { isBillingEnabled, isHosted } from '@/lib/core/config/env-flags'
import { HttpError } from '@/lib/core/utils/http-error'
+/** The fixed part of {@link HostedKeyRequiresPaidPlanError}'s message, which outlives its class. */
+const HOSTED_KEY_PAID_PLAN_PHRASE = "with Sim's hosted key is available on paid plans"
+
+/**
+ * Whether a run failed because a free payer reached for Sim's hosted key. A workflow's failure
+ * reaches its caller as text, so this reads the message rather than the error's class.
+ */
+export function isHostedKeyPaidPlanFailure(message: string | null | undefined): boolean {
+ return Boolean(message?.includes(HOSTED_KEY_PAID_PLAN_PHRASE))
+}
+
/**
* Sim's hosted key was withheld because the run's payer is on the free plan. Carries a 402 so the
* run fails as the caller's plan, not as a Sim fault.
@@ -14,7 +26,7 @@ export class HostedKeyRequiresPaidPlanError extends HttpError {
/** @param subject - what asked for the key: a tool's name or a model id */
constructor(subject: string) {
super(
- `${subject} with Sim's hosted key is available on paid plans. Upgrade your plan, or add your own API key under Settings > BYOK.`
+ `${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. Upgrade your plan (Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers), or add your own API key under Settings > BYOK.`
)
this.name = 'HostedKeyRequiresPaidPlanError'
}
diff --git a/apps/sim/lib/billing/free-plan.integration.ts b/apps/sim/lib/billing/free-plan.integration.ts
new file mode 100644
index 00000000000..3b1e45d6816
--- /dev/null
+++ b/apps/sim/lib/billing/free-plan.integration.ts
@@ -0,0 +1,316 @@
+/**
+ * What the Free plan and the trial edges do against real PostgreSQL: web search is held to paid
+ * payers like every hosted tool, a schedule a free payer's run cannot serve turns off at once, the
+ * trial-ending reminder goes out once per trial, and only an account's own trial can be ended
+ * early (Stripe and mail stubbed at their clients).
+ */
+import { db } from '@sim/db'
+import { subscription, user, userStats, workflowSchedule, workspace } from '@sim/db/schema'
+import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
+import { generateId } from '@sim/utils/id'
+import { eq, inArray } from 'drizzle-orm'
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { endProTrial } from '@/lib/billing/application/pro-trial'
+import { HostedKeyRequiresPaidPlanError } from '@/lib/billing/core/hosted-key-access'
+import {
+ handleTrialWillEnd,
+ type TrialEndingSubscription,
+} from '@/lib/billing/webhooks/plan-notices'
+import { executeSearchTool } from '@/lib/internal/search/execute-tool'
+import { applyScheduleRunFailureUpdate } from '@/background/schedule-execution'
+
+const { stripeStub, mockSendEmail, mockNotifyScheduleAutoDisabled } = vi.hoisted(() => ({
+ stripeStub: { subscriptions: { update: vi.fn() }, invoices: { createPreview: vi.fn() } },
+ mockSendEmail: vi.fn(),
+ mockNotifyScheduleAutoDisabled: vi.fn(),
+}))
+
+vi.mock('@/lib/core/config/env-flags', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isHosted: true,
+ isBillingEnabled: true,
+}))
+
+vi.mock('@/lib/billing/stripe-client', () => ({
+ requireStripeClient: () => stripeStub,
+ getStripeClient: () => stripeStub,
+}))
+
+vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: mockSendEmail }))
+
+vi.mock('@/lib/workflows/schedules/disable-notifications', () => ({
+ notifyScheduleAutoDisabled: mockNotifyScheduleAutoDisabled,
+}))
+
+const PRO_PLAN = 'pro_6000'
+const DAY_MS = 86_400_000
+
+const userIds: string[] = []
+const workspaceIds: string[] = []
+const scheduleIds: string[] = []
+
+async function createUser(): Promise {
+ const id = `free-plan-user-${generateId()}`
+ const now = new Date()
+ await db.insert(user).values({
+ id,
+ name: 'Free Plan Test',
+ email: `${id}@free-plan.test`,
+ emailVerified: true,
+ createdAt: now,
+ updatedAt: now,
+ })
+ await db.insert(userStats).values({ id: generateId(), userId: id })
+ userIds.push(id)
+ return id
+}
+
+async function createWorkspace(ownerId: string): Promise {
+ const id = generateId()
+ await insertWorkspaceFixture(db, {
+ id,
+ ownerId,
+ billedAccountUserId: ownerId,
+ name: 'Free plan workspace',
+ })
+ workspaceIds.push(id)
+ return id
+}
+
+async function addSubscription(referenceId: string, status: string) {
+ const stripeSubscriptionId = `sub_${generateId()}`
+ const now = Date.now()
+ await db.insert(subscription).values({
+ id: generateId(),
+ plan: PRO_PLAN,
+ referenceId,
+ status,
+ stripeSubscriptionId,
+ periodStart: new Date(now - DAY_MS),
+ periodEnd: new Date(now + 13 * DAY_MS),
+ trialStart: status === 'trialing' ? new Date(now - DAY_MS) : null,
+ trialEnd: status === 'trialing' ? new Date(now + 13 * DAY_MS) : null,
+ })
+ return stripeSubscriptionId
+}
+
+function search(userId: string, workspaceId: string) {
+ return executeSearchTool({
+ toolId: 'search_tool',
+ input: { query: 'sim workflows' },
+ headers: new Headers(),
+ context: { workflowId: 'workflow-under-test', workspaceId, userId },
+ requestId: generateId(),
+ })
+}
+
+function trialWillEnd(stripeSubscriptionId: string, status = 'trialing'): TrialEndingSubscription {
+ return {
+ id: stripeSubscriptionId,
+ status,
+ trial_end: Math.floor((Date.now() + 3 * DAY_MS) / 1000),
+ items: {
+ data: [{ quantity: 1, price: { unit_amount: 2500, recurring: { interval: 'month' } } }],
+ },
+ }
+}
+
+async function addClaimedSchedule() {
+ const id = generateId()
+ const claimedAt = new Date()
+ await db.insert(workflowSchedule).values({
+ id,
+ triggerType: 'schedule',
+ cronExpression: '*/5 * * * *',
+ status: 'active',
+ failedCount: 0,
+ lastQueuedAt: claimedAt,
+ nextRunAt: claimedAt,
+ })
+ scheduleIds.push(id)
+ return { id, claimedAt }
+}
+
+async function readSchedule(id: string) {
+ const [row] = await db
+ .select({ status: workflowSchedule.status, failedCount: workflowSchedule.failedCount })
+ .from(workflowSchedule)
+ .where(eq(workflowSchedule.id, id))
+ return row
+}
+
+beforeEach(() => {
+ stripeStub.subscriptions.update.mockReset()
+ stripeStub.subscriptions.update.mockResolvedValue({})
+ mockSendEmail.mockReset()
+ mockSendEmail.mockResolvedValue({ success: true })
+ stripeStub.invoices.createPreview.mockReset()
+ stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 2500 })
+ mockNotifyScheduleAutoDisabled.mockReset()
+})
+
+afterAll(async () => {
+ if (scheduleIds.length > 0) {
+ await db.delete(workflowSchedule).where(inArray(workflowSchedule.id, scheduleIds))
+ }
+ if (workspaceIds.length > 0) {
+ await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds))
+ }
+ if (userIds.length > 0) {
+ await db.delete(subscription).where(inArray(subscription.referenceId, userIds))
+ await db.delete(user).where(inArray(user.id, userIds))
+ }
+})
+
+describe('web search', () => {
+ it('refuses a free payer with the paid-plan 402', async () => {
+ const userId = await createUser()
+ const workspaceId = await createWorkspace(userId)
+
+ const response = await search(userId, workspaceId)
+
+ expect(response.status).toBe(402)
+ expect((await response.json()).error).toBe(
+ new HostedKeyRequiresPaidPlanError('Web Search').message
+ )
+ })
+
+ it('lets a paid payer through to the search provider', async () => {
+ const userId = await createUser()
+ const workspaceId = await createWorkspace(userId)
+ await addSubscription(userId, 'active')
+
+ const response = await search(userId, workspaceId)
+
+ // Past the plan gate, the request reaches the provider step, which has no key under test.
+ expect(response.status).toBe(503)
+ expect((await response.json()).error).toBe('Search service not configured')
+ })
+})
+
+describe('applyScheduleRunFailureUpdate', () => {
+ it("disables a schedule at once when the run was refused Sim's hosted key", async () => {
+ const schedule = await addClaimedSchedule()
+
+ const result = await applyScheduleRunFailureUpdate({
+ scheduleId: schedule.id,
+ now: new Date(),
+ nextRunAt: new Date(Date.now() + 300_000),
+ expectedLastQueuedAt: schedule.claimedAt,
+ requestId: generateId(),
+ context: 'test',
+ failureMessage: `Agent 1: ${new HostedKeyRequiresPaidPlanError('claude-sonnet-5-5').message}`,
+ })
+
+ expect(result.disabled).toBe(true)
+ expect((await readSchedule(schedule.id))?.status).toBe('disabled')
+ expect(mockNotifyScheduleAutoDisabled).toHaveBeenCalledWith(
+ expect.objectContaining({ scheduleId: schedule.id, reason: 'paid_plan_required' })
+ )
+ })
+
+ it('keeps counting any other failure toward the consecutive-failure limit', async () => {
+ const schedule = await addClaimedSchedule()
+
+ const result = await applyScheduleRunFailureUpdate({
+ scheduleId: schedule.id,
+ now: new Date(),
+ nextRunAt: new Date(Date.now() + 300_000),
+ expectedLastQueuedAt: schedule.claimedAt,
+ requestId: generateId(),
+ context: 'test',
+ failureMessage: 'Request timed out',
+ })
+
+ expect(result.disabled).toBe(false)
+ expect(await readSchedule(schedule.id)).toEqual({ status: 'active', failedCount: 1 })
+ expect(mockNotifyScheduleAutoDisabled).not.toHaveBeenCalled()
+ })
+})
+
+describe('handleTrialWillEnd', () => {
+ it('emails the trial reminder once however often Stripe redelivers it', async () => {
+ const userId = await createUser()
+ const stripeSubscriptionId = await addSubscription(userId, 'trialing')
+ const redelivered = trialWillEnd(stripeSubscriptionId)
+
+ await handleTrialWillEnd(redelivered)
+ await handleTrialWillEnd(redelivered)
+
+ expect(mockSendEmail).toHaveBeenCalledTimes(1)
+ expect(mockSendEmail).toHaveBeenCalledWith(
+ expect.objectContaining({ to: `${userId}@free-plan.test` })
+ )
+ })
+
+ it('quotes the discounted charge from the invoice preview', async () => {
+ const userId = await createUser()
+ const stripeSubscriptionId = await addSubscription(userId, 'trialing')
+ stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 1250 })
+
+ await handleTrialWillEnd(trialWillEnd(stripeSubscriptionId))
+
+ expect(mockSendEmail.mock.calls[0]?.[0].html).toContain('$12.50/month')
+ })
+
+ it('retries a reminder whose email failed to send', async () => {
+ const userId = await createUser()
+ const stripeSubscriptionId = await addSubscription(userId, 'trialing')
+ const event = trialWillEnd(stripeSubscriptionId)
+ mockSendEmail.mockResolvedValueOnce({ success: false, message: 'Failed to send email' })
+
+ await expect(handleTrialWillEnd(event)).rejects.toThrow()
+ await handleTrialWillEnd(event)
+
+ expect(mockSendEmail).toHaveBeenCalledTimes(2)
+ })
+
+ it('sends nothing for a subscription that is no longer trialing', async () => {
+ const userId = await createUser()
+ const stripeSubscriptionId = await addSubscription(userId, 'active')
+
+ await handleTrialWillEnd(trialWillEnd(stripeSubscriptionId, 'active'))
+
+ expect(mockSendEmail).not.toHaveBeenCalled()
+ })
+})
+
+describe('endProTrial', () => {
+ function asSession(userId: string) {
+ return { kind: 'session', userId, sessionId: generateId() } as const
+ }
+
+ it("ends the caller's own trial now", async () => {
+ const userId = await createUser()
+ const stripeSubscriptionId = await addSubscription(userId, 'trialing')
+
+ await endProTrial.execute({ principal: asSession(userId), input: {} })
+
+ expect(stripeStub.subscriptions.update).toHaveBeenCalledWith(
+ stripeSubscriptionId,
+ { trial_end: 'now' },
+ expect.anything()
+ )
+ })
+
+ it('refuses an account whose plan is already paid', async () => {
+ const userId = await createUser()
+ await addSubscription(userId, 'active')
+
+ await expect(endProTrial.execute({ principal: asSession(userId), input: {} })).rejects.toThrow(
+ 'There is no free trial to end'
+ )
+ expect(stripeStub.subscriptions.update).not.toHaveBeenCalled()
+ })
+
+ it("never ends another account's trial", async () => {
+ const trialing = await createUser()
+ await addSubscription(trialing, 'trialing')
+ const caller = await createUser()
+
+ await expect(endProTrial.execute({ principal: asSession(caller), input: {} })).rejects.toThrow(
+ 'There is no free trial to end'
+ )
+ expect(stripeStub.subscriptions.update).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/sim/lib/billing/trial.ts b/apps/sim/lib/billing/trial.ts
index fe66fd550e1..d1ecb6e1602 100644
--- a/apps/sim/lib/billing/trial.ts
+++ b/apps/sim/lib/billing/trial.ts
@@ -7,6 +7,7 @@ import { PRO_CREDIT_TIER, PRO_TRIAL_DAYS } from '@/lib/billing/constants'
import { buildPlanName } from '@/lib/billing/plan-helpers'
import { requireStripeClient } from '@/lib/billing/stripe-client'
import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks'
+import type { DbClient } from '@/lib/db/types'
const logger = createLogger('ProTrial')
@@ -22,33 +23,26 @@ type TrialCheckoutParams = Pick<
>
/**
- * The Checkout parameters that start a new subscriber's Pro free trial, or none when the checkout
- * does not qualify. Only a personal checkout of the Pro tier qualifies, for an account that has
- * never trialed or held a subscription and still holds its free allowance (an account reusing a
- * deleted one's identity does not). The card is collected up front and must be a card, so its
- * fingerprint can hold it to one trial ({@link enforceOneTrialPerCard}); a trial left without a
- * payment method cancels instead of invoicing.
+ * Whether an account may start a Pro free trial: it has never trialed or held a subscription and
+ * still holds its free allowance (an account reusing a deleted one's identity does not). Abandoned
+ * checkouts do not count. The card check runs later, at checkout ({@link enforceOneTrialPerCard}).
*/
-export async function getProTrialCheckoutParams(params: {
- userId: string
- referenceId: string
- planName: string
-}): Promise {
- if (params.referenceId !== params.userId) return null
- if (params.planName !== TRIAL_PLAN) return null
-
+export async function isProTrialEligible(
+ userId: string,
+ executor: DbClient = db
+): Promise {
const [[stats], [earlierSubscription]] = await Promise.all([
- db
+ executor
.select({ freeTierEligible: userStats.freeTierEligible })
.from(userStats)
- .where(eq(userStats.userId, params.userId))
+ .where(eq(userStats.userId, userId))
.limit(1),
- db
+ executor
.select({ id: subscription.id })
.from(subscription)
.where(
and(
- eq(subscription.referenceId, params.userId),
+ eq(subscription.referenceId, userId),
or(
isNotNull(subscription.trialStart),
notInArray(subscription.status, NEVER_STARTED_STATUSES)
@@ -57,7 +51,24 @@ export async function getProTrialCheckoutParams(params: {
)
.limit(1),
])
- if (!stats?.freeTierEligible || earlierSubscription) return null
+ return Boolean(stats?.freeTierEligible) && !earlierSubscription
+}
+
+/**
+ * The Checkout parameters that start a new subscriber's Pro free trial, or none when the checkout
+ * does not qualify. Only a personal checkout of the Pro tier qualifies, for an account
+ * {@link isProTrialEligible} admits. The card is collected up front and must be a card, so its
+ * fingerprint can hold it to one trial ({@link enforceOneTrialPerCard}); a trial left without a
+ * payment method cancels instead of invoicing.
+ */
+export async function getProTrialCheckoutParams(params: {
+ userId: string
+ referenceId: string
+ planName: string
+}): Promise {
+ if (params.referenceId !== params.userId) return null
+ if (params.planName !== TRIAL_PLAN) return null
+ if (!(await isProTrialEligible(params.userId))) return null
return {
payment_method_types: ['card'],
diff --git a/apps/sim/lib/billing/usage-upgrade.ts b/apps/sim/lib/billing/usage-upgrade.ts
index 8474657df90..111b61895d5 100644
--- a/apps/sim/lib/billing/usage-upgrade.ts
+++ b/apps/sim/lib/billing/usage-upgrade.ts
@@ -14,7 +14,7 @@ const UPGRADE_PLAN_MESSAGE =
"You've reached your usage limit. Please upgrade your plan to continue."
const TRIAL_ALLOWANCE_MESSAGE =
- "You've used the credits included in your free trial. Usage is paused until your trial ends, when your plan's full allowance starts."
+ "You've used the credits included in your free trial. Usage resumes when your trial ends and your plan's full allowance starts, or start your paid plan now under Settings > Subscription."
const MEMBER_CAP_MESSAGE =
"You've reached the usage limit your organization set for you this billing period. Only an organization owner or admin can raise it — please ask them to continue."
diff --git a/apps/sim/lib/billing/webhooks/plan-notices.ts b/apps/sim/lib/billing/webhooks/plan-notices.ts
new file mode 100644
index 00000000000..238a41c0538
--- /dev/null
+++ b/apps/sim/lib/billing/webhooks/plan-notices.ts
@@ -0,0 +1,178 @@
+import { db } from '@sim/db'
+import { member, subscription, user } from '@sim/db/schema'
+import { createLogger } from '@sim/logger'
+import { getErrorMessage } from '@sim/utils/errors'
+import { and, eq } from 'drizzle-orm'
+import { getHighestPrioritySubscription } from '@/lib/billing/core/plan'
+import { getDisplayPlanName, isPaid } from '@/lib/billing/plan-helpers'
+import { requireStripeClient } from '@/lib/billing/stripe-client'
+import { formatTrialEndDate, hasPaidSubscriptionStatus } from '@/lib/billing/subscriptions/utils'
+import { stripeWebhookIdempotency } from '@/lib/billing/webhooks/idempotency'
+import { getBaseUrl } from '@/lib/core/utils/urls'
+
+const logger = createLogger('PlanNotices')
+
+async function readRecipient(userId: string) {
+ const [recipient] = await db
+ .select({ email: user.email, name: user.name })
+ .from(user)
+ .where(eq(user.id, userId))
+ .limit(1)
+ return recipient?.email ? recipient : null
+}
+
+/** The fields of a Stripe subscription the trial reminder reads. */
+export interface TrialEndingSubscription {
+ id: string
+ status: string
+ trial_end: number | null
+ items: {
+ data: Array<{
+ quantity?: number | null
+ price: { unit_amount: number | null; recurring: { interval: string } | null }
+ }>
+ }
+}
+
+function formatDollars(cents: number): string {
+ const dollars = cents / 100
+ return Number.isInteger(dollars) ? `$${dollars}` : `$${dollars.toFixed(2)}`
+}
+
+/**
+ * What the card is charged when a trial converts. Stripe's invoice preview includes any discount a
+ * promotion code applied; the subscription's list price is the fallback if the preview fails.
+ */
+async function readRenewalCharge(
+ stripeSubscription: TrialEndingSubscription
+): Promise {
+ const item = stripeSubscription.items?.data?.[0]
+ const interval = item?.price.recurring?.interval
+ if (!interval) return null
+ try {
+ const preview = await requireStripeClient().invoices.createPreview({
+ subscription: stripeSubscription.id,
+ })
+ return `${formatDollars(preview.amount_due)}/${interval}`
+ } catch (error) {
+ logger.warn('Invoice preview failed for the trial reminder; quoting the list price', {
+ stripeSubscriptionId: stripeSubscription.id,
+ error: getErrorMessage(error),
+ })
+ }
+ if (!item?.price.unit_amount) return null
+ return `${formatDollars(item.price.unit_amount * (item.quantity ?? 1))}/${interval}`
+}
+
+/**
+ * Handles Stripe's `customer.subscription.trial_will_end`, which arrives three days before a trial
+ * converts: emails the trialing account the date, the charge, and how to cancel. Sent once per
+ * subscription and trial end, however often Stripe redelivers the event.
+ */
+export async function handleTrialWillEnd(
+ stripeSubscription: TrialEndingSubscription
+): Promise {
+ const trialEnd = stripeSubscription.trial_end
+ if (stripeSubscription.status !== 'trialing' || !trialEnd) return
+
+ const [recorded] = await db
+ .select({ plan: subscription.plan, referenceId: subscription.referenceId })
+ .from(subscription)
+ .where(eq(subscription.stripeSubscriptionId, stripeSubscription.id))
+ .limit(1)
+ if (!recorded) {
+ logger.warn('Trial ending for a subscription Sim has not recorded', {
+ stripeSubscriptionId: stripeSubscription.id,
+ })
+ return
+ }
+
+ await stripeWebhookIdempotency.executeWithIdempotency(
+ 'trial-ending-reminder',
+ `${stripeSubscription.id}:${trialEnd}`,
+ async () => {
+ const recipient = await readRecipient(recorded.referenceId)
+ const price = await readRenewalCharge(stripeSubscription)
+ if (!recipient || !price) return { sent: false }
+
+ const { getTrialEndingSubject, renderTrialEndingEmail } = await import('@/components/emails')
+ const { sendEmail } = await import('@/lib/messaging/email/mailer')
+ const planName = getDisplayPlanName(recorded.plan)
+ const endsOn = formatTrialEndDate(new Date(trialEnd * 1000))
+ const html = await renderTrialEndingEmail({
+ planName,
+ userName: recipient.name || undefined,
+ endsOn,
+ price,
+ billingLink: `${getBaseUrl()}/account/settings/billing`,
+ })
+ const result = await sendEmail({
+ to: recipient.email,
+ subject: getTrialEndingSubject(planName, endsOn),
+ html,
+ emailType: 'transactional',
+ })
+ // Throwing leaves the reminder unrecorded, so Stripe's redelivery retries it.
+ if (!result.success) throw new Error('Trial reminder email failed to send')
+ return { sent: true }
+ }
+ )
+}
+
+/** The account a plan's emails go to: the user on a personal plan, the owner on an organization's. */
+async function resolvePlanOwnerId(referenceId: string): Promise {
+ const [owner] = await db
+ .select({ userId: member.userId })
+ .from(member)
+ .where(and(eq(member.organizationId, referenceId), eq(member.role, 'owner')))
+ .limit(1)
+ return owner?.userId ?? referenceId
+}
+
+/**
+ * Tells a payer whose paid plan just ended that Sim-hosted models, tools, and Chat stopped, and
+ * how to keep workflows running. Skipped when the owner is still covered by another paid plan, such
+ * as an organization's or a restored personal Pro. Never throws: a missed notice must not fail
+ * the deletion webhook that settles the final invoice.
+ */
+export async function sendPlanEndedEmail(ended: {
+ id: string
+ plan: string | null
+ referenceId: string
+}) {
+ try {
+ if (!isPaid(ended.plan)) return
+ const ownerId = await resolvePlanOwnerId(ended.referenceId)
+ const current = await getHighestPrioritySubscription(ownerId, { onError: 'throw' })
+ const stillPaid =
+ current &&
+ current.id !== ended.id &&
+ isPaid(current.plan) &&
+ hasPaidSubscriptionStatus(current.status)
+ if (stillPaid) return
+
+ const recipient = await readRecipient(ownerId)
+ if (!recipient) return
+
+ const { getPlanEndedSubject, renderPlanEndedEmail } = await import('@/components/emails')
+ const { sendEmail } = await import('@/lib/messaging/email/mailer')
+ const planName = getDisplayPlanName(ended.plan)
+ const html = await renderPlanEndedEmail({
+ planName,
+ userName: recipient.name || undefined,
+ upgradeLink: `${getBaseUrl()}/account/settings/billing`,
+ })
+ const result = await sendEmail({
+ to: recipient.email,
+ subject: getPlanEndedSubject(planName),
+ html,
+ emailType: 'transactional',
+ })
+ // A notice must not fail the deletion it follows; the error log is the alert.
+ if (!result.success) {
+ logger.error('Plan ended email failed to send', { referenceId: ended.referenceId })
+ }
+ } catch (error) {
+ logger.error('Failed to send plan ended email', { referenceId: ended.referenceId, error })
+ }
+}
diff --git a/apps/sim/lib/billing/webhooks/subscription.ts b/apps/sim/lib/billing/webhooks/subscription.ts
index b556482de00..521d8205700 100644
--- a/apps/sim/lib/billing/webhooks/subscription.ts
+++ b/apps/sim/lib/billing/webhooks/subscription.ts
@@ -19,6 +19,7 @@ import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/util
import { toDecimal, toNumber } from '@/lib/billing/utils/decimal'
import { stripeWebhookIdempotency } from '@/lib/billing/webhooks/idempotency'
import { getBilledOverageForSubscription } from '@/lib/billing/webhooks/invoices'
+import { sendPlanEndedEmail } from '@/lib/billing/webhooks/plan-notices'
import { captureServerEvent } from '@/lib/posthog/server'
import { detachOrganizationWorkspaces } from '@/lib/workspaces/organization-workspaces'
@@ -602,6 +603,7 @@ export async function handleSubscriptionDeleted(
plan: subscription.plan ?? 'unknown',
reference_id: subscription.referenceId,
})
+ await sendPlanEndedEmail(subscription)
return { totalOverage, remainingOverage, restoredProCount, workspacesDetached }
}
diff --git a/apps/sim/lib/internal/search/execute-tool.ts b/apps/sim/lib/internal/search/execute-tool.ts
index 63e4d3ef696..61ffb74a8b0 100644
--- a/apps/sim/lib/internal/search/execute-tool.ts
+++ b/apps/sim/lib/internal/search/execute-tool.ts
@@ -1,5 +1,9 @@
import { getErrorMessage } from '@sim/utils/errors'
import { z } from 'zod'
+import {
+ HostedKeyRequiresPaidPlanError,
+ mayUseHostedKey,
+} from '@/lib/billing/core/hosted-key-access'
import { executeSearchOperation } from '@/lib/internal/search/operations'
import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types'
@@ -24,6 +28,12 @@ export const executeSearchTool: InternalToolOperationHandler = async ({
return Response.json({ success: false, error: 'Invalid request data' }, { status: 400 })
}
+ // Search always runs on Sim's own key, so it is reserved for paid payers like every hosted tool.
+ if (!(await mayUseHostedKey(context.workspaceId, context.billingAttribution))) {
+ const refusal = new HostedKeyRequiresPaidPlanError('Web Search')
+ return Response.json({ success: false, error: refusal.message }, { status: refusal.statusCode })
+ }
+
try {
return Response.json(await executeSearchOperation(parsed.data, signal))
} catch (error) {
diff --git a/apps/sim/lib/workflows/schedules/disable-reasons.ts b/apps/sim/lib/workflows/schedules/disable-reasons.ts
index d6d20e67591..13849ff86fc 100644
--- a/apps/sim/lib/workflows/schedules/disable-reasons.ts
+++ b/apps/sim/lib/workflows/schedules/disable-reasons.ts
@@ -8,6 +8,7 @@ export type ScheduleDisableReason =
| 'authorization_error'
| 'workflow_not_found'
| 'invalid_schedule'
+ | 'paid_plan_required'
/**
* User-facing sentence for each reason. Fixed copy rather than the underlying
@@ -20,4 +21,6 @@ export const SCHEDULE_DISABLE_REASON_COPY: Record
authorization_error: 'The run was not authorized.',
workflow_not_found: 'The workflow could not be found.',
invalid_schedule: 'The schedule is no longer valid.',
+ paid_plan_required:
+ "It uses Sim's hosted models or tools, which need a paid plan. Add your own API key under Settings > BYOK or upgrade, then turn the schedule back on.",
}
diff --git a/packages/testing/src/mocks/email-templates.mock.ts b/packages/testing/src/mocks/email-templates.mock.ts
index b1e2c587560..e929aef0a27 100644
--- a/packages/testing/src/mocks/email-templates.mock.ts
+++ b/packages/testing/src/mocks/email-templates.mock.ts
@@ -301,6 +301,8 @@ export const emailTemplatesMockFns = {
mockLimitThresholdEmail: vi.fn((_props?: unknown): null => null),
mockPaymentFailedEmail: vi.fn((_props?: unknown): null => null),
mockPlanWelcomeEmail: vi.fn((_props?: unknown): null => null),
+ mockPlanEndedEmail: vi.fn((_props?: unknown): null => null),
+ mockTrialEndingEmail: vi.fn((_props?: unknown): null => null),
mockUsageLimitReachedEmail: vi.fn((_props?: unknown): null => null),
mockUsageThresholdEmail: vi.fn((_props?: unknown): null => null),
mockEmailButton: vi.fn((_props?: unknown): null => null),
@@ -332,6 +334,8 @@ export const emailTemplatesMockFns = {
mockRenderFreeTierUpgradeEmail: vi.fn(),
mockRenderLimitThresholdEmail: vi.fn(),
mockRenderPlanWelcomeEmail: vi.fn(),
+ mockRenderPlanEndedEmail: vi.fn(),
+ mockRenderTrialEndingEmail: vi.fn(),
mockRenderWelcomeEmail: vi.fn(),
mockRenderOnboardingFollowupEmail: vi.fn(),
mockRenderAbandonedCheckoutEmail: vi.fn(),
@@ -352,6 +356,13 @@ export const emailTemplatesMockFns = {
(planDisplayName: string): string =>
`Your ${planDisplayName} plan is now active on ${BRAND_NAME}`
),
+ mockGetTrialEndingSubject: vi.fn(
+ (planDisplayName: string, endsOn: string): string =>
+ `Your ${planDisplayName} free trial ends ${endsOn}`
+ ),
+ mockGetPlanEndedSubject: vi.fn(
+ (planDisplayName: string): string => `Your ${planDisplayName} plan has ended on ${BRAND_NAME}`
+ ),
mockGetRequestConfirmationSubject: vi.fn((userSubject: string, requestType?: string): string =>
requestType
? `Your ${requestType} request has been received: ${userSubject}`
@@ -397,6 +408,8 @@ export const emailTemplatesMock = {
LimitThresholdEmail: emailTemplatesMockFns.mockLimitThresholdEmail,
PaymentFailedEmail: emailTemplatesMockFns.mockPaymentFailedEmail,
PlanWelcomeEmail: emailTemplatesMockFns.mockPlanWelcomeEmail,
+ PlanEndedEmail: emailTemplatesMockFns.mockPlanEndedEmail,
+ TrialEndingEmail: emailTemplatesMockFns.mockTrialEndingEmail,
UsageLimitReachedEmail: emailTemplatesMockFns.mockUsageLimitReachedEmail,
UsageThresholdEmail: emailTemplatesMockFns.mockUsageThresholdEmail,
EmailButton: emailTemplatesMockFns.mockEmailButton,
@@ -429,6 +442,8 @@ export const emailTemplatesMock = {
renderFreeTierUpgradeEmail: emailTemplatesMockFns.mockRenderFreeTierUpgradeEmail,
renderLimitThresholdEmail: emailTemplatesMockFns.mockRenderLimitThresholdEmail,
renderPlanWelcomeEmail: emailTemplatesMockFns.mockRenderPlanWelcomeEmail,
+ renderPlanEndedEmail: emailTemplatesMockFns.mockRenderPlanEndedEmail,
+ renderTrialEndingEmail: emailTemplatesMockFns.mockRenderTrialEndingEmail,
renderWelcomeEmail: emailTemplatesMockFns.mockRenderWelcomeEmail,
renderOnboardingFollowupEmail: emailTemplatesMockFns.mockRenderOnboardingFollowupEmail,
renderAbandonedCheckoutEmail: emailTemplatesMockFns.mockRenderAbandonedCheckoutEmail,
@@ -442,6 +457,8 @@ export const emailTemplatesMock = {
getEmailSubject: emailTemplatesMockFns.mockGetEmailSubject,
getLimitEmailSubject: emailTemplatesMockFns.mockGetLimitEmailSubject,
getPlanWelcomeSubject: emailTemplatesMockFns.mockGetPlanWelcomeSubject,
+ getTrialEndingSubject: emailTemplatesMockFns.mockGetTrialEndingSubject,
+ getPlanEndedSubject: emailTemplatesMockFns.mockGetPlanEndedSubject,
getRequestConfirmationSubject: emailTemplatesMockFns.mockGetRequestConfirmationSubject,
getOtpSubject: emailTemplatesMockFns.mockGetOtpSubject,
getCredentialGroupInvitationSubject: