JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(cron): 修复定时任务面板一批交互与状态显示问题
cjh_jinduoxia300de826b6d2
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsxindex ebc477f134..8914ffc4c5 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx@@ -7,6 +7,7 @@ import DatePicker from './DatePicker';import SimpleSelect from './SimpleSelect';import TemplateClusterIcon from './TemplateClusterIcon';import { validateCronExpr } from './cronExprValidation';+import { cronExprToSchedule, isOnceScheduleExpired } from './scheduleConvert';import { TIMEZONE_OPTIONS } from './constants';import type { CronTaskUI, CronTemplateUI } from '../../types/cron';import type { ProjectInfo } from '../../features/workspace/projectTypes';@@ -97,9 +98,18 @@ export default function CronTaskDrawer({ mode, initial, projects, targetOptions,// 必填项缺失时,收集清单用来在"确定"按钮旁给出具体提示(而不是只让按钮变灰、不说原因)const missingFieldLabels: string[] = [];if (!form.name.trim()) missingFieldLabels.push(t('cron.drawer.fieldName'));+ if (!form.description.trim()) missingFieldLabels.push(t('cron.drawer.fieldDescription'));if (!form.cronExpr.trim() || !validateCronExpr(form.cronExpr).valid) missingFieldLabels.push(t('cron.schedule.title'));- const canSubmit = missingFieldLabels.length === 0;- const missingFieldsHint = canSubmit ? undefined : t('cron.drawer.missingFieldsHint', { fields: missingFieldLabels.join(t('cron.schedule.listSeparator')) });+ // "单次"排班选的日期时间已经过去:字段本身不是"没填",属于另一类校验失败,+ // 单独提示(而不是塞进"还需要填写"的缺失字段列表里,语义对不上)+ const parsedSchedule = form.cronExpr.trim() ? cronExprToSchedule(form.cronExpr) : null;+ const scheduleAlreadyExpired = parsedSchedule ? isOnceScheduleExpired(parsedSchedule, form.timezone) : false;+ const canSubmit = missingFieldLabels.length === 0 && !scheduleAlreadyExpired;+ const missingFieldsHint = missingFieldLabels.length > 0+ ? t('cron.drawer.missingFieldsHint', { fields: missingFieldLabels.join(t('cron.schedule.listSeparator')) })+ : scheduleAlreadyExpired+ ? t('cron.drawer.scheduleAlreadyExpiredHint')+ : undefined;const lockedTitle = proactiveLocked ? t('cron.autoManagedToggleDisabled') ?? undefined : undefined;return (@@ -173,7 +183,9 @@ export default function CronTaskDrawer({ mode, initial, projects, targetOptions,</div><div>- <label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldDescription')}</label>+ <label className="mb-1.5 block text-sm font-bold text-text-strong">+ {t('cron.drawer.fieldDescription')} <span className="text-danger">*</span>+ </label><textareavalue={form.description}onChange={(e) => setForm({ ...form, description: e.target.value })}@@ -195,7 +207,7 @@ export default function CronTaskDrawer({ mode, initial, projects, targetOptions,/></div>- <ScheduleEditor value={form.cronExpr} onChange={(cronExpr) => setForm({ ...form, cronExpr })} />+ <ScheduleEditor value={form.cronExpr} onChange={(cronExpr) => setForm({ ...form, cronExpr })} timezone={form.timezone} /><div><label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldTimezone')}</label>diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/DatePicker.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/DatePicker.tsxindex 4ced75797b..2fbfc9fef7 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/DatePicker.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/DatePicker.tsx@@ -8,6 +8,8 @@ interface DatePickerProps {onChange: (v: string) => void;placeholder?: string;className?: string;+ /** 最早可选日期 "YYYY-MM-DD"(含),早于它的日期禁用点选、手动输入也会被拒绝;不传则不限制。 */+ minDate?: string;}function buildMonthList(centerYear: number, centerMonth: number): { year: number; month: number }[] {@@ -31,7 +33,7 @@ function parseFlexibleDate(raw: string): string | null {const WEEKDAY_KEYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];-export default function DatePicker({ value, onChange, placeholder, className = 'flex-1 min-w-0' }: DatePickerProps) {+export default function DatePicker({ value, onChange, placeholder, className = 'flex-1 min-w-0', minDate }: DatePickerProps) {const { t } = useTranslation();const initial = value ? new Date(value) : new Date();const [open, setOpen] = useState(false);@@ -51,7 +53,7 @@ export default function DatePicker({ value, onChange, placeholder, className = 'function commitText(raw: string) {const parsed = parseFlexibleDate(raw);- if (parsed) {+ if (parsed && !(minDate && parsed < minDate)) {onChange(parsed);const d = new Date(parsed);setCursor({ year: d.getFullYear(), month: d.getMonth() });@@ -197,13 +199,18 @@ export default function DatePicker({ value, onChange, placeholder, className = 'selectedDate.getFullYear() === cursor.year &&selectedDate.getMonth() === cursor.month &&selectedDate.getDate() === day;+ const cellDateStr = `${cursor.year}-${String(cursor.month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;+ const disabled = Boolean(minDate && cellDateStr < minDate);return (<buttonkey={idx}type="button"+ disabled={disabled}onClick={() => pick(day)}className={`h-9 w-9 rounded-full text-sm transition-colors ${- isSelected ? 'bg-accent text-accent-foreground' : 'text-text hover:bg-bg-hover'+ disabled+ ? 'cursor-not-allowed text-text-muted/40'+ : isSelected ? 'bg-accent text-accent-foreground' : 'text-text hover:bg-bg-hover'}`}>{day}diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ScheduleEditor.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ScheduleEditor.tsxindex f2295efbe1..668d3c50ab 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ScheduleEditor.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ScheduleEditor.tsx@@ -1,15 +1,16 @@-import { useState } from 'react';+import { useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import SimpleSelect from './SimpleSelect';import TimePicker from './TimePicker';import DatePicker from './DatePicker';import { validateCronExpr } from './cronExprValidation';-import { scheduleToCronExpr, cronExprToSchedule } from './scheduleConvert';+import { scheduleToCronExpr, cronExprToSchedule, nowWallClock } from './scheduleConvert';import type { CronSchedule, CronScheduleKind } from '../../types/cron';interface ScheduleEditorProps {value: string; // cron_expr 原文,唯一提交给后端的数据onChange: (v: string) => void;+ timezone: string; // "单次"tab 用来算"今天/现在",禁掉已经过去的日期和时间点(见 2026-07-16 bugfix)}type TopMode = 'period' | 'interval' | 'once' | 'cronExpr';@@ -39,15 +40,16 @@ function topModeOf(kind: CronScheduleKind): TopMode {}function defaultForTopMode(mode: 'period' | 'interval' | 'once'): CronSchedule {- if (mode === 'interval') return { kind: 'interval', everyHours: 1 };+ if (mode === 'interval') return { kind: 'interval', intervalUnit: 'hours', everyHours: 1 };if (mode === 'once') return { kind: 'once', time: '', date: '' };return { kind: 'daily', time: '' };}-function everyHoursTextOf(schedule: CronSchedule): string {- return schedule.kind === 'interval' && schedule.everyHours !== undefined- ? String(schedule.everyHours)- : '';+// "按间隔"的数字输入:按当前单位(小时/分钟)取对应字段的文本表示,两者二选一+function intervalNumberTextOf(schedule: CronSchedule): string {+ if (schedule.kind !== 'interval') return '';+ const n = schedule.intervalUnit === 'minutes' ? schedule.everyMinutes : schedule.everyHours;+ return n !== undefined ? String(n) : '';}function WeekdayPicker({ selected, onToggle }: { selected: number[]; onToggle: (day: number) => void }) {@@ -78,7 +80,7 @@ function WeekdayPicker({ selected, onToggle }: { selected: number[]; onToggle: (// 高保真设计的执行计划编辑器有 4 个 tab:周期/按间隔/单次/Cron表达式。前 3 个是结构化编辑,// 最后一个是直接编辑 cron_expr 原文的兜底/高级模式(编辑任务时若原表达式无法结构化识别,// 或用户手动切到这个 tab,都以它为准,见 scheduleConvert.ts 的反向解析策略)。-export default function ScheduleEditor({ value, onChange }: ScheduleEditorProps) {+export default function ScheduleEditor({ value, onChange, timezone }: ScheduleEditorProps) {const { t } = useTranslation();const initialParsed = cronExprToSchedule(value);const initialSchedule = initialParsed ?? { kind: 'daily', time: '' };@@ -90,27 +92,60 @@ export default function ScheduleEditor({ value, onChange }: ScheduleEditorProps)const [topMode, setTopMode] = useState<TopMode>(initialParsed ? topModeOf(initialParsed.kind) : value.trim() ? 'cronExpr' : 'period',);- // "按间隔"小时数输入框单独存一份文本状态:如果直接把 <input> 的 value 绑定到 schedule.everyHours- // (number 类型),每次 onChange 都会把输入值转成数字再写回 schedule,一旦用户刚打出的是"5."这种- // 还没打完小数部分的中间态,Number("5.") 会被转成 5,进而把输入框的 value 强制改回"5",把用户刚- // 敲的小数点瞬间吞掉,导致小数点根本打不进去。用独立的文本状态只做"显示",只有能解析成数字时才- // 同步进 schedule,从根上避免这种"受控输入反噬"。- const [everyHoursText, setEveryHoursText] = useState(() => everyHoursTextOf(initialSchedule));+ // "按间隔"数字输入框单独存一份文本状态,只做"显示",输入时先过滤掉非数字字符(小时步长/分钟步长+ // 在 croniter 里都只支持整数,见 cronExprValidation.ts),能解析成数字才同步进 schedule。+ const [intervalNumberText, setIntervalNumberText] = useState(() => intervalNumberTextOf(initialSchedule));++ // 切 tab 时的"上一次编辑内容"缓存:按 topMode 分桶各存一份 schedule。原实现切走一个 tab 时+ // 直接用 defaultForTopMode 把 value(唯一数据源)整个覆盖成空白默认值,原 tab 的数据没有任何+ // 备份,切回来自然拿不到(见 2026-07-16 bugfix)。这里给"周期/按间隔/单次"三个 tab 各留一份+ // 记忆,切换时优先用缓存恢复,缓存没有(该 tab 还没被访问过)才用默认值。+ const savedByModeRef = useRef<Partial<Record<'period' | 'interval' | 'once', CronSchedule>>>(+ initialParsed ? { [topModeOf(initialParsed.kind)]: initialParsed } : {},+ );const validation = value.trim() ? validateCronExpr(value) : { valid: true };- function updateSchedule(next: CronSchedule) {+ // "单次"tab 用:"今天"之前的日期整体不可选;选中日期正好是今天时,"现在"之前的时间点也不可选+ // (见 2026-07-16 bugfix:与其等提交时才提示已过期,不如直接不让选上)+ const nowStr = nowWallClock(timezone);+ const todayStr = nowStr.slice(0, 10);+ const nowTimeStr = nowStr.slice(11, 16);++ // cacheMode 默认取当前 topMode——这对绝大多数调用(在同一个 tab 内编辑字段)是对的。+ // 但 switchTopMode 里 setTopMode(mode) 是异步的,这个函数体内闭包捕获的 topMode 在同一次+ // 事件处理里仍是切换前的旧值;如果这里继续按闭包里的旧 topMode 去写缓存,会把"即将切入的新+ // schedule"错误地存进"切走的旧 tab"的缓存桶,污染旧桶,且新 tab 自己的桶始终没被正确写入——+ // 多切几次 tab 后 topMode 和 schedule.kind 就会彻底对不上,导致 tab 内容整个不渲染+ // (见 2026-07-16 bugfix)。所以 switchTopMode 必须显式把"即将切入的 mode"传进来。+ function updateSchedule(next: CronSchedule, cacheMode: TopMode = topMode) {setSchedule(next);+ if (cacheMode !== 'cronExpr') savedByModeRef.current[cacheMode] = next;onChange(scheduleToCronExpr(next));}function switchTopMode(mode: 'period' | 'interval' | 'once') {if (mode === topMode) return; // 已经在这个 tab 上,不要用当前(可能不完整)的 value 重新解析覆盖+ // 优先级:当前 value 能直接解析成目标 tab 的形状(比如用户在"Cron表达式"tab 手写后切回结构化+ // tab)> 该 tab 之前编辑过的缓存 > 默认值const parsed = cronExprToSchedule(value);- const next = parsed && topModeOf(parsed.kind) === mode ? parsed : defaultForTopMode(mode);+ const next = parsed && topModeOf(parsed.kind) === mode+ ? parsed+ : savedByModeRef.current[mode] ?? defaultForTopMode(mode);setTopMode(mode);- if (mode === 'interval') setEveryHoursText(everyHoursTextOf(next));- updateSchedule(next);+ if (mode === 'interval') setIntervalNumberText(intervalNumberTextOf(next));+ updateSchedule(next, mode);+ }++ // "按间隔"的小时/分钟单位切换:数字重置为空,避免"同一串数字换个单位该怎么解读"的歧义+ function setIntervalUnit(unit: 'hours' | 'minutes') {+ if (schedule.kind !== 'interval' || (schedule.intervalUnit ?? 'hours') === unit) return;+ setIntervalNumberText('');+ updateSchedule(+ unit === 'minutes'+ ? { kind: 'interval', intervalUnit: 'minutes', everyMinutes: undefined, weekdays: schedule.weekdays }+ : { kind: 'interval', intervalUnit: 'hours', everyHours: undefined, weekdays: schedule.weekdays },+ );}function setPeriodKind(kind: Extract<CronScheduleKind, 'daily' | 'weekly' | 'monthly' | 'yearly'>) {@@ -309,23 +344,42 @@ export default function ScheduleEditor({ value, onChange }: ScheduleEditorProps)<div className="flex flex-nowrap items-center gap-2"><span className="shrink-0 text-sm text-text-muted">{t('cron.schedule.every')}</span><input- type="number"- step="any"- value={everyHoursText}+ type="text"+ inputMode="numeric"+ value={intervalNumberText}onChange={(e) => {- const raw = e.target.value;- setEveryHoursText(raw);- if (raw.trim() === '') {- updateSchedule({ ...schedule, everyHours: undefined });+ // 小时/分钟步长在 croniter 里都只支持正整数,从输入源头过滤掉非数字字符+ // (而不是允许打小数、事后校验失败再把确定按钮悄悄置灰,见 2026-07-16 bugfix)+ const raw = e.target.value.replace(/\D/g, '');+ setIntervalNumberText(raw);+ const isMinutes = schedule.intervalUnit === 'minutes';+ if (raw === '') {+ updateSchedule(isMinutes ? { ...schedule, everyMinutes: undefined } : { ...schedule, everyHours: undefined });return;}const n = Number(raw);- if (!Number.isNaN(n)) updateSchedule({ ...schedule, everyHours: n });+ updateSchedule(isMinutes ? { ...schedule, everyMinutes: n } : { ...schedule, everyHours: n });}}- placeholder={t('cron.schedule.everyHoursPlaceholder') ?? undefined}+ placeholder={t(schedule.intervalUnit === 'minutes' ? 'cron.schedule.everyMinutesPlaceholder' : 'cron.schedule.everyHoursPlaceholder') ?? undefined}className="w-16 shrink-0 rounded-md border border-border bg-card px-2 py-1.5 text-sm text-text outline-none focus:border-accent"/>- <span className="shrink-0 text-sm text-text-muted">{t('cron.schedule.hoursUnit')}</span>+ <div className="inline-flex w-fit shrink-0 rounded-md bg-bg-muted p-0.5">+ {(['hours', 'minutes'] as const).map((unit) => {+ const active = (schedule.intervalUnit ?? 'hours') === unit;+ return (+ <button+ key={unit}+ type="button"+ onClick={() => setIntervalUnit(unit)}+ className={`rounded px-1.5 py-0.5 text-xs transition-colors ${+ active ? 'bg-card font-bold text-text-strong shadow-sm' : 'text-text-muted hover:text-text'+ }`}+ >+ {t(`cron.schedule.intervalUnit.${unit}`)}+ </button>+ );+ })}+ </div><WeekdayPicker selected={schedule.weekdays ?? []} onToggle={toggleWeekday} /></div>)}@@ -337,11 +391,13 @@ export default function ScheduleEditor({ value, onChange }: ScheduleEditorProps)onChange={(v) => updateSchedule({ ...schedule, time: v })}className="w-32 shrink-0"placeholder={t('cron.schedule.selectTime') ?? undefined}+ minTime={schedule.date === todayStr ? nowTimeStr : undefined}/><DatePickervalue={schedule.date ?? ''}onChange={(v) => updateSchedule({ ...schedule, date: v })}className="min-w-0 flex-1"+ minDate={todayStr}/></div>)}diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TimePicker.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TimePicker.tsxindex e820e4493e..ac6476fa46 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TimePicker.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TimePicker.tsx@@ -13,17 +13,22 @@ interface TimePickerProps {className?: string;/** 下拉弹层对齐方向:触发按钮靠近容器右边缘时用 'right',避免弹层溢出 */align?: 'left' | 'right';+ /** 最早可选时间 "HH:MM"(含),早于它的时/分选项禁用点选;不传则不限制。+ * 目前只有"单次"排班在选中日期=今天时会传(见 ScheduleEditor.tsx),其余模式代表的是+ * 循环触发的钟点,不存在"过期"概念。 */+ minTime?: string;}// 原生 <input type="time"> 会自带一个浏览器时钟图标,和自绘的 Clock 图标叠在一起变成"两个时钟",// 改成完全自绘的 时/分 两列选择器。宽度由调用方通过 className 控制。-export default function TimePicker({ value, onChange, placeholder, className = 'w-32 shrink-0', align = 'left' }: TimePickerProps) {+export default function TimePicker({ value, onChange, placeholder, className = 'w-32 shrink-0', align = 'left', minTime }: TimePickerProps) {const { t } = useTranslation();const [open, setOpen] = useState(false);const rootRef = useRef<HTMLDivElement>(null);useClickOutside(rootRef, open, () => setOpen(false));const [h, m] = value ? value.split(':') : ['', ''];+ const [minHour, minMinute] = minTime ? minTime.split(':') : [undefined, undefined];function pick(hour: string, minute: string) {onChange(`${hour}:${minute}`);@@ -43,29 +48,45 @@ export default function TimePicker({ value, onChange, placeholder, className = '<div className={`absolute top-[calc(100%+4px)] z-30 flex w-40 overflow-hidden rounded-lg border border-border bg-card shadow-lg ${align === 'right' ? 'right-0' : 'left-0'}`}><div className="flex-1 max-h-52 overflow-y-auto border-r border-border"><div className="sticky top-0 bg-card px-3 py-1.5 text-xs text-text-muted">{t('cron.timePicker.hour')}</div>- {HOURS.map((hh) => (- <button- key={hh}- type="button"- onClick={() => pick(hh, m || '00')}- className={`block w-full px-3 py-1.5 text-left text-sm ${hh === h ? 'bg-bg-hover text-text' : 'text-text hover:bg-bg-hover'}`}- >- {hh}- </button>- ))}+ {HOURS.map((hh) => {+ const disabled = minHour !== undefined && hh < minHour;+ return (+ <button+ key={hh}+ type="button"+ disabled={disabled}+ onClick={() => pick(hh, m || '00')}+ className={`block w-full px-3 py-1.5 text-left text-sm ${+ disabled+ ? 'cursor-not-allowed text-text-muted/50'+ : hh === h ? 'bg-bg-hover text-text' : 'text-text hover:bg-bg-hover'+ }`}+ >+ {hh}+ </button>+ );+ })}</div><div className="flex-1 max-h-52 overflow-y-auto"><div className="sticky top-0 bg-card px-3 py-1.5 text-xs text-text-muted">{t('cron.timePicker.minute')}</div>- {MINUTES.map((mm) => (- <button- key={mm}- type="button"- onClick={() => pick(h || '00', mm)}- className={`block w-full px-3 py-1.5 text-left text-sm ${mm === m ? 'bg-bg-hover text-text' : 'text-text hover:bg-bg-hover'}`}- >- {mm}- </button>- ))}+ {MINUTES.map((mm) => {+ const disabled = minHour !== undefined && minMinute !== undefined && h === minHour && mm < minMinute;+ return (+ <button+ key={mm}+ type="button"+ disabled={disabled}+ onClick={() => pick(h || '00', mm)}+ className={`block w-full px-3 py-1.5 text-left text-sm ${+ disabled+ ? 'cursor-not-allowed text-text-muted/50'+ : mm === m ? 'bg-bg-hover text-text' : 'text-text hover:bg-bg-hover'+ }`}+ >+ {mm}+ </button>+ );+ })}</div></div>)}diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsxindex bf892fb9bd..af0804e53f 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx@@ -335,6 +335,19 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession}}+ // "启动"(恢复已暂停任务)是低风险操作,不需要像"停止"那样二次确认弹窗+ async function handleStart(job: CronTaskUI) {+ try {+ await webRequest<{ job: CronJobDTO }>('cron.job.toggle', { id: job.id, enabled: true });+ setSuccess(t('cron.success.statusUpdated'));+ await loadJobs(projects);+ void reloadCronStore();+ } catch (toggleError) {+ const message = toggleError instanceof Error ? toggleError.message : t('cron.errors.toggleFailed');+ setError(message);+ }+ }+async function handleRunNowConfirm() {if (!confirmState || confirmBusy) return;setConfirmBusy(true);@@ -618,8 +631,13 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession<td className="px-4 py-3 text-text">{channelLabel(job.deliveryChannel)}</td><td className="relative px-4 py-3"><div className="flex items-center gap-3">- {job.expired ? (- <span className="text-sm text-text-muted/50 cursor-not-allowed select-none" title={t('cron.errors.expiredCannotRunNow') ?? undefined}>+ {/* proactive job 没有真正的"停止"态(enabled 由 config 驱动,不是用户可切的+ 开关,同 StatusBadge 的 enabled 判断),立即执行的禁用条件不看它的 enabled */}+ {job.expired || (!isProactive && !job.enabled) ? (+ <span+ className="text-sm text-text-muted/50 cursor-not-allowed select-none"+ title={t(job.expired ? 'cron.errors.expiredCannotRunNow' : 'cron.errors.disabledCannotRunNow') ?? undefined}+ >{t('cron.table.runNow')}</span>) : (@@ -630,17 +648,34 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession{t('cron.table.runNow')}</button>)}+ <button+ onClick={() => setDrawer({ mode: 'edit', initial: jobToForm(job), jobId: job.id })}+ className="text-sm text-cron-action-link hover:opacity-80"+ >+ {t('cron.table.edit')}+ </button>{isProactive ? (<span className="text-sm text-text-muted/50 cursor-not-allowed select-none" title={t('cron.autoManagedToggleDisabled') ?? undefined}>{t('cron.table.stop')}</span>- ) : (+ ) : job.expired ? (+ <span className="text-sm text-text-muted/50 cursor-not-allowed select-none" title={t('cron.errors.expiredCannotEnable') ?? undefined}>+ {t('cron.table.start')}+ </span>+ ) : job.enabled ? (<buttononClick={() => setConfirmState({ type: 'stop', job })}className="text-sm text-cron-action-link hover:opacity-80">{t('cron.table.stop')}</button>+ ) : (+ <button+ onClick={() => void handleStart(job)}+ className="text-sm text-cron-action-link hover:opacity-80"+ >+ {t('cron.table.start')}+ </button>)}<div className="relative" ref={rowMenuJobId === job.id ? rowMenuRef : undefined}><button@@ -651,15 +686,6 @@ export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession</button>{rowMenuJobId === job.id && (<div className="absolute left-0 top-[calc(100%+4px)] z-20 w-28 rounded-lg border border-border bg-card py-1.5 shadow-lg">- <button- onClick={() => {- setRowMenuJobId(null);- setDrawer({ mode: 'edit', initial: jobToForm(job), jobId: job.id });- }}- className="block w-full px-3 py-2 text-left text-sm text-cron-action-link hover:bg-bg-hover"- >- {t('cron.table.edit')}- </button><buttononClick={() => {setRowMenuJobId(null);diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/scheduleConvert.ts b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/scheduleConvert.tsindex d164a5c326..c0ede630c3 100644--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/scheduleConvert.ts+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/scheduleConvert.ts@@ -106,10 +106,14 @@ export function scheduleToCronExpr(schedule: CronSchedule): string {return `0 ${t.m} ${t.h} ${schedule.day} ${schedule.month} ? *`;}case 'interval': {- if (!schedule.everyHours) return '';const days = schedule.weekdays && schedule.weekdays.length > 0? Array.from(new Set(schedule.weekdays)).sort((a, b) => a - b).join(','): '*';+ if (schedule.intervalUnit === 'minutes') {+ if (!schedule.everyMinutes) return '';+ return `0 */${schedule.everyMinutes} * * * ${days} *`;+ }+ if (!schedule.everyHours) return '';return `0 0 */${schedule.everyHours} * * ${days} *`;}case 'once': {@@ -129,7 +133,12 @@ export function cronExprToSchedule(expr: string): CronSchedule | null {const parts = expr.trim().split(/\s+/);if (parts.length !== 7) return null;const [second, minute, hour, day, month, week, year] = parts;- if (second !== '0') return null;+ // 秒字段只要求"是单个具体数字"(不含 */,- 等形状),具体数值不参与结构化模型——+ // 结构化 tab 本身不提供秒级精度,生成时永远写 0;但识别时不应该因为秒不是 0+ // 就整体拒绝,否则像 Agent 工具/OpenClaw "at" 调度产生的、秒字段带着原始时间戳+ // 秒数的单次 cron(如 `2 4 12 16 7 ? 2026`)会被误判成"识别不了"而只能看 Cron+ // 表达式原文,实际上它的日/月/年形状清楚地是"单次"(见 2026-07-16 bugfix)。+ if (parseSingleInt(second) === null) return null;const min = parseSingleInt(minute);const hr = parseSingleInt(hour);@@ -144,17 +153,29 @@ export function cronExprToSchedule(expr: string): CronSchedule | null {return { kind: 'once', time: `${pad2(hr)}:${pad2(min)}`, date: `${y}-${pad2(mo)}-${pad2(d)}` };}- // interval:小时字段带步长+ // interval:小时字段带步长(每N小时)if (hour.startsWith('*/')) {if (minute !== '0') return null;const n = parseSingleInt(hour.slice(2));if (n === null || !isWildcard(day) || month !== '*') return null;if (isWildcard(week)) {- return { kind: 'interval', everyHours: n };+ return { kind: 'interval', intervalUnit: 'hours', everyHours: n };+ }+ const days = parseIntList(week);+ if (!days) return null;+ return { kind: 'interval', intervalUnit: 'hours', everyHours: n, weekdays: days };+ }++ // interval:分钟字段带步长、小时字段通配(每N分钟)+ if (minute.startsWith('*/') && hour === '*') {+ const n = parseSingleInt(minute.slice(2));+ if (n === null || !isWildcard(day) || month !== '*') return null;+ if (isWildcard(week)) {+ return { kind: 'interval', intervalUnit: 'minutes', everyMinutes: n };}const days = parseIntList(week);if (!days) return null;- return { kind: 'interval', everyHours: n, weekdays: days };+ return { kind: 'interval', intervalUnit: 'minutes', everyMinutes: n, weekdays: days };}if (hr === null || min === null) return null;@@ -191,6 +212,28 @@ export function cronExprToSchedule(expr: string): CronSchedule | null {return null;}+/**+ * 给定时区当前的墙钟时间,格式为 "YYYY-MM-DDTHH:mm"(零填充)。+ * 用来跟"单次"排班的 date+time 做字符串比较——两者都是零填充的 ISO 前缀,+ * 按字典序比较等价于按时间先后比较,不需要引入日期库做时区换算。+ * 用 hourCycle: 'h23' 而不是 hour12: false,避免个别引擎在午夜把小时格式化成 "24" 而不是 "00"。+ */+export function nowWallClock(timezone: string): string {+ const parts = new Intl.DateTimeFormat('en-CA', {+ timeZone: timezone,+ year: 'numeric', month: '2-digit', day: '2-digit',+ hour: '2-digit', minute: '2-digit', hourCycle: 'h23',+ }).formatToParts(new Date());+ const get = (type: string) => parts.find((p) => p.type === type)?.value ?? '';+ return `${get('year')}-${get('month')}-${get('day')}T${get('hour')}:${get('minute')}`;+}++/** "单次"排班的日期+时间是否已经过去(按 schedule 所在时区的当前墙钟时间比较)。 */+export function isOnceScheduleExpired(schedule: CronSchedule, timezone: string): boolean {+ if (schedule.kind !== 'once' || !schedule.date || !schedule.time) return false;+ return `${schedule.date}T${schedule.time}` <= nowWallClock(timezone);+}+type TFn = (key: string, options?: Record<string, unknown>) => string;// 星期真实编号(0=周日...6=周六)→ i18n key 后缀,供拼接"每周一、三、五"这样的摘要文案用@@ -237,10 +280,15 @@ export function summarizeSchedule(schedule: CronSchedule, t: TFn): string {day: schedule.day ?? '',time: schedule.time ?? '',});- case 'interval':+ case 'interval': {+ const isMinutes = schedule.intervalUnit === 'minutes';+ const n = isMinutes ? schedule.everyMinutes ?? 1 : schedule.everyHours ?? 1;+ const withWeekdaysKey = isMinutes ? 'cron.schedule.summary.intervalMinutesWithWeekdays' : 'cron.schedule.summary.intervalWithWeekdays';+ const plainKey = isMinutes ? 'cron.schedule.summary.intervalMinutes' : 'cron.schedule.summary.interval';return schedule.weekdays && schedule.weekdays.length > 0- ? t('cron.schedule.summary.intervalWithWeekdays', { n: schedule.everyHours ?? 1, days: joinWeekdays(schedule.weekdays, t) })- : t('cron.schedule.summary.interval', { n: schedule.everyHours ?? 1 });+ ? t(withWeekdaysKey, { n, days: joinWeekdays(schedule.weekdays, t) })+ : t(plainKey, { n });+ }case 'once':return t('cron.schedule.summary.once', { date: schedule.date ?? '', time: schedule.time ?? '' });default:diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 880dc12d50..ff0e3514be 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -995,7 +995,7 @@"update": "Update","delete": "Delete","runNow": "Run Now",- "previewAction": "Preview",+ "previewAction": "Upcoming schedule","enable": "Enable","disable": "Disable","loading": "Loading scheduled tasks...",@@ -1040,7 +1040,7 @@"edit": "Edit","more": "More","history": "Run history",- "triggeredSessions": "Triggered sessions",+ "triggeredSessions": "Run history","noTriggeredSessions": "No trigger records"},"empty": {@@ -1077,7 +1077,8 @@"placeholderInput": "Enter","placeholderSelect": "Select","placeholderEffectiveDate": "Select effective date",- "missingFieldsHint": "Still needed: {{fields}}"+ "missingFieldsHint": "Still needed: {{fields}}",+ "scheduleAlreadyExpiredHint": "The selected run time is already in the past, please choose another"},"schedule": {"title": "Schedule",@@ -1097,7 +1098,13 @@"selectDay": "Select day","every": "Every","everyHoursPlaceholder": "Hours",+ "everyMinutesPlaceholder": "Minutes","hoursUnit": "hours",+ "minutesUnit": "minutes",+ "intervalUnit": {+ "hours": "Hours",+ "minutes": "Minutes"+ },"dayOption": "{{day}}","monthOption": "{{month}}","lastDayOfMonth": "Last day of month",@@ -1119,6 +1126,8 @@"yearly": "Yearly on {{month}}/{{day}} at {{time}}","interval": "Every {{n}}h","intervalWithWeekdays": "Every {{n}}h ({{days}})",+ "intervalMinutes": "Every {{n}}min",+ "intervalMinutesWithWeekdays": "Every {{n}}min ({{days}})","once": "{{date}} {{time}}","lastDay": "the last day"},@@ -1228,6 +1237,7 @@"previewFailed": "Failed to preview next runs","runNowFailed": "Failed to trigger the task immediately","expiredCannotRunNow": "Task has expired and cannot be run",+ "disabledCannotRunNow": "Task is stopped and cannot be run","expiredCannotEnable": "Task has expired and cannot be enabled","loadDetailFailed": "Failed to load task details","nameRequired": "Task name is required",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 56c4448fd7..9da26452e7 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -995,7 +995,7 @@"update": "更新","delete": "删除","runNow": "立即执行",- "previewAction": "预览",+ "previewAction": "未来执行计划","enable": "启动","disable": "停用","loading": "正在加载任务列表...",@@ -1037,10 +1037,11 @@"noProject": "–","runNow": "立即执行","stop": "停止",+ "start": "启动","edit": "编辑","more": "更多","history": "运行历史",- "triggeredSessions": "触发的会话",+ "triggeredSessions": "执行记录","noTriggeredSessions": "暂无触发记录"},"empty": {@@ -1077,7 +1078,8 @@"placeholderInput": "请输入","placeholderSelect": "请选择","placeholderEffectiveDate": "请选择生效日期",- "missingFieldsHint": "还需要填写:{{fields}}"+ "missingFieldsHint": "还需要填写:{{fields}}",+ "scheduleAlreadyExpiredHint": "所选的执行时间已经过去,请重新选择"},"schedule": {"title": "执行计划",@@ -1097,7 +1099,13 @@"selectDay": "请选择日期","every": "每","everyHoursPlaceholder": "小时数",+ "everyMinutesPlaceholder": "分钟数","hoursUnit": "小时",+ "minutesUnit": "分钟",+ "intervalUnit": {+ "hours": "小时",+ "minutes": "分钟"+ },"dayOption": "{{day}}日","monthOption": "{{month}}月","lastDayOfMonth": "月末最后一天",@@ -1118,7 +1126,9 @@"monthlyWeekday": "每月{{weekOfMonth}} 周{{days}} {{time}}","yearly": "每年{{month}}月{{day}}日 {{time}}","interval": "每{{n}}小时",- "intervalWithWeekdays": "每{{n}}小时({{days}})",+ "intervalWithWeekdays": "每{{n}}小时 周{{days}}",+ "intervalMinutes": "每{{n}}分钟",+ "intervalMinutesWithWeekdays": "每{{n}}分钟 周{{days}}","once": "{{date}} {{time}}","lastDay": "月末"},@@ -1228,6 +1238,7 @@"previewFailed": "预览触发时间失败","runNowFailed": "立即执行失败","expiredCannotRunNow": "任务过期,无法执行",+ "disabledCannotRunNow": "任务已停止,无法执行","expiredCannotEnable": "任务过期,无法启动","loadDetailFailed": "获取任务详情失败","nameRequired": "任务名称不能为空",diff --git a/jiuwenswarm/channels/web/frontend/src/types/cron.ts b/jiuwenswarm/channels/web/frontend/src/types/cron.tsindex 64d5048f0f..4eda7223c6 100644--- a/jiuwenswarm/channels/web/frontend/src/types/cron.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/cron.ts@@ -69,5 +69,7 @@ export interface CronSchedule {weekOfMonth?: number | 'L'; // monthlyWeekday 用:1-4,或 'L' 表示最后一周(不支持"第五周",见 §2.3.8)month?: number; // 1-12,yearly 用date?: string; // YYYY-MM-DD,once 用- everyHours?: number; // interval 用;暂不限制取值范围/是否整数,交给 cron_expr 整体校验兜底(见 2026-07-14 progress.md)+ intervalUnit?: 'hours' | 'minutes'; // interval 用:数字的单位,默认 'hours'(兼容旧数据/旧生成结果)+ everyHours?: number; // interval 用,intervalUnit 为 'hours' 时的取值;只允许正整数(croniter 小时步长不支持小数)+ everyMinutes?: number; // interval 用,intervalUnit 为 'minutes' 时的取值;只允许正整数且需整除 60}diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex adf9e1ecdf..f23beb5089 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -410,13 +410,14 @@ class CronSchedulerService:now = self._now_fn()for job in jobs:- if not job.enabled:- continuetry:push_dt, wake_dt, run_id = self._compute_next_run(job, now_ts=now)except Exception as exc: # noqa: BLE001if self._is_croniter_no_next_date(exc):- # 已过期的 one-shot:标记 expired 并停用,避免 UI 仍显示 enabled。+ # 已过期的 one-shot:标记 expired 并停用,避免 UI 仍显示"运行中/已暂停"。+ # 这里故意不提前 continue 掉 disabled 的任务——一个单次任务如果在到期前+ # 被手动暂停,同样需要能被检测到"已经没有下一次执行时间"从而转入过期态,+ # 否则会永远卡在"已暂停"(见 2026-07-16 bugfix)。# proactive job 的 enabled 由 ConfigPanel 开关管,scheduler 不碰。try:is_proactive = getattr(job, "mode", "") == "proactive.tick"@@ -435,6 +436,8 @@ class CronSchedulerService:else:logger.warning("[Cron] compute next run failed job=%s: %s", job.id, exc)continue+ if not job.enabled:+ continue# 幂等保护:reload 清空事件队列后重新排入,但同一 run_id# 可能已执行中或已完成(wake_offset 过大时 wake_dt 在过去,# 每次 reload 都会立刻触发)。跳过已活跃 run 的 wake 事件,