feat: implement agent scheduled execution with cron and time picker
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 1m9s

- Add scheduledTime, scheduledDay, timezone fields to Agent schema
- Create calculateNextRun() helper with timezone-aware scheduling
- Add POST /api/cron/agents endpoint for external scheduler
- Calculate nextRun on agent create, update, and after execution
- Add time/day picker in agent form (daily/weekly/monthly)
- Show "Next run" countdown in agent card
- Add i18n keys for schedule UI (FR + EN)

External scheduler (N8N, Vercel Cron) should call /api/cron/agents
every 5-15 min. Requires `prisma db push` to apply schema changes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-04-26 10:45:48 +02:00
parent dc18dc3de4
commit 73de1cd26d
10 changed files with 439 additions and 1 deletions

View File

@@ -120,6 +120,9 @@ export function AgentsPageClient({
maxSteps: formData.get('maxSteps') ? Number(formData.get('maxSteps')) : undefined,
notifyEmail: formData.get('notifyEmail') === 'true',
includeImages: formData.get('includeImages') === 'true',
scheduledTime: (formData.get('scheduledTime') as string) || undefined,
scheduledDay: formData.get('scheduledDay') ? Number(formData.get('scheduledDay')) : undefined,
timezone: (formData.get('timezone') as string) || undefined,
}
if (editingAgent) {

View File

@@ -8,6 +8,7 @@
import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { calculateNextRun } from '@/lib/agents/schedule'
// --- CRUD ---
@@ -24,6 +25,9 @@ export async function createAgent(data: {
maxSteps?: number
notifyEmail?: boolean
includeImages?: boolean
scheduledTime?: string
scheduledDay?: number
timezone?: string
}) {
const session = await auth()
if (!session?.user?.id) {
@@ -45,10 +49,30 @@ export async function createAgent(data: {
maxSteps: data.maxSteps || 10,
notifyEmail: data.notifyEmail || false,
includeImages: data.includeImages || false,
scheduledTime: data.scheduledTime || '08:00',
scheduledDay: data.scheduledDay ?? null,
timezone: data.timezone || null,
userId: session.user.id,
}
})
// Calculate nextRun for scheduled agents
const freq = data.frequency || 'manual'
if (freq !== 'manual') {
const nextRun = calculateNextRun({
frequency: freq,
scheduledTime: data.scheduledTime || '08:00',
scheduledDay: data.scheduledDay,
timezone: data.timezone,
})
if (nextRun) {
await prisma.agent.update({
where: { id: agent.id },
data: { nextRun },
})
}
}
revalidatePath('/agents')
return { success: true, agent }
} catch (error) {
@@ -71,6 +95,9 @@ export async function updateAgent(id: string, data: {
maxSteps?: number
notifyEmail?: boolean
includeImages?: boolean
scheduledTime?: string
scheduledDay?: number | null
timezone?: string
}) {
const session = await auth()
if (!session?.user?.id) {
@@ -97,6 +124,31 @@ export async function updateAgent(id: string, data: {
if (data.maxSteps !== undefined) updateData.maxSteps = data.maxSteps
if (data.notifyEmail !== undefined) updateData.notifyEmail = data.notifyEmail
if (data.includeImages !== undefined) updateData.includeImages = data.includeImages
if (data.scheduledTime !== undefined) updateData.scheduledTime = data.scheduledTime
if (data.scheduledDay !== undefined) updateData.scheduledDay = data.scheduledDay
if (data.timezone !== undefined) updateData.timezone = data.timezone
// Recalculate nextRun when scheduling fields change
const shouldRecalcNextRun =
data.frequency !== undefined ||
data.scheduledTime !== undefined ||
data.scheduledDay !== undefined ||
data.timezone !== undefined
if (shouldRecalcNextRun) {
const freq = data.frequency || existing.frequency
if (freq === 'manual') {
updateData.nextRun = null
} else {
const nextRun = calculateNextRun({
frequency: freq,
scheduledTime: data.scheduledTime || existing.scheduledTime || '08:00',
scheduledDay: data.scheduledDay ?? existing.scheduledDay,
timezone: data.timezone || existing.timezone,
})
updateData.nextRun = nextRun
}
}
const agent = await prisma.agent.update({
where: { id },

View File

@@ -0,0 +1,102 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { calculateNextRun } from '@/lib/agents/schedule'
export const dynamic = 'force-dynamic'
/**
* POST /api/cron/agents
*
* Finds all enabled, non-manual agents whose nextRun <= now,
* executes them, and schedules the next run.
*
* Optional auth: set CRON_SECRET env var, callers must pass
* Authorization: Bearer <CRON_SECRET>
*/
export async function POST(request: NextRequest) {
// Optional auth
const cronSecret = process.env.CRON_SECRET
if (cronSecret) {
const authHeader = request.headers.get('authorization')
if (authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
}
try {
const now = new Date()
const dueAgents = await prisma.agent.findMany({
where: {
isEnabled: true,
frequency: { not: 'manual' },
nextRun: { lte: now },
},
select: {
id: true,
userId: true,
frequency: true,
scheduledTime: true,
scheduledDay: true,
timezone: true,
},
})
if (dueAgents.length === 0) {
return NextResponse.json({ success: true, executed: 0 })
}
const results: { id: string; success: boolean; error?: string }[] = []
// Execute agents sequentially to avoid overwhelming the AI provider
for (const agent of dueAgents) {
try {
const { executeAgent } = await import('@/lib/ai/services/agent-executor.service')
const result = await executeAgent(agent.id, agent.userId)
// Calculate and set next run
const nextRun = calculateNextRun({
frequency: agent.frequency,
scheduledTime: agent.scheduledTime,
scheduledDay: agent.scheduledDay,
timezone: agent.timezone,
})
await prisma.agent.update({
where: { id: agent.id },
data: { nextRun },
})
results.push({ id: agent.id, success: result.success, error: result.error })
} catch (error) {
const msg = error instanceof Error ? error.message : 'Unknown error'
console.error(`[CronAgents] Agent ${agent.id} failed:`, msg)
results.push({ id: agent.id, success: false, error: msg })
// Still schedule next run even on failure
const nextRun = calculateNextRun({
frequency: agent.frequency,
scheduledTime: agent.scheduledTime,
scheduledDay: agent.scheduledDay,
timezone: agent.timezone,
})
await prisma.agent.update({
where: { id: agent.id },
data: { nextRun },
})
}
}
return NextResponse.json({
success: true,
executed: results.length,
results,
})
} catch (error) {
console.error('[CronAgents] Error:', error)
return NextResponse.json(
{ success: false, error: 'Internal Server Error' },
{ status: 500 }
)
}
}