Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/docs/content/docs/platform/costs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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?',
Expand Down
21 changes: 21 additions & 0 deletions apps/sim/app/api/billing/end-trial/route.ts
Original file line number Diff line number Diff line change
@@ -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,
})
6 changes: 5 additions & 1 deletion apps/sim/app/api/billing/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 () => {
Expand Down
5 changes: 4 additions & 1 deletion apps/sim/app/api/billing/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -89,6 +91,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
data: {
...personalBilling,
upgradeWorkspaceId,
proTrialEligible,
...(organizationMembership ? { organization: organizationMembership } : {}),
},
})
Expand Down
Original file line number Diff line number Diff line change
@@ -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 <ChatPlanNoticeContent />
}

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 (
<p className='mb-4 max-w-chat text-center text-[var(--text-muted)] text-small'>
Chat with Sim is included with paid plans.{' '}
{canManageBilling ? (
<button
type='button'
onClick={openUpgrade}
className='text-[var(--text-body)] underline underline-offset-2'
>
{offersTrial ? `Start a ${PRO_TRIAL_DAYS}-day free trial` : 'Upgrade your plan'}
</button>
) : (
unavailableMessage
)}
</p>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { ChatPlanNotice } from './chat-plan-notice'
2 changes: 2 additions & 0 deletions apps/sim/app/workspace/[workspaceId]/home/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -441,6 +442,7 @@ function HomeContent({ chatId, userName, userId }: HomeProps) {
<h1 className={cn(pageHeadingClassName, 'mb-7 max-w-chat')}>
What should we get done{firstName ? `, ${firstName}` : ''}?
</h1>
<ChatPlanNotice />
<div ref={initialViewInputRef} className='relative w-full max-w-chat'>
<ChatSurfaceProvider
userId={userId}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import {
import { useUpdateOrganizationUsageLimit } from '@/hooks/queries/organization'
import { useOrganizationBillingSummary } from '@/hooks/queries/organization-billing-summary'
import {
useEndProTrial,
useInvoices,
useOpenBillingPortal,
useSubscriptionData,
Expand Down Expand Up @@ -173,6 +174,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
const { data: session } = useSession()
const betterAuthSubscription = useSubscription()
const openBillingPortal = useOpenBillingPortal()
const endProTrial = useEndProTrial()

const organizationBilling = organizationBillingData?.data
const enterpriseSelfServe = isOrganizationScope
Expand Down Expand Up @@ -652,6 +654,28 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
</div>
)}

{isTrialing && !isOrganizationScope && canManageBilling && !isCancelledAtPeriodEnd && (
<div className='flex items-center justify-between'>
<span className='text-[var(--text-body)] text-small'>
End the trial and start paying today
</span>
<Chip
disabled={endProTrial.isPending}
onClick={() =>
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
</Chip>
</div>
)}

{subscription.isPaid && weeklyRefreshDollars > 0 && (
<div className='flex items-center justify-between'>
<span className='text-[var(--text-body)] text-small'>Weekly refresh</span>
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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',
Expand Down
13 changes: 11 additions & 2 deletions apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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}`)
Expand Down Expand Up @@ -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')
Expand Down
63 changes: 51 additions & 12 deletions apps/sim/background/schedule-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -98,19 +99,49 @@ function resetScheduleInfraRetryCount(): Pick<WorkflowScheduleUpdate, 'infraRetr
*/
export function buildScheduleFailureUpdate(
now: Date,
nextRunAt: Date | null
nextRunAt: Date | null,
options: { disable?: boolean } = {}
): WorkflowScheduleUpdate {
return {
updatedAt: now,
lastQueuedAt: null,
nextRunAt,
failedCount: incrementScheduleFailedCount(),
lastFailedAt: now,
status: scheduleStatusAfterFailedCountIncrement(),
status: options.disable ? 'disabled' : scheduleStatusAfterFailedCountIncrement(),
...resetScheduleInfraRetryCount(),
}
}

/**
* Records a scheduled run that failed. A run refused Sim's hosted key because its payer is on the
* free plan fails the same way every time until the payer adds a key or upgrades, so it disables
* the schedule at once instead of after {@link MAX_CONSECUTIVE_FAILURES} identical failures.
* Disabling notifies the workspace with the reason.
*/
export async function applyScheduleRunFailureUpdate(params: {
scheduleId: string
now: Date
nextRunAt: Date | null
expectedLastQueuedAt: Date | null
requestId: string
context: string
failureMessage: string | null | undefined
}): Promise<{ updated: boolean; disabled: boolean }> {
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'
Expand Down Expand Up @@ -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}`,
Expand All @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/components/emails/auth/welcome-email.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function WelcomeEmail({ userName }: WelcomeEmailProps) {
<div style={baseStyles.divider} />

<Text style={baseStyles.footnote}>
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.
</Text>
</EmailLayout>
)
Expand Down
1 change: 1 addition & 0 deletions apps/sim/components/emails/billing/constants.ts
Original file line number Diff line number Diff line change
@@ -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' },
Expand Down
Loading
Loading