Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(task): render cron weekday ranges correctly (#23683)

Max-Reisinger9df9d682c042
diff --git a/packages/utils/src/cronEval.test.ts b/packages/utils/src/cronEval.test.ts
index 80a76f6724f..01ce7ea8f0e 100644
--- a/packages/utils/src/cronEval.test.ts
+++ b/packages/utils/src/cronEval.test.ts
@@ -7,6 +7,7 @@ import {
isCronOccurrence,
isExecutionTime,
isPreciseSchedulePattern,
+ parseCronWeekdays,
snapScheduleToStandardMinute,
validateCronPattern,
validateScheduleUpdate,
@@ -581,3 +582,18 @@ describe('snapScheduleToStandardMinute', () => {
expect(snapScheduleToStandardMinute('*/15 * * * *')).toBe('*/15 * * * *');
});
});
+
+describe('parseCronWeekdays', () => {
+ it('expands weekday names, ranges, lists, steps, and Sunday alias 7', () => {
+ expect(parseCronWeekdays('30 9 * * MON-FRI')).toEqual([1, 2, 3, 4, 5]);
+ expect(parseCronWeekdays('30 9 * * 1-5/2')).toEqual([1, 3, 5]);
+ expect(parseCronWeekdays('30 9 * * 6-7')).toEqual([0, 6]);
+ });
+
+ it('returns an empty array for qualified or invalid weekday fields', () => {
+ expect(parseCronWeekdays('30 9 * * FRI#2')).toEqual([]);
+ expect(parseCronWeekdays('30 9 * * 5L')).toEqual([]);
+ expect(parseCronWeekdays('30 9 * * MON-INVALID')).toEqual([]);
+ expect(parseCronWeekdays('invalid')).toEqual([]);
+ });
+});
diff --git a/packages/utils/src/cronEval.ts b/packages/utils/src/cronEval.ts
index 1b8aebf9a87..c954bcb817f 100644
--- a/packages/utils/src/cronEval.ts
+++ b/packages/utils/src/cronEval.ts
@@ -64,6 +64,18 @@ const parseCron = (cronPattern: string, timezone: string | null, currentDate: Da
return CronExpressionParser.parse(pattern, { currentDate, tz });
};
+/** Expand cron weekdays for a weekly picker. Sunday is 0 in the picker. */
+export const parseCronWeekdays = (cronPattern: string): number[] => {
+ try {
+ const { dayOfWeek } = parseCron(cronPattern, null, new Date()).fields;
+ if (dayOfWeek.nthDay || dayOfWeek.hasLastChar) return [];
+
+ return [...new Set(dayOfWeek.values.map((day) => Number(day) % 7))].sort((a, b) => a - b);
+ } catch {
+ return [];
+ }
+};
+
/**
* Find the occurrence a cron pattern is due for on this dispatcher tick, or
* `null` when nothing is due. The returned instant identifies the occurrence,
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.test.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.test.ts
index 31be2c282ac..f82b1a86e29 100644
--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.test.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.test.ts
@@ -1,11 +1,28 @@
import dayjs from 'dayjs';
import { describe, expect, it } from 'vitest';
-import { buildCronPattern, getMinuteChoices, parseCronPattern } from './CronConfig';
+import {
+ buildCronPattern,
+ getMinuteChoices,
+ parseCronPattern,
+ updateCronPatternField,
+} from './CronConfig';
import { formatScheduleDescription } from './helpers';
const time = (hour: number, minute: number) => dayjs().hour(hour).minute(minute);
+describe('updateCronPatternField', () => {
+ it('updates only the requested cron field and preserves qualifiers', () => {
+ expect(updateCronPatternField('30 9 * * FRI#2', 1, '10')).toBe('30 10 * * FRI#2');
+ expect(updateCronPatternField('30 9 * * 5L', 0, '0')).toBe('0 9 * * 5L');
+ expect(updateCronPatternField('30 9 * * MON-FRI', 1, '8')).toBe('30 8 * * MON-FRI');
+ });
+
+ it('returns null for non-5-field expressions', () => {
+ expect(updateCronPatternField('invalid', 1, '10')).toBeNull();
+ });
+});
+
describe('buildCronPattern', () => {
it('keeps the exact minute for every frequency', () => {
expect(buildCronPattern('daily', time(9, 17))).toBe('17 9 * * *');
@@ -32,6 +49,10 @@ describe('parseCronPattern', () => {
expect(parseCronPattern('*/15 * * * *').triggerMinute).toBe(0);
expect(parseCronPattern('* 9 * * *').triggerMinute).toBe(0);
});
+
+ it('normalizes Sunday when a range includes the alias 7', () => {
+ expect(parseCronPattern('30 9 * * 6-7').weekdays).toEqual([0, 6]);
+ });
});
describe('getMinuteChoices', () => {
@@ -61,6 +82,24 @@ describe('formatScheduleDescription', () => {
expect(formatScheduleDescription('5 9 * * 1', t)).toContain('"time":"09:05"');
});
+ it.each(['MON-FRI', '1-5', '1,2,3,4,5'])('shows all weekdays at 09:30 for %s', (weekdayField) => {
+ const days = ['mon', 'tue', 'wed', 'thu', 'fri']
+ .map((weekday) => `taskSchedule.weekdays.${weekday}`)
+ .join('/');
+
+ expect(formatScheduleDescription(`30 9 * * ${weekdayField}`, t)).toBe(
+ `taskSchedule.summary.weekly:{"days":"${days}","time":"09:30"}`,
+ );
+ });
+
+ it.each(['MON-INVALID', 'FRI#2', '5L'])(
+ 'shows the original expression when %s cannot be rendered as a weekly schedule',
+ (weekdayField) => {
+ const pattern = `30 9 * * ${weekdayField}`;
+ expect(formatScheduleDescription(pattern, t)).toBe(pattern);
+ },
+ );
+
it('names an exact minute for hourly schedules', () => {
expect(formatScheduleDescription('5 * * * *', t)).toBe(
'taskSchedule.summary.hourlyAtMinute:{"minute":"05"}',
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.ts
index 2e7300b04d4..85d56983552 100644
--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/CronConfig.ts
@@ -1,3 +1,4 @@
+import { parseCronWeekdays } from '@lobechat/utils/cronEval';
import { type Dayjs } from 'dayjs';
export type ScheduleType = 'daily' | 'hourly' | 'weekly';
@@ -102,7 +103,7 @@ export const parseCronPattern = (
triggerMinute: number;
weekdays?: number[];
} => {
- const parts = cronPattern.split(' ');
+ const parts = cronPattern.trim().split(/\s+/);
if (parts.length !== 5) {
return { scheduleType: 'daily', triggerHour: 0, triggerMinute: 0 };
}
@@ -123,13 +124,33 @@ export const parseCronPattern = (
const triggerHour = Number.parseInt(hour);
if (weekday !== '*') {
- const weekdays = weekday.split(',').map((d) => Number.parseInt(d));
- return { scheduleType: 'weekly', triggerHour, triggerMinute, weekdays };
+ return {
+ scheduleType: 'weekly',
+ triggerHour,
+ triggerMinute,
+ weekdays: parseCronWeekdays(cronPattern),
+ };
}
return { scheduleType: 'daily', triggerHour, triggerMinute };
};
+/**
+ * Replace a single field in a standard 5-field cron expression while preserving
+ * all other fields (for example, weekday qualifiers such as `FRI#2` or `5L`).
+ * Returns `null` when the pattern is not a 5-field expression.
+ */
+export const updateCronPatternField = (
+ cronPattern: string,
+ fieldIndex: 0 | 1 | 2 | 3 | 4,
+ value: string,
+): string | null => {
+ const parts = cronPattern.trim().split(/\s+/);
+ if (parts.length !== 5) return null;
+ parts[fieldIndex] = value;
+ return parts.join(' ');
+};
+
/**
* Build cron pattern (minute hour day month weekday) from editable schedule info.
*/
@@ -152,7 +173,10 @@ export const buildCronPattern = (
return `${minute} ${hour} * * *`;
}
case 'weekly': {
- const days = weekdays && weekdays.length > 0 ? weekdays.sort().join(',') : '0,1,2,3,4,5,6';
+ const days =
+ weekdays && weekdays.length > 0
+ ? [...weekdays].sort((a, b) => a - b).join(',')
+ : '0,1,2,3,4,5,6';
return `${minute} ${hour} * * ${days}`;
}
}
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
index 9bd1f0a5a0c..32eeb874421 100644
--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/SchedulerForm.tsx
@@ -11,24 +11,27 @@ import {
Text,
ToggleGroup,
} from '@lobehub/ui';
-import dayjs, { type Dayjs } from 'dayjs';
import { Globe, Hash, SlidersHorizontal } from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useBusinessPreciseSchedule } from '@/business/client/hooks/useBusinessPreciseSchedule';
import { densityVars } from '@/styles/densityVars';
import {
- buildCronPattern,
getMinuteChoices,
- parseCronPattern,
SCHEDULE_TYPE_OPTIONS,
- type ScheduleType,
TIMEZONE_OPTIONS,
type TimezoneOption,
WEEKDAYS,
} from './CronConfig';
+import {
+ CUSTOM_MINUTE_UPGRADE,
+ type SchedulerFormChange,
+ useSchedulerForm,
+} from './useSchedulerForm';
+
+export type { SchedulerFormChange } from './useSchedulerForm';
const styles = createStaticStyles(({ css, cssVar }) => ({
fieldLabel: css`
@@ -51,22 +54,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const DEFAULT_PATTERN = '0 9 * * *';
-const DEFAULT_TIMEZONE = 'UTC';
-
const pad = (n: number) => String(n).padStart(2, '0');
const HOUR_OPTIONS = Array.from({ length: 24 }, (_, hour) => ({ label: pad(hour), value: hour }));
-/** Sentinel minute option that opens the upgrade flow instead of changing the value. */
-const CUSTOM_MINUTE_UPGRADE = -1;
-
-export interface SchedulerFormChange {
- maxExecutions: number | null;
- pattern: string;
- timezone: string;
-}
-
interface SchedulerFormProps {
maxExecutions?: number | null;
onChange: (change: SchedulerFormChange) => void;
@@ -83,135 +74,23 @@ const SchedulerForm = memo<SchedulerFormProps>(({ maxExecutions, onChange, patte
[t],
);
- // Local state seeded once from props at mount; never re-synced. Keeps the
- // form in user control even if an unrelated detail refresh runs concurrently.
- // Parent should `key={taskId}` this component to remount cleanly across tasks.
- const [initial] = useState(() => {
- const parsed = parseCronPattern(pattern || DEFAULT_PATTERN);
- return {
- ...parsed,
- triggerTime: dayjs().hour(parsed.triggerHour).minute(parsed.triggerMinute),
- };
- });
-
- const [scheduleType, setScheduleType] = useState<ScheduleType>(initial.scheduleType);
- const [triggerTime, setTriggerTime] = useState<Dayjs>(initial.triggerTime);
- const [hourlyInterval, setHourlyInterval] = useState<number>(initial.hourlyInterval ?? 1);
- const [weekdays, setWeekdays] = useState<number[]>(
- initial.weekdays ?? (initial.scheduleType === 'weekly' ? [1, 2, 3, 4, 5] : []),
- );
- const [tz, setTz] = useState<string>(timezone || DEFAULT_TIMEZONE);
- const [maxExec, setMaxExec] = useState<number | null>(maxExecutions ?? null);
- const [continuous, setContinuous] = useState<boolean>(
- maxExecutions === null || maxExecutions === undefined,
- );
-
- const emit = useCallback(
- (
- overrides: Partial<{
- hourlyInterval: number;
- maxExec: number | null;
- scheduleType: ScheduleType;
- triggerTime: Dayjs;
- tz: string;
- weekdays: number[];
- }>,
- ) => {
- // When the user is mid-editing maxExec (cleared the input but hasn't
- // typed yet), local maxExec is null but `continuous` is still false.
- // Falling back to the persisted prop here avoids emitting null for an
- // unrelated field change β€” which would otherwise flip Continuous on.
- const fallbackMaxExec = continuous ? null : (maxExec ?? maxExecutions ?? null);
- const next = {
- hourlyInterval: overrides.hourlyInterval ?? hourlyInterval,
- maxExec: overrides.maxExec === undefined ? fallbackMaxExec : overrides.maxExec,
- scheduleType: overrides.scheduleType ?? scheduleType,
- triggerTime: overrides.triggerTime ?? triggerTime,
- tz: overrides.tz ?? tz,
- weekdays: overrides.weekdays ?? weekdays,
- };
- const nextPattern = buildCronPattern(
- next.scheduleType,
- next.triggerTime,
- next.hourlyInterval,
- next.weekdays,
- );
- onChange({ maxExecutions: next.maxExec, pattern: nextPattern, timezone: next.tz });
- },
- [
- continuous,
- hourlyInterval,
- maxExec,
- maxExecutions,
- onChange,
- scheduleType,
- triggerTime,
- tz,
- weekdays,
- ],
- );
-
- const handleScheduleTypeChange = (value: ScheduleType) => {
- const nextWeekdays = value === 'weekly' ? (weekdays.length ? weekdays : [1, 2, 3, 4, 5]) : [];
- setScheduleType(value);
- setWeekdays(nextWeekdays);
- emit({ scheduleType: value, weekdays: nextWeekdays });
- };
-
- const handleHourChange = (hour: number) => {
- const next = triggerTime.hour(hour);
- setTriggerTime(next);
- emit({ triggerTime: next });
- };
-
- const handleMinuteChange = (minute: number) => {
- if (minute === CUSTOM_MINUTE_UPGRADE) {
- onUpgrade?.();
- return;
- }
- const next = triggerTime.minute(minute);
- setTriggerTime(next);
- emit({ triggerTime: next });
- };
-
- const handleHourlyIntervalChange = (value: number | string | null) => {
- const next = typeof value === 'number' && value > 0 ? value : 1;
- setHourlyInterval(next);
- emit({ hourlyInterval: next });
- };
-
- const handleWeekdaysChange = (values: string[]) => {
- const next = values.map(Number).sort((a, b) => a - b);
- setWeekdays(next);
- emit({ weekdays: next });
- };
-
- const handleTimezoneChange = (value: string) => {
- setTz(value);
- emit({ tz: value });
- };
-
- const handleMaxExecChange = (value: number | string | null) => {
- if (typeof value === 'number' && value > 0) {
- setMaxExec(value);
- emit({ maxExec: value });
- return;
- }
- // Mid-edit clear (e.g. user is replacing 100 with 5): keep the field
- // empty locally but don't toggle Continuous or emit a null upstream.
- setMaxExec(null);
- };
-
- const handleContinuousChange = (checked: boolean) => {
- setContinuous(checked);
- if (checked) {
- emit({ maxExec: null });
- } else {
- const next = maxExec ?? 100;
- setMaxExec(next);
- emit({ maxExec: next });
- }
- };
+ const {
+ continuous,
+ handleContinuousChange,
+ handleHourChange,
+ handleHourlyIntervalChange,
+ handleMaxExecChange,
+ handleMinuteChange,
+ handleScheduleTypeChange,
+ handleTimezoneChange,
+ handleWeekdaysChange,
+ hourlyInterval,
+ maxExec,
+ scheduleType,
+ triggerTime,
+ tz,
+ weekdays,
+ } = useSchedulerForm({ maxExecutions, onChange, onUpgrade, pattern, timezone });
const showTimeRow = scheduleType !== 'hourly';
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts
index 2b37cd39754..f804fb0f266 100644
--- a/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/helpers.ts
@@ -1,3 +1,4 @@
+import { validateCronPattern } from '@lobechat/utils/cronEval';
import dayjs, { type Dayjs } from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
@@ -68,16 +69,16 @@ export const formatScheduleDescription = (pattern: string, t: TFunction<'chat'>)
});
}
case 'weekly': {
- const days = parsed.weekdays ?? [];
- const allDays = days.length === 7;
- if (allDays) {
+ const days = parsed.weekdays;
+ if (!days?.length) return pattern;
+ if (days.length === WEEKDAYS.length) {
return t('taskSchedule.summary.daily', {
time: formatHHmm(parsed.triggerHour, parsed.triggerMinute),
});
}
- const labels = [...days]
- .sort((a, b) => a - b)
- .map((d) => t(WEEKDAYS.find((w) => w.key === d)!.label as any))
+ const labels = WEEKDAYS.filter(({ key }) => days.includes(key))
+ .sort((a, b) => a.key - b.key)
+ .map(({ label }) => t(label))
.join('/');
return t('taskSchedule.summary.weekly', {
days: labels,
@@ -139,6 +140,10 @@ const computeNextScheduleFiring = (
export const nextScheduleFiring = (pattern: string, tz: string | null): Dayjs | null => {
const parsed = parseCronPattern(pattern);
const safeTz = tz || dayjs.tz.guess();
+ if (parsed.scheduleType === 'weekly' && !parsed.weekdays?.length) {
+ const result = validateCronPattern(pattern, safeTz, { count: 1 });
+ return result.valid ? dayjs(result.nextRuns[0]).tz(safeTz) : null;
+ }
try {
return computeNextScheduleFiring(
parsed.scheduleType,
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/useSchedulerForm.test.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/useSchedulerForm.test.ts
new file mode 100644
index 00000000000..278b27b8de5
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/useSchedulerForm.test.ts
@@ -0,0 +1,127 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useSchedulerForm } from './useSchedulerForm';
+
+describe('useSchedulerForm', () => {
+ it('preserves qualified cron patterns when editing timezone or max executions', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSchedulerForm({
+ maxExecutions: null,
+ onChange,
+ pattern: '30 9 * * FRI#2',
+ timezone: 'UTC',
+ }),
+ );
+
+ act(() => {
+ result.current.handleTimezoneChange('Asia/Shanghai');
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: null,
+ pattern: '30 9 * * FRI#2',
+ timezone: 'Asia/Shanghai',
+ });
+
+ act(() => {
+ result.current.handleContinuousChange(false);
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: 100,
+ pattern: '30 9 * * FRI#2',
+ timezone: 'Asia/Shanghai',
+ });
+
+ act(() => {
+ result.current.handleMaxExecChange(5);
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: 5,
+ pattern: '30 9 * * FRI#2',
+ timezone: 'Asia/Shanghai',
+ });
+ });
+
+ it('preserves qualified weekdays when changing only hour or minute', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSchedulerForm({
+ maxExecutions: null,
+ onChange,
+ pattern: '30 9 * * FRI#2',
+ timezone: 'UTC',
+ }),
+ );
+
+ act(() => {
+ result.current.handleHourChange(10);
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: null,
+ pattern: '30 10 * * FRI#2',
+ timezone: 'UTC',
+ });
+
+ act(() => {
+ result.current.handleMinuteChange(0);
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: null,
+ pattern: '0 10 * * FRI#2',
+ timezone: 'UTC',
+ });
+
+ act(() => {
+ result.current.handleTimezoneChange('America/New_York');
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: null,
+ pattern: '0 10 * * FRI#2',
+ timezone: 'America/New_York',
+ });
+ });
+
+ it('replaces a qualified weekday only when the user picks weekdays or changes frequency', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() =>
+ useSchedulerForm({
+ maxExecutions: null,
+ onChange,
+ pattern: '30 9 * * 5L',
+ timezone: 'UTC',
+ }),
+ );
+
+ act(() => {
+ result.current.handleScheduleTypeChange('weekly');
+ });
+ expect(onChange).not.toHaveBeenCalled();
+
+ act(() => {
+ result.current.handleWeekdaysChange(['1']);
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: null,
+ pattern: '30 9 * * 1',
+ timezone: 'UTC',
+ });
+
+ act(() => {
+ result.current.handleScheduleTypeChange('daily');
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith({
+ maxExecutions: null,
+ pattern: '30 9 * * *',
+ timezone: 'UTC',
+ });
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/scheduler/useSchedulerForm.ts b/src/features/AgentTasks/AgentTaskDetail/scheduler/useSchedulerForm.ts
new file mode 100644
index 00000000000..b133fb4d16d
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/scheduler/useSchedulerForm.ts
@@ -0,0 +1,182 @@
+import dayjs, { type Dayjs } from 'dayjs';
+import { useCallback, useState } from 'react';
+
+import {
+ buildCronPattern,
+ parseCronPattern,
+ type ScheduleType,
+ updateCronPatternField,
+} from './CronConfig';
+
+const DEFAULT_PATTERN = '0 9 * * *';
+const DEFAULT_TIMEZONE = 'UTC';
+
+/** Sentinel minute option that opens the upgrade flow instead of changing the value. */
+export const CUSTOM_MINUTE_UPGRADE = -1;
+
+export interface SchedulerFormChange {
+ maxExecutions: number | null;
+ pattern: string;
+ timezone: string;
+}
+
+export interface UseSchedulerFormOptions {
+ maxExecutions?: number | null;
+ onChange: (change: SchedulerFormChange) => void;
+ onUpgrade?: () => void;
+ pattern?: string | null;
+ timezone?: string | null;
+}
+
+export const useSchedulerForm = ({
+ maxExecutions,
+ onChange,
+ onUpgrade,
+ pattern,
+ timezone,
+}: UseSchedulerFormOptions) => {
+ // Local state seeded once from props at mount; never re-synced. Keeps the
+ // form in user control even if an unrelated detail refresh runs concurrently.
+ // Parent should `key={taskId}` this component to remount cleanly across tasks.
+ const [initial] = useState(() => {
+ const initialPattern = pattern || DEFAULT_PATTERN;
+ const parsed = parseCronPattern(initialPattern);
+ return {
+ ...parsed,
+ pattern: initialPattern,
+ triggerTime: dayjs().hour(parsed.triggerHour).minute(parsed.triggerMinute),
+ };
+ });
+
+ const [currentPattern, setCurrentPattern] = useState<string>(initial.pattern);
+ const [scheduleType, setScheduleType] = useState<ScheduleType>(initial.scheduleType);
+ const [triggerTime, setTriggerTime] = useState<Dayjs>(initial.triggerTime);
+ const [hourlyInterval, setHourlyInterval] = useState<number>(initial.hourlyInterval ?? 1);
+ const [weekdays, setWeekdays] = useState<number[]>(
+ initial.weekdays ?? (initial.scheduleType === 'weekly' ? [1, 2, 3, 4, 5] : []),
+ );
+ const [tz, setTz] = useState<string>(timezone || DEFAULT_TIMEZONE);
+ const [maxExec, setMaxExec] = useState<number | null>(maxExecutions ?? null);
+ const [continuous, setContinuous] = useState<boolean>(
+ maxExecutions === null || maxExecutions === undefined,
+ );
+
+ const emit = useCallback(
+ (
+ overrides: Partial<{
+ maxExec: number | null;
+ pattern: string;
+ tz: string;
+ }>,
+ ) => {
+ // When the user is mid-editing maxExec (cleared the input but hasn't
+ // typed yet), local maxExec is null but `continuous` is still false.
+ // Falling back to the persisted prop here avoids emitting null for an
+ // unrelated field change β€” which would otherwise flip Continuous on.
+ const fallbackMaxExec = continuous ? null : (maxExec ?? maxExecutions ?? null);
+ onChange({
+ maxExecutions: overrides.maxExec === undefined ? fallbackMaxExec : overrides.maxExec,
+ pattern: overrides.pattern ?? currentPattern,
+ timezone: overrides.tz ?? tz,
+ });
+ },
+ [continuous, currentPattern, maxExec, maxExecutions, onChange, tz],
+ );
+
+ const handleScheduleTypeChange = (value: ScheduleType) => {
+ if (value === scheduleType) return;
+ const nextWeekdays = value === 'weekly' ? (weekdays.length ? weekdays : [1, 2, 3, 4, 5]) : [];
+ const nextPattern = buildCronPattern(value, triggerTime, hourlyInterval, nextWeekdays);
+ setScheduleType(value);
+ setWeekdays(nextWeekdays);
+ setCurrentPattern(nextPattern);
+ emit({ pattern: nextPattern });
+ };
+
+ const handleHourChange = (hour: number) => {
+ const next = triggerTime.hour(hour);
+ const nextPattern =
+ updateCronPatternField(currentPattern, 1, String(hour)) ??
+ buildCronPattern(scheduleType, next, hourlyInterval, weekdays);
+ setTriggerTime(next);
+ setCurrentPattern(nextPattern);
+ emit({ pattern: nextPattern });
+ };
+
+ const handleMinuteChange = (minute: number) => {
+ if (minute === CUSTOM_MINUTE_UPGRADE) {
+ onUpgrade?.();
+ return;
+ }
+ const next = triggerTime.minute(minute);
+ const nextPattern =
+ updateCronPatternField(currentPattern, 0, String(minute)) ??
+ buildCronPattern(scheduleType, next, hourlyInterval, weekdays);
+ setTriggerTime(next);
+ setCurrentPattern(nextPattern);
+ emit({ pattern: nextPattern });
+ };
+
+ const handleHourlyIntervalChange = (value: number | string | null) => {
+ const next = typeof value === 'number' && value > 0 ? value : 1;
+ const nextPattern =
+ updateCronPatternField(currentPattern, 1, next === 1 ? '*' : `*/${next}`) ??
+ buildCronPattern(scheduleType, triggerTime, next, weekdays);
+ setHourlyInterval(next);
+ setCurrentPattern(nextPattern);
+ emit({ pattern: nextPattern });
+ };
+
+ const handleWeekdaysChange = (values: string[]) => {
+ const next = values.map(Number).sort((a, b) => a - b);
+ const nextPattern = buildCronPattern(scheduleType, triggerTime, hourlyInterval, next);
+ setWeekdays(next);
+ setCurrentPattern(nextPattern);
+ emit({ pattern: nextPattern });
+ };
+
+ const handleTimezoneChange = (value: string) => {
+ setTz(value);
+ emit({ tz: value });
+ };
+
+ const handleMaxExecChange = (value: number | string | null) => {
+ if (typeof value === 'number' && value > 0) {
+ setMaxExec(value);
+ emit({ maxExec: value });
+ return;
+ }
+ // Mid-edit clear (e.g. user is replacing 100 with 5): keep the field
+ // empty locally but don't toggle Continuous or emit a null upstream.
+ setMaxExec(null);
+ };
+
+ const handleContinuousChange = (checked: boolean) => {
+ setContinuous(checked);
+ if (checked) {
+ emit({ maxExec: null });
+ } else {
+ const next = maxExec ?? 100;
+ setMaxExec(next);
+ emit({ maxExec: next });
+ }
+ };
+
+ return {
+ continuous,
+ handleContinuousChange,
+ handleHourChange,
+ handleHourlyIntervalChange,
+ handleMaxExecChange,
+ handleMinuteChange,
+ handleScheduleTypeChange,
+ handleTimezoneChange,
+ handleWeekdaysChange,
+ hourlyInterval,
+ maxExec,
+ scheduleType,
+ triggerTime,
+ tz,
+ weekdays,
+ };
+};