Skip to content

Commit 7afd34d

Browse files
authored
fix(billing): hold Mothership fal video and audio generation to paid payers (#10525)
1 parent f195a22 commit 7afd34d

3 files changed

Lines changed: 118 additions & 7 deletions

File tree

‎apps/sim/lib/billing/free-plan.integration.ts‎

Lines changed: 96 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
/**
2-
* What the Free plan and the trial edges do against real PostgreSQL: web search is held to paid
3-
* payers like every hosted tool, a schedule a free payer's run cannot serve turns off at once, the
4-
* trial-ending reminder goes out once per trial, and only an account's own trial can be ended
5-
* early (Stripe and mail stubbed at their clients).
2+
* What the Free plan and the trial edges do against real PostgreSQL: web search and Mothership's
3+
* fal media generation are held to paid payers like every hosted tool, a schedule a free payer's
4+
* run cannot serve turns off at once, the trial-ending reminder goes out once per trial, and only
5+
* an account's own trial can be ended early (Stripe, mail and fal stubbed at their clients).
66
*/
77
import { db } from '@sim/db'
8-
import { subscription, user, userStats, workflowSchedule, workspace } from '@sim/db/schema'
8+
import {
9+
permissions,
10+
subscription,
11+
user,
12+
userStats,
13+
workflowSchedule,
14+
workspace,
15+
} from '@sim/db/schema'
916
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
1017
import { generateId } from '@sim/utils/id'
1118
import { eq, inArray } from 'drizzle-orm'
@@ -18,15 +25,27 @@ import {
1825
type TrialEndingSubscription,
1926
} from '@/lib/billing/webhooks/plan-notices'
2027
import { executeSearchTool } from '@/lib/internal/search/execute-tool'
28+
import type { ServerToolContext } from '@/lib/mothership/tools/server/base-tool'
29+
import { generateAudioServerTool } from '@/lib/mothership/tools/server/media/generate-audio'
30+
import { generateVideoServerTool } from '@/lib/mothership/tools/server/media/generate-video'
2131
import { applyScheduleRunFailureUpdate } from '@/background/schedule-execution'
22-
23-
const { stripeStub, mockSendEmail, mockNotifyScheduleAutoDisabled } = vi.hoisted(() => ({
32+
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
33+
34+
const {
35+
stripeStub,
36+
mockSendEmail,
37+
mockNotifyScheduleAutoDisabled,
38+
mockGenerateFalAudio,
39+
mockGenerateFalVideo,
40+
} = vi.hoisted(() => ({
2441
stripeStub: {
2542
subscriptions: { update: vi.fn(), retrieve: vi.fn() },
2643
invoices: { createPreview: vi.fn() },
2744
},
2845
mockSendEmail: vi.fn(),
2946
mockNotifyScheduleAutoDisabled: vi.fn(),
47+
mockGenerateFalAudio: vi.fn(),
48+
mockGenerateFalVideo: vi.fn(),
3049
}))
3150

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

68+
vi.mock('@/lib/media/falai-audio', () => ({ generateFalAudio: mockGenerateFalAudio }))
69+
vi.mock('@/lib/media/falai-video', () => ({ generateFalVideo: mockGenerateFalVideo }))
70+
4971
const PRO_PLAN = 'pro_6000'
5072
const DAY_MS = 86_400_000
5173

@@ -77,6 +99,13 @@ async function createWorkspace(ownerId: string): Promise<string> {
7799
billedAccountUserId: ownerId,
78100
name: 'Free plan workspace',
79101
})
102+
await db.insert(permissions).values({
103+
id: generateId(),
104+
userId: ownerId,
105+
entityType: 'workspace',
106+
entityId: id,
107+
permissionType: 'admin',
108+
})
80109
workspaceIds.push(id)
81110
return id
82111
}
@@ -166,13 +195,16 @@ beforeEach(() => {
166195
liveSubscriptions.get(id)
167196
)
168197
mockNotifyScheduleAutoDisabled.mockReset()
198+
mockGenerateFalAudio.mockReset().mockRejectedValue(new Error('fal reached'))
199+
mockGenerateFalVideo.mockReset().mockRejectedValue(new Error('fal reached'))
169200
})
170201

171202
afterAll(async () => {
172203
if (scheduleIds.length > 0) {
173204
await db.delete(workflowSchedule).where(inArray(workflowSchedule.id, scheduleIds))
174205
}
175206
if (workspaceIds.length > 0) {
207+
await db.delete(permissions).where(inArray(permissions.entityId, workspaceIds))
176208
await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds))
177209
}
178210
if (userIds.length > 0) {
@@ -208,6 +240,63 @@ describe('web search', () => {
208240
})
209241
})
210242

