Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Chore/cron ai nudges (#30527)

Terry Sutton4fb9b5848617
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
index 524b5915c96..c3130c51d6f 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
@@ -17,7 +17,6 @@ import {
Button,
Form_Shadcn_,
FormControl_Shadcn_,
- FormDescription_Shadcn_,
FormField_Shadcn_,
FormLabel_Shadcn_,
Input_Shadcn_,
@@ -35,7 +34,13 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { CRONJOB_DEFINITIONS } from './CronJobs.constants'
-import { buildCronQuery, buildHttpRequestCommand, parseCronJobCommand } from './CronJobs.utils'
+import {
+ buildCronQuery,
+ buildHttpRequestCommand,
+ cronPattern,
+ secondsPattern,
+ parseCronJobCommand,
+} from './CronJobs.utils'
import { CronJobScheduleSection } from './CronJobScheduleSection'
import { EdgeFunctionSection } from './EdgeFunctionSection'
import { HTTPHeaderFieldsSection } from './HttpHeaderFieldsSection'
@@ -44,8 +49,6 @@ import { HttpRequestSection } from './HttpRequestSection'
import { SqlFunctionSection } from './SqlFunctionSection'
import { SqlSnippetSection } from './SqlSnippetSection'
import EnableExtensionModal from 'components/interfaces/Database/Extensions/EnableExtensionModal'
-import { checkDomainOfScale } from 'recharts/types/util/ChartUtils'
-import { InfoIcon } from 'lucide-react'
export interface CreateCronJobSheetProps {
selectedCronJob?: Pick<CronJob, 'jobname' | 'schedule' | 'active' | 'command'>
@@ -94,13 +97,18 @@ const FormSchema = z.object({
.trim()
.min(1)
.refine((value) => {
- try {
- CronToString(value)
- } catch {
- return false
+ if (cronPattern.test(value)) {
+ try {
+ CronToString(value)
+ return true
+ } catch {
+ return false
+ }
+ } else if (secondsPattern.test(value)) {
+ return true
}
- return true
- }, 'The schedule needs to be in a Cron format.'),
+ return false
+ }, 'The schedule needs to be in a valid Cron format or specify seconds like "x seconds".'),
values: z.discriminatedUnion('type', [
edgeFunctionSchema,
httpRequestSchema,
@@ -135,7 +143,7 @@ export const CreateCronJobSheet = ({
resolver: zodResolver(FormSchema),
defaultValues: {
name: selectedCronJob?.jobname || '',
- schedule: selectedCronJob?.schedule || '* * * * * *',
+ schedule: selectedCronJob?.schedule || '*/5 * * * *',
values: cronJobValues,
},
})
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx
index 5adbd02dd10..f77e38953c5 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx
@@ -26,17 +26,19 @@ import {
import { Input } from 'ui-patterns/DataInputs/Input'
import { CreateCronJobForm } from './CreateCronJobSheet'
import CronSyntaxChart from './CronSyntaxChart'
+import { secondsPattern } from './CronJobs.utils'
interface CronJobScheduleSectionProps {
form: UseFormReturn<CreateCronJobForm>
}
-const presets = [
- { name: 'Every minute', expression: '* * * * * *' },
+const PRESETS = [
+ { name: 'Every minute', expression: '* * * * *' },
{ name: 'Every 5 minutes', expression: '*/5 * * * *' },
{ name: 'Every first of the month, at 00:00', expression: '0 0 1 * *' },
- { name: 'Every Monday at midnight', expression: '0 0 * * 1' },
- { name: 'Every night at midnight', expression: '0 0 0 * * *' },
+ { name: 'Every night at midnight', expression: '0 0 * * *' },
+ { name: 'Every Monday at 2 AM', expression: '0 2 * * 1' },
+ { name: 'Every 30 seconds', expression: '30 seconds' },
] as const
export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) => {
@@ -46,7 +48,7 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
const [presetValue, setPresetValue] = useState<string>(initialValue)
const [inputValue, setInputValue] = useState(initialValue)
- const [debouncedValue] = useDebounce(inputValue, 500)
+ const [debouncedValue] = useDebounce(inputValue, 750)
const [useNaturalLanguage, setUseNaturalLanguage] = useState(false)
const [scheduleString, setScheduleString] = useState('')
@@ -78,19 +80,31 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
}, [debouncedValue, useNaturalLanguage])
useEffect(() => {
- if (!inputValue) return
+ if (!inputValue || inputValue.length < 5) return // set a min length before showing invalid message
// update the cronstrue string when the input value changes
try {
setScheduleString(CronToString(inputValue))
form.setValue('schedule', inputValue)
- } catch {}
+ } catch (error) {
+ console.error('Error converting cron expression to string:', error)
+ }
}, [form, inputValue])
useEffect(() => {
- if (!useNaturalLanguage) {
- setPresetValue(schedule)
+ if (useNaturalLanguage) return
+
+ setPresetValue(schedule)
+
+ if (!schedule) {
+ setScheduleString('')
+ return
+ }
+
+ try {
setScheduleString(CronToString(schedule))
+ } catch (error) {
+ console.error('Error converting cron expression to string:', error)
}
}, [schedule])
@@ -113,6 +127,11 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
value={inputValue}
placeholder="E.g. every 5 minutes"
className={cn(!useNaturalLanguage && 'hidden')}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ }
+ }}
onChange={(e) => setInputValue(e.target.value)}
/>
) : (
@@ -136,6 +155,7 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
setInputValue('')
setPresetValue('')
setScheduleString('')
+ form.setValue('schedule', '')
}}
/>
<p className="text-sm text-foreground-light">Use natural language</p>
@@ -143,7 +163,7 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
<div className="mt-2">
<ul className="flex gap-2 flex-wrap mt-2">
- {presets.map((preset) => (
+ {PRESETS.map((preset) => (
<li key={preset.name}>
<Button
type="outline"
@@ -183,46 +203,38 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
isGeneratingCron ? 'animate-pulse text-foreground-lighter' : 'text-foreground'
)}
>
- {isGeneratingCron ? <CronSyntaxLoader /> : presetValue || '* * * * * *'}
+ {isGeneratingCron ? <CronSyntaxLoader /> : presetValue || '* * * * *'}
</span>
) : (
<span className="text-xl font-mono text-foreground-lighter">
- {isGeneratingCron ? <CronSyntaxLoader /> : presetValue || '* * * * * *'}
+ {isGeneratingCron ? <CronSyntaxLoader /> : presetValue || '* * * * *'}
</span>
)}
{!inputValue && !isGeneratingCron && !scheduleString ? (
<span className="text-sm text-foreground-light">
Describe your schedule above
</span>
- ) : scheduleString ? (
+ ) : (
<span className="text-sm text-foreground-light flex items-center gap-2">
- The cron will be run {/* lowercase the first letter */}
{isGeneratingCron ? (
- <span className="inline-flex items-center">
- {[0, 1, 2].map((i) => (
- <motion.span
- key={i}
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- transition={{
- duration: 0.5,
- repeat: Infinity,
- repeatType: 'reverse',
- delay: i * 0.2,
- }}
- >
- .
- </motion.span>
- ))}
- </span>
+ <LoadingDots />
+ ) : scheduleString === '' ? ( // set a min length before showing invalid message
+ 'Enter a valid cron expression above'
+ ) : scheduleString.includes('Invalid cron expression') ? (
+ 'Invalid cron expression'
) : (
- scheduleString
- .split(' ')
- .map((s, i) => (i === 0 ? s.toLocaleLowerCase() : s))
- .join(' ') + '.'
+ <>
+ The cron will be run{' '}
+ {secondsPattern.test(schedule)
+ ? 'every ' + schedule
+ : scheduleString
+ .split(' ')
+ .map((s, i) => (i === 0 ? s.toLocaleLowerCase() : s))
+ .join(' ') + '.'}
+ </>
)}
</span>
- ) : null}
+ )}
</div>
</FormItem_Shadcn_>
)
@@ -235,7 +247,7 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
const CronSyntaxLoader = () => {
return (
<div className="flex gap-2">
- {['*', '*', '*', '*', '*', '*'].map((char, i) => (
+ {['*', '*', '*', '*', '*'].map((char, i) => (
<motion.span
key={i}
initial={{ opacity: 0.3 }}
@@ -253,3 +265,25 @@ const CronSyntaxLoader = () => {
</div>
)
}
+
+const LoadingDots = () => {
+ return (
+ <span className="inline-flex items-center">
+ {[0, 1, 2].map((i) => (
+ <motion.span
+ key={i}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{
+ duration: 0.5,
+ repeat: Infinity,
+ repeatType: 'reverse',
+ delay: i * 0.2,
+ }}
+ >
+ .
+ </motion.span>
+ ))}
+ </span>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
index e54f33da4e8..ad1dab0ead7 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
@@ -1,5 +1,5 @@
import { it } from 'vitest'
-import { parseCronJobCommand } from './CronJobs.utils'
+import { parseCronJobCommand, secondsPattern, cronPattern } from './CronJobs.utils'
describe('parseCronJobCommand', () => {
it('should return a default object when the command is null', () => {
@@ -34,4 +34,38 @@ describe('parseCronJobCommand', () => {
type: 'edge_function',
})
})
+
+ // Array of test cases for secondsPattern
+ const secondsPatternTests = [
+ { description: '10 seconds', command: '10 seconds' },
+ { description: '30 seconds', command: '30 seconds' },
+ ]
+
+ // Run tests for secondsPattern
+ secondsPatternTests.forEach(({ description, command }) => {
+ it(`should match the regex for a secondsPattern with "${description}"`, () => {
+ expect(command).toMatch(secondsPattern)
+ })
+ })
+
+ // Array of test cases for cronPattern
+ const cronPatternTests = [
+ { description: 'every hour', command: '0 * * * *' },
+ { description: 'every day at midnight', command: '0 0 * * *' },
+ { description: 'every Monday at 9 AM', command: '0 9 * * 1' },
+ { description: 'every 15th of the month at noon', command: '0 12 15 * *' },
+ { description: 'every January 1st at 3 AM', command: '0 3 1 1 *' },
+ { description: 'every 30 minutes', command: '30 * * * *' },
+ { description: 'every weekday at 6 PM', command: '0 18 * * 1-5' },
+ { description: 'every weekend at 10 AM', command: '0 10 * * 0,6' },
+ { description: 'every quarter hour', command: '*/15 * * * *' },
+ { description: 'twice daily at 8 AM and 8 PM', command: '0 8,20 * * *' },
+ ]
+
+ // Replace the single cronPattern test with forEach
+ cronPatternTests.forEach(({ description, command }) => {
+ it(`should match the regex for a cronPattern with "${description}"`, () => {
+ expect(command).toMatch(cronPattern)
+ })
+ })
})
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
index f316468e5cf..af9f02fa528 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
@@ -110,3 +110,8 @@ export const parseCronJobCommand = (originalCommand: string): CronJobType => {
return DEFAULT_CRONJOB_COMMAND
}
+
+// detect seconds like "10 seconds" or normal cron syntax like "*/5 * * * *"
+export const secondsPattern = /^\d+\s+seconds$/
+export const cronPattern =
+ /^(\*|(\d+|\*\/\d+)|\d+\/\d+|\d+-\d+|\d+(,\d+)*)(\s+(\*|(\d+|\*\/\d+)|\d+\/\d+|\d+-\d+|\d+(,\d+)*)){4}$/
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronSyntaxChart.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronSyntaxChart.tsx
index 6bd57df71d3..30d4c97ac8b 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronSyntaxChart.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronSyntaxChart.tsx
@@ -4,14 +4,13 @@ export default function CronSyntaxChart() {
<pre className="text-xs font-mono text-foreground-light">
{/* prettier-ignore */}
{`
-┌───────────── second (0 - 59)
-│ ┌───────────── minute (0 - 59)
-│ │ ┌───────────── hour (0 - 23)
-│ │ │ ┌───────────── day of month (1 - 31)
-│ │ │ │ ┌───────────── month (1 - 12)
-│ │ │ │ │ ┌───────────── day of week (0 - 7)
-│ │ │ │ │ │
-* * * * * * `}
+ ┌───────────── minute (0 - 59)
+ │ ┌───────────── hour (0 - 23)
+ │ │ ┌───────────── day of month (1 - 31)
+ │ │ │ ┌───────────── month (1 - 12)
+ │ │ │ │ ┌───────────── day of week (0 - 7)
+ │ │ │ │ │
+ * * * * * `}
</pre>
</div>
)
diff --git a/packages/ai-commands/src/sql/cron.ts b/packages/ai-commands/src/sql/cron.ts
index c9f0ce5fdb1..27df01ec0fd 100644
--- a/packages/ai-commands/src/sql/cron.ts
+++ b/packages/ai-commands/src/sql/cron.ts
@@ -12,28 +12,37 @@ export async function generateCron(openai: OpenAI, prompt: string) {
You are a cron syntax expert. Your purpose is to convert natural language time descriptions into valid cron expressions for pg_cron.
Rules for responses:
- - Output cron expressions in the 6-field format supported by pg_cron (seconds minute hour day month weekday)
- - The seconds field is optional - if not specified, it defaults to 0
- - Provide a brief explanation of what the cron expression does
+ - Output cron expressions in the 5-field format supported by pg_cron
+ - Do not provide any explanation of what the cron expression does
- Format output as markdown with the cron expression in a code block
- - If the request is unclear or impossible, ask for clarification
- - If the request isn't related to cron scheduling, explain that you can only help with cron expressions
+ - Do not ask for clarification if you need it. Just output the cron expression.
Example input: "Every Monday at 3am"
Example output:
This cron expression runs every Monday at 3:00:00 AM:
\`\`\`
- 0 0 3 * * 1
+ 0 3 * * 1
\`\`\`
- Common patterns to remember:
- - * means "every" for that field
- - */n means "every n intervals"
- - n means "exactly at n"
- - n,m means "at n and m"
- - n-m means "every value from n to m"
- Field order: seconds (0-59), minute (0-59), hour (0-23), day (1-31), month (1-12), weekday (0-6, Sunday=0)
+ This cron expression runs every minute:
+ \`\`\`
+ * * * * *
+ \`\`\`
+
+ Additional examples:
+ - Every minute: \`* * * * *\`
+ - Every 5 minutes: \`*/5 * * * *\`
+ - Every first of the month, at 00:00: \`0 0 1 * *\`
+ - Every night at midnight: \`0 0 * * *\`
+ - Every Monday at 2am: \`0 2 * * 1\`
+
+ Field order:
+ - minute (0-59)
+ - hour (0-23)
+ - day (1-31)
+ - month (1-12)
+ - weekday (0-6, Sunday=0)
Here is the user's prompt:
${prompt}