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
103 changes: 96 additions & 7 deletions apps/sim/lib/billing/free-plan.integration.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
/**
* 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).
* What the Free plan and the trial edges do against real PostgreSQL: web search and Mothership's
* fal media generation are 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, mail and fal stubbed at their clients).
*/
import { db } from '@sim/db'
import { subscription, user, userStats, workflowSchedule, workspace } from '@sim/db/schema'
import {
permissions,
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'
Expand All @@ -18,15 +25,27 @@ import {
type TrialEndingSubscription,
} from '@/lib/billing/webhooks/plan-notices'
import { executeSearchTool } from '@/lib/internal/search/execute-tool'
import type { ServerToolContext } from '@/lib/mothership/tools/server/base-tool'
import { generateAudioServerTool } from '@/lib/mothership/tools/server/media/generate-audio'
import { generateVideoServerTool } from '@/lib/mothership/tools/server/media/generate-video'
import { applyScheduleRunFailureUpdate } from '@/background/schedule-execution'

const { stripeStub, mockSendEmail, mockNotifyScheduleAutoDisabled } = vi.hoisted(() => ({
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'

const {
stripeStub,
mockSendEmail,
mockNotifyScheduleAutoDisabled,
mockGenerateFalAudio,
mockGenerateFalVideo,
} = vi.hoisted(() => ({
stripeStub: {
subscriptions: { update: vi.fn(), retrieve: vi.fn() },
invoices: { createPreview: vi.fn() },
},
mockSendEmail: vi.fn(),
mockNotifyScheduleAutoDisabled: vi.fn(),
mockGenerateFalAudio: vi.fn(),
mockGenerateFalVideo: vi.fn(),
}))

vi.mock('@/lib/core/config/env-flags', async (importOriginal) => ({
Expand All @@ -46,6 +65,9 @@ vi.mock('@/lib/workflows/schedules/disable-notifications', () => ({
notifyScheduleAutoDisabled: mockNotifyScheduleAutoDisabled,
}))

vi.mock('@/lib/media/falai-audio', () => ({ generateFalAudio: mockGenerateFalAudio }))
vi.mock('@/lib/media/falai-video', () => ({ generateFalVideo: mockGenerateFalVideo }))

const PRO_PLAN = 'pro_6000'
const DAY_MS = 86_400_000

Expand Down Expand Up @@ -77,6 +99,13 @@ async function createWorkspace(ownerId: string): Promise<string> {
billedAccountUserId: ownerId,
name: 'Free plan workspace',
})
await db.insert(permissions).values({
id: generateId(),
userId: ownerId,
entityType: 'workspace',
entityId: id,
permissionType: 'admin',
})
workspaceIds.push(id)
return id
}
Expand Down Expand Up @@ -166,13 +195,16 @@ beforeEach(() => {
liveSubscriptions.get(id)
)
mockNotifyScheduleAutoDisabled.mockReset()
mockGenerateFalAudio.mockReset().mockRejectedValue(new Error('fal reached'))
mockGenerateFalVideo.mockReset().mockRejectedValue(new Error('fal reached'))
})

afterAll(async () => {
if (scheduleIds.length > 0) {
await db.delete(workflowSchedule).where(inArray(workflowSchedule.id, scheduleIds))
}
if (workspaceIds.length > 0) {
await db.delete(permissions).where(inArray(permissions.entityId, workspaceIds))
await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds))
}
if (userIds.length > 0) {
Expand Down Expand Up @@ -208,6 +240,63 @@ describe('web search', () => {
})
})

/** The context the Copilot pipeline builds for a tool call in the payer's workspace. */
function copilotContext(userId: string, workspaceId: string): ServerToolContext {
return {
userId,
workspaceId,
toolCallId: generateId(),
copilotToolExecution: true,
resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry([]),
}
}

const MEDIA_TOOLS = [
{
name: 'video',
tool: generateVideoServerTool,
fal: mockGenerateFalVideo,
subject: 'Video generation',
},
{
name: 'audio',
tool: generateAudioServerTool,
fal: mockGenerateFalAudio,
subject: 'Audio generation',
},
] as const

describe.each(MEDIA_TOOLS)(
"Mothership $name generation on Sim's fal key",
({ tool, fal, subject }) => {
it('refuses a free payer before reaching fal', async () => {
const userId = await createUser()
const workspaceId = await createWorkspace(userId)

const result = await tool.execute(
{ prompt: 'a lighthouse at dusk' },
copilotContext(userId, workspaceId)
)

expect(result).toEqual({
success: false,
message: new HostedKeyRequiresPaidPlanError(subject, { byok: false }).message,
})
expect(fal).not.toHaveBeenCalled()
})

it('lets a paid payer through to fal', async () => {
const userId = await createUser()
const workspaceId = await createWorkspace(userId)
await addSubscription(userId, 'active')

await tool.execute({ prompt: 'a lighthouse at dusk' }, copilotContext(userId, workspaceId))

expect(fal).toHaveBeenCalledOnce()
})
}
)

describe('applyScheduleRunFailureUpdate', () => {
it("disables a schedule at once when the run was refused Sim's hosted key", async () => {
const schedule = await addClaimedSchedule()
Expand Down
11 changes: 11 additions & 0 deletions apps/sim/lib/mothership/tools/server/media/generate-audio.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import {
HostedKeyRequiresPaidPlanError,
mayUseHostedKey,
} from '@/lib/billing/core/hosted-key-access'
import { MAX_MEDIA_BYTES } from '@/lib/media/falai'
import { type AudioType, generateFalAudio } from '@/lib/media/falai-audio'
import {
Expand Down Expand Up @@ -82,6 +86,13 @@ export const generateAudioServerTool: BaseServerTool<GenerateAudioArgs, Generate
if (!params.prompt) {
return { success: false, message: 'prompt is required' }
}
// Generation always draws Sim's own fal key, so only a paid payer may run it.
if (!(await mayUseHostedKey(workspaceId, context.billingAttribution))) {
return {
success: false,
message: new HostedKeyRequiresPaidPlanError('Audio generation', { byok: false }).message,
}
}

const type = (params.type || 'speech') as AudioType
if (!VALID_TYPES.includes(type)) {
Expand Down
11 changes: 11 additions & 0 deletions apps/sim/lib/mothership/tools/server/media/generate-video.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import {
HostedKeyRequiresPaidPlanError,
mayUseHostedKey,
} from '@/lib/billing/core/hosted-key-access'
import { MAX_MEDIA_BYTES } from '@/lib/media/falai'
import { generateFalVideo } from '@/lib/media/falai-video'
import {
Expand Down Expand Up @@ -68,6 +72,13 @@ export const generateVideoServerTool: BaseServerTool<GenerateVideoArgs, Generate
if (!params.prompt) {
return { success: false, message: 'prompt is required' }
}
// Generation always draws Sim's own fal key, so only a paid payer may run it.
if (!(await mayUseHostedKey(workspaceId, context.billingAttribution))) {
return {
success: false,
message: new HostedKeyRequiresPaidPlanError('Video generation', { byok: false }).message,
}
}

try {
const outputFile = params.outputs?.files?.[0]
Expand Down
Loading