243+
/** The context the Copilot pipeline builds for a tool call in the payer's workspace. */
244+
function copilotContext(userId: string, workspaceId: string): ServerToolContext {
245+
return {
246+
userId,
247+
workspaceId,
248+
toolCallId: generateId(),
249+
copilotToolExecution: true,
250+
resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry([]),
251+
}
252+
}
253+
254+
const MEDIA_TOOLS = [
255+
{
256+
name: 'video',
257+
tool: generateVideoServerTool,
258+
fal: mockGenerateFalVideo,
259+
subject: 'Video generation',
260+
},
261+
{
262+
name: 'audio',
263+
tool: generateAudioServerTool,
264+
fal: mockGenerateFalAudio,
265+
subject: 'Audio generation',
266+
},
267+
] as const
268+
269+
describe.each(MEDIA_TOOLS)(
270+
"Mothership $name generation on Sim's fal key",
271+
({ tool, fal, subject }) => {
272+
it('refuses a free payer before reaching fal', async () => {
273+
const userId = await createUser()
274+
const workspaceId = await createWorkspace(userId)
275+
276+
const result = await tool.execute(
277+
{ prompt: 'a lighthouse at dusk' },
278+
copilotContext(userId, workspaceId)
279+
)
280+
281+
expect(result).toEqual({
282+
success: false,
283+
message: new HostedKeyRequiresPaidPlanError(subject, { byok: false }).message,
284+
})
285+
expect(fal).not.toHaveBeenCalled()
286+
})
287+
288+
it('lets a paid payer through to fal', async () => {
289+
const userId = await createUser()
290+
const workspaceId = await createWorkspace(userId)
291+
await addSubscription(userId, 'active')
292+
293+
await tool.execute({ prompt: 'a lighthouse at dusk' }, copilotContext(userId, workspaceId))
294+
295+
expect(fal).toHaveBeenCalledOnce()
296+
})
297+
}
298+
)
299+
211300
describe('applyScheduleRunFailureUpdate', () => {
212301
it("disables a schedule at once when the run was refused Sim's hosted key", async () => {
213302
const schedule = await addClaimedSchedule()

‎apps/sim/lib/mothership/tools/server/media/generate-audio.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { createLogger } from '@sim/logger'
22
import { getErrorMessage } from '@sim/utils/errors'
3+
import {
4+
HostedKeyRequiresPaidPlanError,
5+
mayUseHostedKey,
6+
} from '@/lib/billing/core/hosted-key-access'
37
import { MAX_MEDIA_BYTES } from '@/lib/media/falai'
48
import { type AudioType, generateFalAudio } from '@/lib/media/falai-audio'
59
import {
@@ -82,6 +86,13 @@ export const generateAudioServerTool: BaseServerTool<GenerateAudioArgs, Generate
8286
if (!params.prompt) {
8387
return { success: false, message: 'prompt is required' }
8488
}
89+
// Generation always draws Sim's own fal key, so only a paid payer may run it.
90+
if (!(await mayUseHostedKey(workspaceId, context.billingAttribution))) {
91+
return {
92+
success: false,
93+
message: new HostedKeyRequiresPaidPlanError('Audio generation', { byok: false }).message,
94+
}
95+
}
8596

8697
const type = (params.type || 'speech') as AudioType
8798
if (!VALID_TYPES.includes(type)) {

‎apps/sim/lib/mothership/tools/server/media/generate-video.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { createLogger } from '@sim/logger'
22
import { getErrorMessage } from '@sim/utils/errors'
3+
import {
4+
HostedKeyRequiresPaidPlanError,
5+
mayUseHostedKey,
6+
} from '@/lib/billing/core/hosted-key-access'
37
import { MAX_MEDIA_BYTES } from '@/lib/media/falai'
48
import { generateFalVideo } from '@/lib/media/falai-video'
59
import {
@@ -68,6 +72,13 @@ export const generateVideoServerTool: BaseServerTool<GenerateVideoArgs, Generate
6872
if (!params.prompt) {
6973
return { success: false, message: 'prompt is required' }
7074
}
75+
// Generation always draws Sim's own fal key, so only a paid payer may run it.
76+
if (!(await mayUseHostedKey(workspaceId, context.billingAttribution))) {
77+
return {
78+
success: false,
79+
message: new HostedKeyRequiresPaidPlanError('Video generation', { byok: false }).message,
80+
}
81+
}
7182

7283
try {
7384
const outputFile = params.outputs?.files?.[0]

0 commit comments

Comments
 (0)