Skip to content

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

feat: 定时任务改造

yuhaiquan0856e694de7e
diff --git a/jiuwenswarm/channels/web/frontend/AGENTS.md b/jiuwenswarm/channels/web/frontend/AGENTS.md
new file mode 100644
index 0000000000..39d1efc5f6
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/AGENTS.md
@@ -0,0 +1,28 @@
+# Frontend development rules
+
+## Scope
+
+These rules apply only to newly added or modified code.
+
+Do not trigger a repository-wide scan or migration solely because of these rules. When a feature changes an existing file, apply these rules to the touched code. Plan large-scale legacy cleanup as a separate, explicitly scoped task.
+
+## Formatting
+
+- Follow `.prettierrc.cjs`.
+- Do not introduce formatting conventions that conflict with Prettier.
+
+## Colors
+
+- Do not hardcode product colors in business components, pages, or component styles, including hex values, `rgb()` / `rgba()`, or Tailwind palette classes.
+- Use existing semantic theme tokens: CSS uses `var(--color-*)`; Tailwind uses semantic classes such as `bg-accent`, `text-text-link`, and `text-warn`.
+- Define concrete color values only in theme token files. New tokens must be named for their role, not their hue.
+- A2UI, Mermaid and chart palettes, logos, multicolor illustrations, image assets, SVG masks/clipping paths/transparent placeholders, and unavoidable browser or third-party constants may retain concrete colors.
+- These exceptions must not be used for product UI backgrounds, borders, buttons, text, states, or interaction feedback.
+
+## SVG
+
+- New or modified static, single-color UI SVG assets must use `fill="currentColor"` and/or `stroke="currentColor"` on visible paths.
+- Import those SVG assets through SVGR as React components, for example `import SettingsIcon from '../../assets/sidebar/config.svg?react';`.
+- New or modified inline SVG must use `currentColor`; it does not need to be extracted into a separate asset solely for this rule.
+- Do not load a themeable SVG with `currentColor` through `<img>`.
+- Logos, multicolor illustrations, image resources, and SVGs that do not need theming may retain their original colors and use `<img>`.
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index a9c99f8a0c..b2ddf404bf 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -50,6 +50,7 @@ import {
useTodoStore,
useHarnessStore,
useWorkspaceStore,
+ useCronStore,
} from './stores';
import { useChatRoute } from './multi-session/routing/useChatRoute';
import { ConversationSidebar, type NewConversationOptions } from './multi-session/sidebar/ConversationSidebar';
@@ -1461,6 +1462,9 @@ function AppContent() {
);
setHistoryLoadingMore(false);
resetNewConversationRuntime({ mode: targetMode, selectedModelName, projectDir });
+ if (options.initialInputValue) {
+ useChatStore.getState().setInputValue(NEW_CONVERSATION_ID, options.initialInputValue);
+ }
if (options.preserveProject) {
preserveSelectedProjectOnChatNewRef.current = true;
newConversationProjectRef.current = selectedProject
@@ -1765,6 +1769,14 @@ function AppContent() {
const deletingCurrent = sessionIdRef.current === deleteTarget.session_id;
setDeleteTarget(null);
await useWorkspaceStore.getState().refreshSessionWorkspace(deletedSession);
+ // 删除 session 后刷新所属定时任务的触发会话列表
+ const cronStore = useCronStore.getState();
+ for (const [jobId, sessions] of Object.entries(cronStore.cronSessions)) {
+ if (sessions.some((s) => s.session_id === deletedSession.session_id)) {
+ const job = cronStore.jobs.find((j) => j.id === jobId);
+ void cronStore.loadCronSessions(job?.project_id || 'default', jobId);
+ }
+ }
if (deletingCurrent) {
enterNewConversation();
}
@@ -1909,6 +1921,8 @@ function AppContent() {
onNew={(options) => requestSessionNavigation('new', options)}
onSelect={requestSessionNavigation}
onDelete={(session) => { setDialogError(null); setDeleteTarget(session); }}
+ onOpenCron={() => handleNavigate('cron')}
+ isCronActive={false}
/>
<div className="chat-workspace flex-1 flex min-h-0 overflow-hidden">
{showConversationNotFound && (
@@ -2005,8 +2019,27 @@ function AppContent() {
</div>
)}
{activeNav === 'cron' && (
- <div className="app-section">
- <CronPanel sessionId={sessionId} />
+ <div className="chat-layout flex-1 flex min-h-0 overflow-hidden">
+ <ConversationSidebar
+ // 停留在定时任务时,项目/会话列表不应该还显示"选中"效果——定时任务和它们是同一级的
+ // 互斥选中关系,传 null 让列表里的选中态清空(沿用"新建会话时传 null"的既有语义)
+ activeSessionId={null}
+ onNew={(options) => requestSessionNavigation('new', options)}
+ onSelect={requestSessionNavigation}
+ onDelete={(session) => { setDialogError(null); setDeleteTarget(session); }}
+ onOpenCron={() => handleNavigate('cron')}
+ isCronActive
+ />
+ <div className="chat-workspace flex-1 flex min-h-0 overflow-hidden">
+ <CronPanel
+ sessionId={sessionId}
+ onCreateViaChat={(initialInputValue) => requestSessionNavigation('new', { initialInputValue })}
+ onSelectSession={(session) => {
+ if (typeof session === 'string') { void handleRestoreSession(session); return; }
+ requestSessionNavigation(session);
+ }}
+ />
+ </div>
</div>
)}
{activeNav === 'configpanel' && (
diff --git a/jiuwenswarm/channels/web/frontend/src/assets/cron-empty.svg b/jiuwenswarm/channels/web/frontend/src/assets/cron-empty.svg
new file mode 100644
index 0000000000..3555f1d194
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/assets/cron-empty.svg
@@ -0,0 +1,26 @@
+<svg viewBox="0 0 80 80" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="80.000000" height="80.000000" fill="none" customFrame="#000000">
+ <defs>
+ <clipPath id="clipPath_0">
+ <rect width="80.000000" height="80.000000" x="0.000000" y="0.000000" fill="rgb(255,255,255)" />
+ </clipPath>
+ </defs>
+ <rect id="文件为空-empty-file" width="80.000000" height="80.000000" x="0.000000" y="0.000000" fill="rgb(255,255,255)" fill-opacity="0" />
+ <g id="文件为空-empty-file" clip-path="url(#clipPath_0)" customFrame="url(#clipPath_0)">
+ <rect id="文件为空-empty-file" width="80.000000" height="80.000000" x="0.000000" y="0.000000" />
+ <g id="缺省提示/文件为空">
+ <path id="矩形" d="M12.3 22.5L67.2 22.5C69.0225 22.5 70.5 23.4775 70.5 25.3L70.5 37L9.5 37L9.5 25.3C9.5 23.4775 10.4775 22.5 12.3 22.5Z" fill="rgb(240,240,240)" fill-rule="evenodd" />
+ <path id="矩形" d="M67.4554 22C69.2749 22 70.75 23.4924 70.75 25.3333L70.75 37L9.25 37L9.25 25.3333C9.25 23.4924 10.7251 22 12.5446 22L67.4554 22ZM67.4554 23.1111L12.5446 23.1111C11.3316 23.1111 10.3482 24.106 10.3482 25.3333L10.3482 35.8889L69.6518 35.8889L69.6518 25.3333C69.6518 24.1432 68.7271 23.1716 67.565 23.1138L67.4554 23.1111Z" fill="rgb(128,128,128)" fill-rule="nonzero" />
+ <path id="形状结合" d="M73 72.7C73 74.5225 71.5225 76 69.7 76L10.3 76C8.47746 76 7 74.5225 7 72.7L7 38.6C7 36.7775 8.47746 35.3 10.3 35.3L40.734 35.2995L50.9995 26.5005L69.7 26.5C71.5225 26.5 73 27.9775 73 29.8L73 72.7Z" fill="rgb(255,254.745,254.745)" fill-rule="evenodd" />
+ <path id="形状结合" d="M69.7 26.5C71.5225 26.5 73 27.9775 73 29.8L73 72.7C73 74.5225 71.5225 76 69.7 76L10.3 76C8.47746 76 7 74.5225 7 72.7L7 38.6C7 36.7775 8.47746 35.3 10.3 35.3L40.7332 35.3L51 26.5L69.7 26.5ZM51.4064 27.6L41.1401 36.4L10.3 36.4C9.08497 36.4 8.1 37.385 8.1 38.6L8.1 72.7C8.1 73.915 9.08497 74.9 10.3 74.9L69.7 74.9C70.915 74.9 71.9 73.915 71.9 72.7L71.9 29.8C71.9 28.585 70.915 27.6 69.7 27.6L51.4064 27.6Z" fill="rgb(128,128,128)" fill-rule="nonzero" />
+ <g id="编组-16">
+ <circle id="椭圆形备份" cx="40" cy="55.5" r="8" fill="rgb(20,118,255)" />
+ </g>
+ <path id="形状结合" d="M40 51C40.2761 51 40.5 51.2239 40.5 51.5L40.5 54.9995L44 55C44.2761 55 44.5 55.2239 44.5 55.5C44.5 55.7761 44.2761 56 44 56L40.5 56L40.5 59.5C40.5 59.7761 40.2761 60 40 60C39.7239 60 39.5 59.7761 39.5 59.5L39.5 56L36 56C35.7239 56 35.5 55.7761 35.5 55.5C35.5 55.2239 35.7239 55 36 55L39.5 55L39.5 51.5C39.5 51.2239 39.7239 51 40 51Z" fill="rgb(255,255,255)" fill-rule="evenodd" />
+ <g id="编组-17">
+ <path id="路径-21" d="M39 4C39.2761 4 39.5 4.25128 39.5 4.56124L39.5 11.4388C39.5 11.7487 39.2761 12 39 12C38.7239 12 38.5 11.7487 38.5 11.4388L38.5 4.56124C38.5 4.25128 38.7239 4 39 4Z" fill="rgb(128,128,128)" fill-rule="nonzero" />
+ <path id="路径-21" d="M22.2769 7.07445C22.5418 6.92119 22.8804 7.01214 23.0333 7.27759L26.4257 13.1674C26.5786 13.4329 26.4879 13.7723 26.2231 13.9256C25.9582 14.0788 25.6196 13.9879 25.4667 13.7224L22.0743 7.83259C21.9214 7.56714 22.0121 7.22771 22.2769 7.07445Z" fill="rgb(128,128,128)" fill-rule="nonzero" />
+ <path id="路径-21" d="M0.276934 0.0744479C0.541756 -0.0788097 0.880383 0.0121403 1.03328 0.27759L4.42573 6.16741C4.57862 6.43287 4.48789 6.77229 4.22306 6.92555C3.95824 7.07881 3.61962 6.98786 3.46672 6.72241L0.0742722 0.832585C-0.0786228 0.567135 0.0121117 0.227705 0.276934 0.0744479Z" fill="rgb(128,128,128)" fill-rule="nonzero" transform="matrix(-1,0,0,1,56,7)" />
+ </g>
+ </g>
+ </g>
+</svg>
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ConfirmDialog.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ConfirmDialog.tsx
new file mode 100644
index 0000000000..9fe3e9bd26
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ConfirmDialog.tsx
@@ -0,0 +1,45 @@
+import { useTranslation } from 'react-i18next';
+import { X } from 'lucide-react';
+
+interface ConfirmDialogProps {
+ title: string;
+ message: string;
+ onConfirm: () => void;
+ onCancel: () => void;
+ loading?: boolean;
+}
+
+export default function ConfirmDialog({ title, message, onConfirm, onCancel, loading = false }: ConfirmDialogProps) {
+ const { t } = useTranslation();
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-overlay-cron-dialog" onClick={onCancel}>
+ <div
+ className="relative w-[420px] rounded-lg bg-card p-6 shadow-xl animate-scale-in"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="mb-5 flex items-center justify-between">
+ <h3 className="text-2xl font-bold text-text-strong">{title}</h3>
+ <button onClick={onCancel} className="text-text-muted hover:text-text">
+ <X size={20} />
+ </button>
+ </div>
+ <p className="mb-6 text-sm text-text">{message}</p>
+ <div className="flex justify-center gap-3">
+ <button
+ onClick={onConfirm}
+ disabled={loading}
+ className="rounded-full bg-cron-action px-10 py-1.5 text-sm font-bold text-cron-action-foreground hover:bg-cron-action-hover disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {t('cron.actions.confirm')}
+ </button>
+ <button
+ onClick={onCancel}
+ className="rounded-full border border-border bg-card px-10 py-1.5 text-sm font-bold text-text hover:bg-bg-hover"
+ >
+ {t('common.cancel')}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx
new file mode 100644
index 0000000000..ebc477f134
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/CronTaskDrawer.tsx
@@ -0,0 +1,258 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { X, Pencil } from 'lucide-react';
+import ScheduleEditor from './ScheduleEditor';
+import ModelPicker from './ModelPicker';
+import DatePicker from './DatePicker';
+import SimpleSelect from './SimpleSelect';
+import TemplateClusterIcon from './TemplateClusterIcon';
+import { validateCronExpr } from './cronExprValidation';
+import { TIMEZONE_OPTIONS } from './constants';
+import type { CronTaskUI, CronTemplateUI } from '../../types/cron';
+import type { ProjectInfo } from '../../features/workspace/projectTypes';
+
+// "生效周期"依赖后端 effective_from/effective_until(见 backend-requests.md 需求3),目前后端还
+// 没有这个概念,选了也不下发。之前的方案是保留字段但标注"即将上线",用户后来觉得不如先整个隐藏,
+// 等后端接口交付后再打开——代码/state(`CronTaskFormValue.effectiveDate`)都保留,不用重写
+const CRON_EFFECTIVE_DATE_UI_ENABLED = false;
+
+export interface CronTaskFormValue {
+ name: string;
+ projectDir: string | null; // 仅创建/模板创建模式使用;编辑模式不展示项目字段,不参与提交
+ modelName: string | null;
+ description: string;
+ targets: string; // 推送频道,对应后端 CronJob.targets
+ cronExpr: string;
+ timezone: string;
+ effectiveDate: string | null; // 【backend-requests.md #3】仅前端展示,不下发
+ enabled: boolean;
+}
+
+function emptyForm(): CronTaskFormValue {
+ return {
+ name: '',
+ projectDir: null,
+ modelName: null,
+ description: '',
+ targets: 'web',
+ cronExpr: '',
+ timezone: 'Asia/Shanghai',
+ effectiveDate: null,
+ enabled: true,
+ };
+}
+
+export function jobToForm(job: CronTaskUI): CronTaskFormValue {
+ return {
+ name: job.name,
+ projectDir: null,
+ modelName: job.modelName,
+ description: job.description,
+ targets: job.deliveryChannel,
+ cronExpr: job.cronExpr,
+ timezone: job.timezone,
+ effectiveDate: null,
+ enabled: job.enabled,
+ };
+}
+
+export function templateToForm(tpl: CronTemplateUI, title: string, description: string): CronTaskFormValue {
+ return {
+ name: title,
+ projectDir: null,
+ modelName: null,
+ description,
+ targets: 'web',
+ cronExpr: tpl.cronExpr,
+ timezone: 'Asia/Shanghai',
+ effectiveDate: null,
+ enabled: true,
+ };
+}
+
+interface CronTaskDrawerProps {
+ mode: 'create' | 'edit' | 'template';
+ initial?: CronTaskFormValue;
+ projects: ProjectInfo[];
+ targetOptions: { value: string; label: string; disabled?: boolean }[];
+ // 主动推荐自动维护的 job(proactive-tick-auto)编辑时锁定:只能改执行计划(cron表达式)和时区,
+ // 其余字段(名称/模型/描述/推送频道/启用)由 ConfigPanel/cron_sync 管理,只读展示
+ // (沿用 upstream 提交 59cf6de7 的约束,见 index.tsx handleEditSubmit)
+ proactiveLocked?: boolean;
+ onClose: () => void;
+ onSubmit: (value: CronTaskFormValue) => void;
+ onSwitchToManual?: () => void;
+ onSwitchToTemplate?: () => void;
+}
+
+const fieldClass = 'w-full rounded-md border border-border bg-card px-3 py-1.5 text-sm text-text outline-none focus:border-accent disabled:cursor-not-allowed disabled:opacity-50';
+
+export default function CronTaskDrawer({ mode, initial, projects, targetOptions, proactiveLocked = false, onClose, onSubmit, onSwitchToManual, onSwitchToTemplate }: CronTaskDrawerProps) {
+ const { t } = useTranslation();
+ const [form, setForm] = useState<CronTaskFormValue>(initial ?? emptyForm());
+
+ const title = mode === 'edit' ? t('cron.drawer.titleEdit') : mode === 'template' ? t('cron.drawer.titleTemplate') : t('cron.drawer.titleCreate');
+ const projectOptions = projects.map((p) => ({ value: p.project_dir, label: p.name }));
+ const timezoneOptions = TIMEZONE_OPTIONS.map((tz) => ({ value: tz, label: tz }));
+ // 必填项缺失时,收集清单用来在"确定"按钮旁给出具体提示(而不是只让按钮变灰、不说原因)
+ const missingFieldLabels: string[] = [];
+ if (!form.name.trim()) missingFieldLabels.push(t('cron.drawer.fieldName'));
+ 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 lockedTitle = proactiveLocked ? t('cron.autoManagedToggleDisabled') ?? undefined : undefined;
+
+ return (
+ <div className="fixed inset-0 z-40 flex justify-end bg-overlay-cron-drawer" onClick={onClose}>
+ <div
+ className="relative flex h-full w-[560px] flex-col overflow-y-auto bg-card p-6 shadow-xl animate-slide-in-right"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="mb-6 flex items-center justify-between">
+ <h3 className="text-2xl font-bold text-text-strong">{title}</h3>
+ <div className="flex items-center gap-3">
+ {mode === 'template' && onSwitchToManual && (
+ <button
+ type="button"
+ onClick={onSwitchToManual}
+ className="flex items-center gap-1 text-sm text-text hover:opacity-70"
+ >
+ <Pencil size={14} /> {t('cron.drawer.switchToManual')}
+ </button>
+ )}
+ {mode === 'create' && onSwitchToTemplate && (
+ <button
+ type="button"
+ onClick={onSwitchToTemplate}
+ className="flex items-center gap-1 text-sm text-text hover:opacity-70"
+ >
+ <TemplateClusterIcon size={14} /> {t('cron.drawer.switchToTemplate')}
+ </button>
+ )}
+ <button onClick={onClose} className="text-text-muted hover:text-text">
+ <X size={18} />
+ </button>
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-5">
+ {proactiveLocked && (
+ <p className="rounded-md bg-bg-muted px-3 py-2 text-xs text-text-muted">{t('cron.autoManagedHint')}</p>
+ )}
+
+ <div>
+ <label className="mb-1.5 block text-sm font-bold text-text-strong">
+ {t('cron.drawer.fieldName')} <span className="text-danger">*</span>
+ </label>
+ <input
+ type="text"
+ value={form.name}
+ onChange={(e) => setForm({ ...form, name: e.target.value })}
+ placeholder={t('cron.drawer.placeholderInput') ?? undefined}
+ disabled={proactiveLocked}
+ title={lockedTitle}
+ className={fieldClass}
+ />
+ </div>
+
+ {mode !== 'edit' && (
+ <div>
+ <label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldProject')}</label>
+ <SimpleSelect
+ value={form.projectDir ?? ''}
+ onChange={(v) => setForm({ ...form, projectDir: v || null })}
+ options={projectOptions}
+ placeholder={t('cron.drawer.placeholderSelect') ?? undefined}
+ />
+ </div>
+ )}
+
+ <div>
+ <label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldModel')}</label>
+ <ModelPicker value={form.modelName} onChange={(modelName) => setForm({ ...form, modelName })} disabled={proactiveLocked} />
+ </div>
+
+ <div>
+ <label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldDescription')}</label>
+ <textarea
+ value={form.description}
+ onChange={(e) => setForm({ ...form, description: e.target.value })}
+ placeholder={t('cron.drawer.placeholderInput') ?? undefined}
+ rows={4}
+ disabled={proactiveLocked}
+ title={lockedTitle}
+ className={`${fieldClass} resize-none`}
+ />
+ </div>
+
+ <div>
+ <label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldChannel')}</label>
+ <SimpleSelect
+ value={form.targets}
+ onChange={(v) => setForm({ ...form, targets: v })}
+ options={targetOptions}
+ disabled={proactiveLocked}
+ />
+ </div>
+
+ <ScheduleEditor value={form.cronExpr} onChange={(cronExpr) => setForm({ ...form, cronExpr })} />
+
+ <div>
+ <label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldTimezone')}</label>
+ <SimpleSelect
+ value={form.timezone}
+ onChange={(v) => setForm({ ...form, timezone: v })}
+ options={timezoneOptions}
+ />
+ </div>
+
+ {CRON_EFFECTIVE_DATE_UI_ENABLED && (
+ <div>
+ <label className="mb-1.5 block text-sm font-bold text-text-strong">{t('cron.drawer.fieldEffectiveDate')}</label>
+ <DatePicker
+ value={form.effectiveDate ?? ''}
+ onChange={(v) => setForm({ ...form, effectiveDate: v || null })}
+ placeholder={t('cron.drawer.placeholderEffectiveDate') ?? undefined}
+ />
+ <p className="mt-1 text-xs text-text-muted">{t('cron.drawer.effectiveDateComingSoon')}</p>
+ </div>
+ )}
+
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ disabled={proactiveLocked}
+ title={lockedTitle}
+ onClick={() => setForm({ ...form, enabled: !form.enabled })}
+ className={`inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${form.enabled ? 'bg-accent' : 'bg-border-strong'}`}
+ >
+ <span
+ className={`inline-block h-4 w-4 transform rounded-full bg-card transition-transform ${form.enabled ? 'translate-x-6' : 'translate-x-1'}`}
+ />
+ </button>
+ <span className="text-sm font-bold text-text">
+ {form.enabled ? t('cron.status.enabled') : t('cron.status.disabled')}
+ </span>
+ </div>
+ </div>
+
+ <div className="mt-8 flex justify-center gap-3">
+ <button
+ onClick={() => onSubmit(form)}
+ disabled={!canSubmit}
+ title={missingFieldsHint}
+ className="rounded-full bg-cron-action px-10 py-1.5 text-sm font-bold text-cron-action-foreground hover:bg-cron-action-hover disabled:opacity-50"
+ >
+ {t('cron.actions.confirm')}
+ </button>
+ <button
+ onClick={onClose}
+ className="rounded-full border border-border bg-card px-10 py-1.5 text-sm font-bold text-text hover:bg-bg-hover"
+ >
+ {t('common.cancel')}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/DatePicker.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/DatePicker.tsx
new file mode 100644
index 0000000000..4ced75797b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/DatePicker.tsx
@@ -0,0 +1,254 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Calendar, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
+import { useClickOutside } from './useClickOutside';
+
+interface DatePickerProps {
+ value: string; // "YYYY-MM-DD",空字符串表示未选择
+ onChange: (v: string) => void;
+ placeholder?: string;
+ className?: string;
+}
+
+function buildMonthList(centerYear: number, centerMonth: number): { year: number; month: number }[] {
+ const list = [];
+ for (let offset = -5; offset <= 6; offset++) {
+ const d = new Date(centerYear, centerMonth + offset, 1);
+ list.push({ year: d.getFullYear(), month: d.getMonth() });
+ }
+ return list;
+}
+
+// 支持 "2026-5-25" "2026/5/25" 等宽松分隔符与不补零写法,统一归一化为 YYYY-MM-DD
+function parseFlexibleDate(raw: string): string | null {
+ const m = raw.trim().match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/);
+ if (!m) return null;
+ const [, y, mo, d] = m;
+ const date = new Date(Number(y), Number(mo) - 1, Number(d));
+ if (date.getFullYear() !== Number(y) || date.getMonth() !== Number(mo) - 1 || date.getDate() !== Number(d)) return null;
+ return `${y}-${mo.padStart(2, '0')}-${d.padStart(2, '0')}`;
+}
+
+const WEEKDAY_KEYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
+
+export default function DatePicker({ value, onChange, placeholder, className = 'flex-1 min-w-0' }: DatePickerProps) {
+ const { t } = useTranslation();
+ const initial = value ? new Date(value) : new Date();
+ const [open, setOpen] = useState(false);
+ const [panelView, setPanelView] = useState<'day' | 'year'>('day');
+ const [cursor, setCursor] = useState({ year: initial.getFullYear(), month: initial.getMonth() });
+ const [yearPageStart, setYearPageStart] = useState(initial.getFullYear() - 5);
+ const [text, setText] = useState(value);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useClickOutside(rootRef, open, () => {
+ setOpen(false);
+ setPanelView('day');
+ });
+
+ useEffect(() => {
+ setText(value);
+ }, [value]);
+
+ function commitText(raw: string) {
+ const parsed = parseFlexibleDate(raw);
+ if (parsed) {
+ onChange(parsed);
+ const d = new Date(parsed);
+ setCursor({ year: d.getFullYear(), month: d.getMonth() });
+ setText(parsed);
+ } else {
+ setText(value);
+ }
+ }
+
+ const first = new Date(cursor.year, cursor.month, 1);
+ const startWeekday = first.getDay();
+ const daysInMonth = new Date(cursor.year, cursor.month + 1, 0).getDate();
+ const cells: (number | null)[] = [...Array(startWeekday).fill(null), ...Array.from({ length: daysInMonth }, (_, i) => i + 1)];
+
+ const selectedDate = value ? new Date(value) : null;
+ const monthList = buildMonthList(cursor.year, cursor.month);
+
+ function pick(day: number) {
+ const mm = String(cursor.month + 1).padStart(2, '0');
+ const dd = String(day).padStart(2, '0');
+ onChange(`${cursor.year}-${mm}-${dd}`);
+ setOpen(false);
+ }
+
+ function openYearPicker() {
+ setYearPageStart(cursor.year - 5);
+ setPanelView('year');
+ }
+
+ function pickYear(year: number) {
+ setCursor((c) => ({ ...c, year }));
+ setPanelView('day');
+ }
+
+ return (
+ <div className={`relative ${className}`} ref={rootRef}>
+ <div
+ className="flex w-full items-center gap-1.5 rounded-md border border-border bg-card px-3 py-1.5 text-sm focus-within:border-accent"
+ onClick={() => setOpen(true)}
+ >
+ <input
+ type="text"
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ onFocus={() => setOpen(true)}
+ onBlur={() => commitText(text)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ commitText(text);
+ setOpen(false);
+ }
+ }}
+ placeholder={placeholder}
+ className="min-w-0 flex-1 bg-transparent text-text outline-none placeholder:text-text-muted"
+ />
+ <Calendar
+ size={15}
+ className="shrink-0 cursor-pointer text-text-muted"
+ onClick={(e) => {
+ e.stopPropagation();
+ setOpen((v) => !v);
+ }}
+ />
+ </div>
+ {open && panelView === 'day' && (
+ <div className="absolute left-0 top-[calc(100%+4px)] z-30 flex w-96 overflow-hidden rounded-lg border border-border bg-card shadow-lg">
+ <div className="w-16 shrink-0 max-h-72 overflow-y-auto border-r border-border py-1">
+ {monthList.map((m, idx) => (
+ <div key={`${m.year}-${m.month}`}>
+ {(idx === 0 || m.year !== monthList[idx - 1].year) && (
+ <div className="px-2 pt-2 pb-1 text-xs font-bold text-text-muted">{m.year}</div>
+ )}
+ <button
+ type="button"
+ onClick={() => setCursor({ year: m.year, month: m.month })}
+ className={`block w-full px-2 py-1.5 text-left text-sm ${
+ m.year === cursor.year && m.month === cursor.month
+ ? 'bg-bg-hover font-bold text-text'
+ : 'text-text hover:bg-bg-hover'
+ }`}
+ >
+ {t('cron.datePicker.monthItem', { month: m.month + 1 })}
+ </button>
+ </div>
+ ))}
+ </div>
+ <div className="flex-1 p-4">
+ <div className="mb-3 flex items-center justify-between">
+ <div className="flex items-center">
+ <button
+ type="button"
+ onClick={() => setCursor((c) => ({ ...c, year: c.year - 1 }))}
+ title={t('cron.datePicker.prevYear') ?? undefined}
+ className="rounded p-1 text-text-muted hover:bg-bg-hover hover:text-text"
+ >
+ <ChevronsLeft size={18} />
+ </button>
+ <button
+ type="button"
+ onClick={() => setCursor((c) => (c.month === 0 ? { year: c.year - 1, month: 11 } : { year: c.year, month: c.month - 1 }))}
+ title={t('cron.datePicker.prevMonth') ?? undefined}
+ className="rounded p-1 text-text-muted hover:bg-bg-hover hover:text-text"
+ >
+ <ChevronLeft size={18} />
+ </button>
+ </div>
+ <button
+ type="button"
+ onClick={openYearPicker}
+ className="rounded px-2 py-1 text-base font-medium text-text hover:bg-bg-hover"
+ >
+ {t('cron.datePicker.yearMonthHeader', { year: cursor.year, month: cursor.month + 1 })}
+ </button>
+ <div className="flex items-center">
+ <button
+ type="button"
+ onClick={() => setCursor((c) => (c.month === 11 ? { year: c.year + 1, month: 0 } : { year: c.year, month: c.month + 1 }))}
+ title={t('cron.datePicker.nextMonth') ?? undefined}
+ className="rounded p-1 text-text-muted hover:bg-bg-hover hover:text-text"
+ >
+ <ChevronRight size={18} />
+ </button>
+ <button
+ type="button"
+ onClick={() => setCursor((c) => ({ ...c, year: c.year + 1 }))}
+ title={t('cron.datePicker.nextYear') ?? undefined}
+ className="rounded p-1 text-text-muted hover:bg-bg-hover hover:text-text"
+ >
+ <ChevronsRight size={18} />
+ </button>
+ </div>
+ </div>
+ <div className="grid grid-cols-7 gap-1 text-center text-sm text-text-muted mb-1.5">
+ {WEEKDAY_KEYS.map((key) => (
+ <span key={key}>{t(`cron.datePicker.weekday.${key}`)}</span>
+ ))}
+ </div>
+ <div className="grid grid-cols-7 gap-1">
+ {cells.map((day, idx) => {
+ if (day === null) return <span key={idx} />;
+ const isSelected =
+ selectedDate &&
+ selectedDate.getFullYear() === cursor.year &&
+ selectedDate.getMonth() === cursor.month &&
+ selectedDate.getDate() === day;
+ return (
+ <button
+ key={idx}
+ type="button"
+ 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'
+ }`}
+ >
+ {day}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ )}
+ {open && panelView === 'year' && (
+ <div className="absolute left-0 top-[calc(100%+4px)] z-30 w-72 rounded-lg border border-border bg-card p-4 shadow-lg">
+ <div className="mb-3 flex items-center justify-between">
+ <button
+ type="button"
+ onClick={() => setYearPageStart((y) => y - 12)}
+ className="rounded p-1 text-text-muted hover:bg-bg-hover hover:text-text"
+ >
+ <ChevronLeft size={18} />
+ </button>
+ <span className="text-base font-medium text-text">{yearPageStart} - {yearPageStart + 11}</span>
+ <button
+ type="button"
+ onClick={() => setYearPageStart((y) => y + 12)}
+ className="rounded p-1 text-text-muted hover:bg-bg-hover hover:text-text"
+ >
+ <ChevronRight size={18} />
+ </button>
+ </div>
+ <div className="grid grid-cols-3 gap-2">
+ {Array.from({ length: 12 }, (_, i) => yearPageStart + i).map((y) => (
+ <button
+ key={y}
+ type="button"
+ onClick={() => pickYear(y)}
+ className={`rounded-md py-2 text-sm transition-colors ${
+ y === cursor.year ? 'bg-accent text-accent-foreground' : 'text-text hover:bg-bg-hover'
+ }`}
+ >
+ {y}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ModelPicker.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ModelPicker.tsx
new file mode 100644
index 0000000000..7cd41ee4b0
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ModelPicker.tsx
@@ -0,0 +1,78 @@
+import { useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { ChevronDown, Check } from 'lucide-react';
+import { useClickOutside } from './useClickOutside';
+import { useSessionStore } from '../../stores/sessionStore';
+import { ModelProviderIcon } from '../ModelProviderIcon';
+
+interface ModelPickerProps {
+ value: string | null;
+ onChange: (modelName: string) => void;
+ disabled?: boolean;
+}
+
+// 参考会话界面的模型下拉框(components/ChatPanel/InputArea.tsx 的模型选择器),
+// 复用同样的 ModelProviderIcon 厂商图标组件与 sessionStore.availableModels 数据源。
+export default function ModelPicker({ value, onChange, disabled = false }: ModelPickerProps) {
+ const { t } = useTranslation();
+ const availableModels = useSessionStore((s) => s.availableModels);
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useClickOutside(rootRef, open && !disabled, () => setOpen(false));
+ const selected = availableModels.find((m) => m.model_name === value) ?? null;
+
+ return (
+ <div className="relative" ref={rootRef}>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center justify-between rounded-md border border-border bg-card px-3 py-1.5 text-sm outline-none hover:border-border-strong disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:border-border"
+ >
+ {selected ? (
+ <span className="inline-flex items-center gap-2 text-text">
+ <ModelProviderIcon model={selected} />
+ {selected.alias || selected.model_name}
+ </span>
+ ) : (
+ <span className="text-text-muted">{t('cron.drawer.placeholderSelect')}</span>
+ )}
+ <ChevronDown size={14} className={`text-text-muted transition-transform ${open ? 'rotate-180' : ''}`} />
+ </button>
+ {open && !disabled && (
+ <div className="absolute left-0 top-[calc(100%+4px)] z-30 w-full rounded-lg border border-border bg-card p-1.5 shadow-lg">
+ {availableModels.length === 0 ? (
+ <div className="px-2 py-2 text-xs text-text-muted">{t('cron.modelPicker.empty')}</div>
+ ) : (
+ <>
+ <div className="px-2 py-1 text-xs text-text-muted">{t('cron.modelPicker.configured')}</div>
+ {availableModels.map((m) => {
+ const key = m.model_name;
+ const active = key === value;
+ return (
+ <button
+ key={key}
+ type="button"
+ onClick={() => {
+ onChange(m.model_name);
+ setOpen(false);
+ }}
+ className={`flex w-full items-center justify-between gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors ${
+ active ? 'bg-bg-hover text-text' : 'text-text hover:bg-bg-hover'
+ }`}
+ >
+ <span className="inline-flex items-center gap-2">
+ <ModelProviderIcon model={m} />
+ {m.alias || m.model_name}
+ </span>
+ {active && <Check size={14} className="text-accent" />}
+ </button>
+ );
+ })}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ScheduleEditor.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ScheduleEditor.tsx
new file mode 100644
index 0000000000..f2295efbe1
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/ScheduleEditor.tsx
@@ -0,0 +1,378 @@
+import { 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 type { CronSchedule, CronScheduleKind } from '../../types/cron';
+
+interface ScheduleEditorProps {
+ value: string; // cron_expr 原文,唯一提交给后端的数据
+ onChange: (v: string) => void;
+}
+
+type TopMode = 'period' | 'interval' | 'once' | 'cronExpr';
+
+const PERIOD_KINDS: Extract<CronScheduleKind, 'daily' | 'weekly' | 'monthly' | 'yearly'>[] = [
+ 'daily', 'weekly', 'monthly', 'yearly',
+];
+
+// croniter 实测的真实星期编号:0=周日...6=周六(见 plan.md §2.3.1),按钮显示顺序用"一二三四五六日"
+const WEEKDAY_ITEMS: { value: number; key: string }[] = [
+ { value: 1, key: 'mon' }, { value: 2, key: 'tue' }, { value: 3, key: 'wed' },
+ { value: 4, key: 'thu' }, { value: 5, key: 'fri' }, { value: 6, key: 'sat' },
+ { value: 0, key: 'sun' },
+];
+
+// "每月第几周"选项:不提供"第五周"(croniter 的 #5 在没有第5次出现的月份会整月跳过,不可靠,
+// 见 plan.md §2.3.8 第1点),只给第一~四周 + 最后一周(后者是独立的 L{dow} 语法,行为可靠)
+const WEEK_OF_MONTH_OPTIONS: { value: string; key: string }[] = [
+ { value: '1', key: '1' }, { value: '2', key: '2' }, { value: '3', key: '3' }, { value: '4', key: '4' },
+ { value: 'L', key: 'last' },
+];
+
+function topModeOf(kind: CronScheduleKind): TopMode {
+ if (kind === 'interval') return 'interval';
+ if (kind === 'once') return 'once';
+ return 'period';
+}
+
+function defaultForTopMode(mode: 'period' | 'interval' | 'once'): CronSchedule {
+ if (mode === 'interval') return { kind: 'interval', 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 WeekdayPicker({ selected, onToggle }: { selected: number[]; onToggle: (day: number) => void }) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex min-w-0 flex-1 gap-1.5">
+ {WEEKDAY_ITEMS.map(({ value, key }) => {
+ const active = selected.includes(value);
+ return (
+ <button
+ key={value}
+ type="button"
+ onClick={() => onToggle(value)}
+ className={`h-9 min-w-0 flex-1 rounded-md border text-sm transition-colors ${
+ active
+ ? 'border-accent bg-accent-subtle text-accent'
+ : 'border-border bg-card text-text hover:border-border-strong'
+ }`}
+ >
+ {t(`cron.schedule.weekday.${key}`)}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+// 高保真设计的执行计划编辑器有 4 个 tab:周期/按间隔/单次/Cron表达式。前 3 个是结构化编辑,
+// 最后一个是直接编辑 cron_expr 原文的兜底/高级模式(编辑任务时若原表达式无法结构化识别,
+// 或用户手动切到这个 tab,都以它为准,见 scheduleConvert.ts 的反向解析策略)。
+export default function ScheduleEditor({ value, onChange }: ScheduleEditorProps) {
+ const { t } = useTranslation();
+ const initialParsed = cronExprToSchedule(value);
+ const initialSchedule = initialParsed ?? { kind: 'daily', time: '' };
+ const [schedule, setSchedule] = useState<CronSchedule>(initialSchedule);
+ // 默认 tab:能解析出结构化 schedule 就跟它走;解析不出来时,创建任务(value 为空)默认落在
+ // "周期"而不是"Cron表达式"(更符合大多数人的心智,表达式 tab 留给"手写/编辑一条解析不了的旧
+ // 表达式"这种进阶场景);编辑一条解析不出来的已有表达式(value 非空但 parse 失败)则仍然落在
+ // "Cron表达式"tab,让用户能看到并编辑原文,不能默默换成一个和原表达式无关的默认周期排班。
+ 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));
+
+ const validation = value.trim() ? validateCronExpr(value) : { valid: true };
+
+ function updateSchedule(next: CronSchedule) {
+ setSchedule(next);
+ onChange(scheduleToCronExpr(next));
+ }
+
+ function switchTopMode(mode: 'period' | 'interval' | 'once') {
+ if (mode === topMode) return; // 已经在这个 tab 上,不要用当前(可能不完整)的 value 重新解析覆盖
+ const parsed = cronExprToSchedule(value);
+ const next = parsed && topModeOf(parsed.kind) === mode ? parsed : defaultForTopMode(mode);
+ setTopMode(mode);
+ if (mode === 'interval') setEveryHoursText(everyHoursTextOf(next));
+ updateSchedule(next);
+ }
+
+ function setPeriodKind(kind: Extract<CronScheduleKind, 'daily' | 'weekly' | 'monthly' | 'yearly'>) {
+ const time = 'time' in schedule ? schedule.time ?? '' : '';
+ if (kind === 'daily') updateSchedule({ kind: 'daily', time });
+ else if (kind === 'weekly') updateSchedule({ kind: 'weekly', time, weekdays: [] });
+ // 从其它类型切到"每月",默认停在"按日期"子模式(不管切之前是不是"按星期")
+ else if (kind === 'monthly') updateSchedule({ kind: 'monthly', time, day: 1 });
+ else updateSchedule({ kind: 'yearly', time, month: 1, day: 1 });
+ }
+
+ // "每月"内部的"按日期/按星期"二级切换;只在 schedule.kind 是 monthly/monthlyWeekday 时会被调用
+ function setMonthlySubMode(mode: 'date' | 'week') {
+ const time = schedule.time ?? '';
+ if (mode === 'date') updateSchedule({ kind: 'monthly', time, day: 1 });
+ else updateSchedule({ kind: 'monthlyWeekday', time, weekOfMonth: 1, weekdays: [] });
+ }
+
+ function toggleWeekday(day: number) {
+ if (schedule.kind !== 'weekly' && schedule.kind !== 'interval' && schedule.kind !== 'monthlyWeekday') return;
+ const current = schedule.weekdays ?? [];
+ const next = current.includes(day) ? current.filter((d) => d !== day) : [...current, day].sort((a, b) => a - b);
+ updateSchedule({ ...schedule, weekdays: next });
+ }
+
+ const dayOptions = [
+ ...Array.from({ length: 31 }, (_, i) => ({ value: String(i + 1), label: t('cron.schedule.dayOption', { day: i + 1 }) })),
+ { value: 'L', label: t('cron.schedule.lastDayOfMonth') },
+ ];
+ const monthOptions = Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1), label: t('cron.schedule.monthOption', { month: i + 1 }) }));
+ const periodKindOptions = PERIOD_KINDS.map((k) => ({ value: k, label: t(`cron.schedule.${k}`) }));
+ const weekOfMonthOptions = WEEK_OF_MONTH_OPTIONS.map((o) => ({ value: o.value, label: t(`cron.schedule.weekOfMonth.${o.key}`) }));
+
+ return (
+ <div className="relative">
+ <div className="mb-2 flex items-center gap-1.5 text-sm font-bold text-text-strong">
+ {t('cron.schedule.title')} <span className="text-danger">*</span>
+ <span
+ className="inline-flex h-4 w-4 items-center justify-center rounded-full border border-border text-[10px] font-normal text-text-muted cursor-help"
+ title={t('cron.schedule.help') ?? undefined}
+ >
+ ?
+ </span>
+ </div>
+
+ <div className="mb-3 inline-flex rounded-md bg-bg-muted p-0.5">
+ {(['period', 'interval', 'once'] as const).map((mode) => (
+ <button
+ key={mode}
+ type="button"
+ onClick={() => switchTopMode(mode)}
+ className={`rounded px-4 py-1.5 text-sm transition-colors ${
+ topMode === mode ? 'bg-card font-bold text-text-strong shadow-sm' : 'text-text-muted hover:text-text'
+ }`}
+ >
+ {t(`cron.schedule.mode${mode === 'period' ? 'Period' : mode === 'interval' ? 'Interval' : 'Once'}`)}
+ </button>
+ ))}
+ <button
+ type="button"
+ onClick={() => setTopMode('cronExpr')}
+ className={`rounded px-4 py-1.5 text-sm transition-colors ${
+ topMode === 'cronExpr' ? 'bg-card font-bold text-text-strong shadow-sm' : 'text-text-muted hover:text-text'
+ }`}
+ >
+ {t('cron.schedule.modeCronExpr')}
+ </button>
+ </div>
+
+ {topMode === 'period' && (
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-nowrap items-center gap-2">
+ <SimpleSelect
+ value={schedule.kind === 'interval' || schedule.kind === 'once' ? 'daily' : schedule.kind === 'monthlyWeekday' ? 'monthly' : schedule.kind}
+ onChange={(v) => setPeriodKind(v as Extract<CronScheduleKind, 'daily' | 'weekly' | 'monthly' | 'yearly'>)}
+ options={periodKindOptions}
+ className="w-24 shrink-0"
+ />
+
+ {/* "每月"的二级切换:按日期(已有)/ 按星期("每月第几周星期几",见 plan.md §2.3.8),
+ 跟周期细分选择器放同一行,节省纵向空间 */}
+ {(schedule.kind === 'monthly' || schedule.kind === 'monthlyWeekday') && (
+ <div className="inline-flex w-fit shrink-0 rounded-md bg-bg-muted p-0.5">
+ {(['date', 'week'] as const).map((subMode) => {
+ const active = subMode === 'date' ? schedule.kind === 'monthly' : schedule.kind === 'monthlyWeekday';
+ return (
+ <button
+ key={subMode}
+ type="button"
+ onClick={() => setMonthlySubMode(subMode)}
+ className={`rounded px-3 py-1 text-xs transition-colors ${
+ active ? 'bg-card font-bold text-text-strong shadow-sm' : 'text-text-muted hover:text-text'
+ }`}
+ >
+ {t(`cron.schedule.monthlySubMode.${subMode}`)}
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ {schedule.kind === 'weekly' && (
+ <>
+ <WeekdayPicker selected={schedule.weekdays ?? []} onToggle={toggleWeekday} />
+ <TimePicker
+ value={schedule.time ?? ''}
+ onChange={(v) => updateSchedule({ ...schedule, time: v })}
+ className="w-28 shrink-0"
+ align="right"
+ placeholder={t('cron.schedule.selectTime') ?? undefined}
+ />
+ </>
+ )}
+
+ {schedule.kind === 'yearly' && (
+ <>
+ <SimpleSelect
+ value={schedule.month ? String(schedule.month) : ''}
+ onChange={(v) => updateSchedule({ ...schedule, month: Number(v) })}
+ options={monthOptions}
+ placeholder={t('cron.schedule.selectMonth') ?? undefined}
+ className="min-w-0 flex-1"
+ />
+ <SimpleSelect
+ value={schedule.day !== undefined ? String(schedule.day) : ''}
+ onChange={(v) => updateSchedule({ ...schedule, day: Number(v) })}
+ options={dayOptions.filter((o) => o.value !== 'L')}
+ placeholder={t('cron.schedule.selectDay') ?? undefined}
+ className="min-w-0 flex-1"
+ />
+ <TimePicker
+ value={schedule.time ?? ''}
+ onChange={(v) => updateSchedule({ ...schedule, time: v })}
+ className="min-w-0 flex-1"
+ align="right"
+ placeholder={t('cron.schedule.selectTime') ?? undefined}
+ />
+ </>
+ )}
+
+ {schedule.kind === 'daily' && (
+ <TimePicker
+ value={schedule.time ?? ''}
+ onChange={(v) => updateSchedule({ ...schedule, time: v })}
+ className="min-w-0 flex-1"
+ placeholder={t('cron.schedule.selectTime') ?? undefined}
+ />
+ )}
+ </div>
+
+ {(schedule.kind === 'monthly' || schedule.kind === 'monthlyWeekday') && (
+ <div className="flex flex-nowrap items-center gap-2">
+ {schedule.kind === 'monthly' && (
+ <>
+ <SimpleSelect
+ value={schedule.day !== undefined ? String(schedule.day) : ''}
+ onChange={(v) => updateSchedule({ ...schedule, day: v === 'L' ? 'L' : Number(v) })}
+ options={dayOptions}
+ placeholder={t('cron.schedule.selectDay') ?? undefined}
+ className="min-w-0 flex-1"
+ />
+ <TimePicker
+ value={schedule.time ?? ''}
+ onChange={(v) => updateSchedule({ ...schedule, time: v })}
+ className="min-w-0 flex-1"
+ align="right"
+ placeholder={t('cron.schedule.selectTime') ?? undefined}
+ />
+ </>
+ )}
+
+ {schedule.kind === 'monthlyWeekday' && (
+ <>
+ <SimpleSelect
+ value={schedule.weekOfMonth !== undefined ? String(schedule.weekOfMonth) : ''}
+ onChange={(v) => updateSchedule({ ...schedule, weekOfMonth: v === 'L' ? 'L' : Number(v) })}
+ options={weekOfMonthOptions}
+ className="w-24 shrink-0"
+ />
+ <WeekdayPicker selected={schedule.weekdays ?? []} onToggle={toggleWeekday} />
+ <TimePicker
+ value={schedule.time ?? ''}
+ onChange={(v) => updateSchedule({ ...schedule, time: v })}
+ className="w-28 shrink-0"
+ align="right"
+ placeholder={t('cron.schedule.selectTime') ?? undefined}
+ />
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {topMode === 'interval' && schedule.kind === 'interval' && (
+ <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}
+ onChange={(e) => {
+ const raw = e.target.value;
+ setEveryHoursText(raw);
+ if (raw.trim() === '') {
+ updateSchedule({ ...schedule, everyHours: undefined });
+ return;
+ }
+ const n = Number(raw);
+ if (!Number.isNaN(n)) updateSchedule({ ...schedule, everyHours: n });
+ }}
+ placeholder={t('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>
+ <WeekdayPicker selected={schedule.weekdays ?? []} onToggle={toggleWeekday} />
+ </div>
+ )}
+
+ {topMode === 'once' && schedule.kind === 'once' && (
+ <div className="flex flex-nowrap items-center gap-2">
+ <TimePicker
+ value={schedule.time ?? ''}
+ onChange={(v) => updateSchedule({ ...schedule, time: v })}
+ className="w-32 shrink-0"
+ placeholder={t('cron.schedule.selectTime') ?? undefined}
+ />
+ <DatePicker
+ value={schedule.date ?? ''}
+ onChange={(v) => updateSchedule({ ...schedule, date: v })}
+ className="min-w-0 flex-1"
+ />
+ </div>
+ )}
+
+ {topMode === 'cronExpr' && (
+ <div>
+ <div className="relative">
+ <input
+ type="text"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={t('cron.schedule.cronExprPlaceholder') ?? undefined}
+ className={`w-full rounded-md border bg-card px-3 py-1.5 pr-8 text-sm text-text outline-none mono ${
+ !validation.valid ? 'border-danger' : 'border-border focus:border-accent'
+ }`}
+ />
+ <span
+ className="absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-text cursor-help"
+ title={t('cron.placeholders.cron') ?? undefined}
+ >
+ <svg width="16" height="16" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
+ <circle cx="20" cy="20" r="18" fill="transparent" stroke="currentColor" strokeWidth="2" />
+ <text x="20" y="22" fontSize="24" fill="currentColor" textAnchor="middle" dominantBaseline="middle">?</text>
+ </svg>
+ </span>
+ </div>
+ {!validation.valid && (
+ <p className="mt-1 text-xs text-danger">{t(validation.error || 'cron.errors.cronFormat')}</p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/SimpleSelect.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/SimpleSelect.tsx
new file mode 100644
index 0000000000..6b64092006
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/SimpleSelect.tsx
@@ -0,0 +1,70 @@
+import { useRef, useState } from 'react';
+import { ChevronDown, Check } from 'lucide-react';
+import { useClickOutside } from './useClickOutside';
+
+interface SimpleSelectOption {
+ value: string;
+ label: string;
+ disabled?: boolean;
+}
+
+interface SimpleSelectProps {
+ value: string;
+ onChange: (v: string) => void;
+ options: SimpleSelectOption[];
+ placeholder?: string;
+ className?: string;
+ disabled?: boolean;
+}
+
+// 原生 <select> 的浏览器默认下拉箭头样式不统一也不好看,参考 ModelPicker 的自绘下拉结构,
+// 做一个通用版本给 项目/时区 等纯文本选项复用。
+export default function SimpleSelect({ value, onChange, options, placeholder = '', className = 'w-full', disabled = false }: SimpleSelectProps) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useClickOutside(rootRef, open && !disabled, () => setOpen(false));
+ const selected = options.find((o) => o.value === value) ?? null;
+
+ return (
+ <div className={`relative ${className}`} ref={rootRef}>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center justify-between rounded-md border border-border bg-card px-3 py-1.5 text-sm outline-none hover:border-border-strong disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:border-border"
+ >
+ <span className={selected ? 'text-text' : 'text-text-muted'}>{selected ? selected.label : placeholder}</span>
+ <ChevronDown size={14} className={`text-text-muted transition-transform ${open ? 'rotate-180' : ''}`} />
+ </button>
+ {open && !disabled && (
+ <div className="absolute left-0 top-[calc(100%+4px)] z-30 w-full rounded-lg border border-border bg-card p-1.5 shadow-lg">
+ {options.map((opt) => {
+ const active = opt.value === value;
+ return (
+ <button
+ key={opt.value}
+ type="button"
+ disabled={opt.disabled}
+ onClick={() => {
+ if (opt.disabled) return;
+ onChange(opt.value);
+ setOpen(false);
+ }}
+ className={`flex w-full items-center justify-between gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors ${
+ opt.disabled
+ ? 'cursor-not-allowed text-text-muted'
+ : active
+ ? 'bg-bg-hover text-text'
+ : 'text-text hover:bg-bg-hover'
+ }`}
+ >
+ {opt.label}
+ {active && !opt.disabled && <Check size={14} className="text-accent" />}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/StatusBadge.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/StatusBadge.tsx
new file mode 100644
index 0000000000..b4fd570f5c
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/StatusBadge.tsx
@@ -0,0 +1,58 @@
+import { useTranslation } from 'react-i18next';
+
+interface StatusBadgeProps {
+ enabled: boolean;
+ expired: boolean;
+}
+
+// "运行中"图标:lucide 里没有贴近设计稿的对应图标(两个相对方括号),因此手绘还原。
+export function RunningIcon({ size = 15 }: { size?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M3.3 6V5C3.3 3.9 4.2 3 5.3 3H10.7C11.8 3 12.7 3.9 12.7 5V6" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" />
+ <path d="M3.3 10V11C3.3 12.1 4.2 13 5.3 13H10.7C11.8 13 12.7 12.1 12.7 11V10" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" />
+ </svg>
+ );
+}
+
+// "已暂停"/"过期"复用的空心圆环图标,同样复刻自 demo:lucide 的 Circle 组件小尺寸下描边圆环会糊成
+// 实心点,改成固定比例手绘圆环(外圆 r=6.5,内圆孔洞占比固定)。
+export function BoldRingIcon({ size = 12 }: { size?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <circle cx="8" cy="8" r="6.5" stroke="currentColor" strokeWidth="3" />
+ </svg>
+ );
+}
+
+// 这里是"任务本身的状态"(运行中/已暂停/过期),依据 enabled/expired 两个现成字段,跟后端要不要
+// 交付执行状态无关——这三态本轮已经完整实现,不是待办(2026-07-14 用户已澄清并纠正早前文档里
+// "运行失败也是任务列表三态之一"的误解)。"运行失败"属于"执行历史"维度(某一次执行的结果:
+// 运行成功/运行失败/手动停止),不会出现在这个组件里,见 CronPanel/index.tsx 的执行历史 tab
+// (目前用 CRON_HISTORY_UI_ENABLED 隐藏,等 backend-requests.md 需求1 交付后再接真实数据)。
+// 图标复刻自阶段1 demo 的 __demo__/cron-tasks/StatusBadge.tsx。
+export default function StatusBadge({ enabled, expired }: StatusBadgeProps) {
+ const { t } = useTranslation();
+ if (expired) {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-sm text-amber-600">
+ <BoldRingIcon />
+ {t('cron.status.expired')}
+ </span>
+ );
+ }
+ if (enabled) {
+ return (
+ <span className="inline-flex items-center gap-1.5 text-sm text-cron-running">
+ <RunningIcon />
+ {t('cron.status.running')}
+ </span>
+ );
+ }
+ return (
+ <span className="inline-flex items-center gap-1.5 text-sm text-text-muted">
+ <BoldRingIcon />
+ {t('cron.status.paused')}
+ </span>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TemplateClusterIcon.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TemplateClusterIcon.tsx
new file mode 100644
index 0000000000..ef6eefc856
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TemplateClusterIcon.tsx
@@ -0,0 +1,27 @@
+// "从模板创建" 图标:3 个六边形堆叠(1 上 2 下),右下角六边形中间还有一个圆形。
+// lucide 与项目 svg 导出资产里都没有等价图标,手绘还原(图标策略第③级)。
+export default function TemplateClusterIcon({ size = 14 }: { size?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <polygon
+ points="8,2 10.8,3.6 10.8,6.8 8,8.4 5.2,6.8 5.2,3.6"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinejoin="round"
+ />
+ <polygon
+ points="4.6,7.8 7.4,9.4 7.4,12.6 4.6,14.2 1.8,12.6 1.8,9.4"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinejoin="round"
+ />
+ <polygon
+ points="11.4,7.8 14.2,9.4 14.2,12.6 11.4,14.2 8.6,12.6 8.6,9.4"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinejoin="round"
+ />
+ <circle cx="11.4" cy="11" r="1.3" stroke="currentColor" strokeWidth="1.1" />
+ </svg>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TimePicker.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TimePicker.tsx
new file mode 100644
index 0000000000..e820e4493e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/TimePicker.tsx
@@ -0,0 +1,74 @@
+import { useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Clock } from 'lucide-react';
+import { useClickOutside } from './useClickOutside';
+
+const HOURS = Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0'));
+const MINUTES = Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0'));
+
+interface TimePickerProps {
+ value: string; // "HH:MM",空字符串表示未选择
+ onChange: (v: string) => void;
+ placeholder?: string;
+ className?: string;
+ /** 下拉弹层对齐方向:触发按钮靠近容器右边缘时用 'right',避免弹层溢出 */
+ align?: 'left' | 'right';
+}
+
+// 原生 <input type="time"> 会自带一个浏览器时钟图标,和自绘的 Clock 图标叠在一起变成"两个时钟",
+// 改成完全自绘的 时/分 两列选择器。宽度由调用方通过 className 控制。
+export default function TimePicker({ value, onChange, placeholder, className = 'w-32 shrink-0', align = 'left' }: 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(':') : ['', ''];
+
+ function pick(hour: string, minute: string) {
+ onChange(`${hour}:${minute}`);
+ }
+
+ return (
+ <div className={`relative ${className}`} ref={rootRef}>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full flex-nowrap items-center justify-between gap-1 rounded-md border border-border bg-card px-3 py-1.5 text-sm outline-none hover:border-border-strong"
+ >
+ <span className={`truncate ${value ? 'text-text' : 'text-text-muted'}`}>{value || placeholder}</span>
+ <Clock size={15} className="shrink-0 text-text-muted" />
+ </button>
+ {open && (
+ <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>
+ ))}
+ </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>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/constants.ts b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/constants.ts
new file mode 100644
index 0000000000..98b969340c
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/constants.ts
@@ -0,0 +1,44 @@
+import type { CronTemplateUI } from '../../types/cron';
+
+// 沿用旧 CronPanel/index.tsx 的时区选项列表
+export const TIMEZONE_OPTIONS = [
+ 'Asia/Shanghai',
+ 'Asia/Bangkok',
+ 'Asia/Tokyo',
+ 'Asia/Seoul',
+ 'Asia/Singapore',
+ 'Europe/London',
+ 'Europe/Paris',
+ 'America/New_York',
+ 'America/Los_Angeles',
+ 'America/Chicago',
+];
+
+// 任务模板:后端没有"模板"概念(见 _migration/backend-requests.md),本轮先用前端静态常量,
+// 不做后端持久化/用户自定义模板。cron_expr 只是预填的初始值,用户可在"Cron表达式"输入框里改。
+// 周字段是 croniter 实测的真实编号:0=周日...6=周六(不是 Quartz 的 1=SUN...7=SAT),见
+// cronExprValidation.ts 顶部说明;"工作周报"模板曾按 Quartz 惯例误写成 6(周六),实际描述文案
+// 写的是"每周五",2026-07-14 用户验收发现并订正为 5(周五)。
+export const CRON_TEMPLATES: CronTemplateUI[] = [
+ {
+ id: 'tpl-daily-news',
+ icon: 'trend',
+ titleKey: 'cron.template.trend.title',
+ descriptionKey: 'cron.template.trend.description',
+ cronExpr: '0 0 8 * * ? *',
+ },
+ {
+ id: 'tpl-market-watch',
+ icon: 'newspaper',
+ titleKey: 'cron.template.newspaper.title',
+ descriptionKey: 'cron.template.newspaper.description',
+ cronExpr: '0 0 12 * * ? *',
+ },
+ {
+ id: 'tpl-weekly-report',
+ icon: 'briefcase',
+ titleKey: 'cron.template.briefcase.title',
+ descriptionKey: 'cron.template.briefcase.description',
+ cronExpr: '0 0 18 ? * 5 *',
+ },
+];
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/cronExprValidation.ts b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/cronExprValidation.ts
new file mode 100644
index 0000000000..17884e7e13
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/cronExprValidation.ts
@@ -0,0 +1,103 @@
+// 7段式 cron 表达式校验(croniter 语法,second_at_beginning=True),原样搬自旧 CronPanel/index.tsx,
+// i18n.errors.cron* key 沿用;周字段范围已按 croniter 实测结果修正(见下方说明)。
+
+function isValidCronField(value: string, min: number, max: number, stepDivisor: number | null, allowQuestion: boolean = false, allowLast: boolean = false): { valid: boolean; error?: string } {
+ if (value === '*') return { valid: true };
+ if (allowQuestion && value === '?') return { valid: true };
+ if (allowLast && value === 'L') return { valid: true };
+ const parts = value.split(',');
+ for (const part of parts) {
+ if (part.includes('/')) {
+ const [range, stepStr] = part.split('/');
+ const step = parseInt(stepStr, 10);
+ if (isNaN(step) || step <= 0) return { valid: false, error: getStepRangeError(min, max) };
+ if (stepDivisor !== null && stepDivisor % step !== 0) return { valid: false, error: getStepRangeError(min, max) };
+ if (range === '*') continue;
+ const rangeValid = isValidCronRange(range, min, max);
+ if (!rangeValid) return { valid: false, error: getFieldError(min, max) };
+ } else if (part.includes('-')) {
+ if (!isValidCronRange(part, min, max)) return { valid: false, error: getFieldError(min, max) };
+ } else {
+ const num = parseInt(part, 10);
+ if (isNaN(num) || num < min || num > max) return { valid: false, error: getFieldError(min, max) };
+ }
+ }
+ return { valid: true };
+}
+
+function getFieldError(min: number, max: number): string {
+ if (min === 0 && max === 59) return 'cron.errors.cronSecondOrMinute';
+ if (min === 0 && max === 23) return 'cron.errors.cronHour';
+ if (min === 1 && max === 31) return 'cron.errors.cronDay';
+ if (min === 1 && max === 12) return 'cron.errors.cronMonth';
+ if (min === 0 && max === 6) return 'cron.errors.cronWeek';
+ return 'cron.errors.cronFormat';
+}
+
+function getStepRangeError(min: number, max: number): string {
+ if (min === 0 && max === 59) return 'cron.errors.cronSecondOrMinuteStep';
+ if (min === 0 && max === 23) return 'cron.errors.cronHourStep';
+ return getFieldError(min, max);
+}
+
+function isValidCronRange(range: string, min: number, max: number): boolean {
+ const [startStr, endStr] = range.split('-');
+ if (!startStr || !endStr) return false;
+ const start = parseInt(startStr, 10);
+ const end = parseInt(endStr, 10);
+ if (isNaN(start) || isNaN(end)) return false;
+ if (start < min || end > max || start > end) return false;
+ return true;
+}
+
+// 周字段专用校验:在普通 isValidCronField 的基础上,额外接受"每月第几周星期几"用到的
+// `{dow}#{1-5}`(第几周)和 `L{dow}`(最后一周)形状(见 scheduleConvert.ts / plan.md §2.3.8)。
+// 这两种形状是"整段"匹配(不像普通数字/区间/步长那样可以被通用逻辑复用),所以单独判断。
+function isValidWeekField(value: string): { valid: boolean; error?: string } {
+ if (value === '*' || value === '?') return { valid: true };
+ const parts = value.split(',');
+ for (const part of parts) {
+ // 含 # 或以 L 开头的段必须严格匹配"第几周"/"最后一周"形状,不能落到下面的通用数字解析——
+ // 否则像 "1#9"(n 超出 1-5 合法范围)会被 parseInt 只认前面的 "1" 而误判成合法
+ if (part.includes('#') || part.startsWith('L')) {
+ const nthMatch = part.match(/^(\d)#([1-5])$/);
+ if (nthMatch && Number(nthMatch[1]) <= 6) continue;
+ const lastMatch = part.match(/^L(\d)$/);
+ if (lastMatch && Number(lastMatch[1]) <= 6) continue;
+ return { valid: false, error: 'cron.errors.cronWeek' };
+ }
+ const plainResult = isValidCronField(part, 0, 6, null);
+ if (!plainResult.valid) return { valid: false, error: 'cron.errors.cronWeek' };
+ }
+ return { valid: true };
+}
+
+export function validateCronExpr(expr: string): { valid: boolean; error?: string } {
+ const parts = expr.trim().split(/\s+/);
+ if (parts.length !== 7) {
+ return { valid: false, error: 'cron.errors.cronFormat' };
+ }
+ const [second, minute, hour, day, month, week, year] = parts;
+ const secondResult = isValidCronField(second, 0, 59, 60);
+ if (!secondResult.valid) return { valid: false, error: secondResult.error };
+ const minuteResult = isValidCronField(minute, 0, 59, 60);
+ if (!minuteResult.valid) return { valid: false, error: minuteResult.error };
+ const hourResult = isValidCronField(hour, 0, 23, 24);
+ if (!hourResult.valid) return { valid: false, error: hourResult.error };
+ // day 字段允许 'L'(月末最后一天,croniter 支持,见 plan.md §2.3.1 第3点)
+ const dayResult = isValidCronField(day, 1, 31, null, true, true);
+ if (!dayResult.valid) return { valid: false, error: dayResult.error };
+ const monthResult = isValidCronField(month, 1, 12, null);
+ if (!monthResult.valid) return { valid: false, error: monthResult.error };
+ // 周字段实测范围是 0-6(0=周日...6=周六),不是 Quartz 的 1-7;旧文案/校验此前写反了。
+ // 用专门的 isValidWeekField(支持 ?/*、普通值、以及"每月第几周"的 #N / L 形状)
+ const weekResult = isValidWeekField(week);
+ if (!weekResult.valid) return { valid: false, error: weekResult.error };
+ if (year !== '*') {
+ const yearNum = parseInt(year, 10);
+ if (isNaN(yearNum) || yearNum < 1970 || yearNum > 2099) {
+ return { valid: false, error: 'cron.errors.cronYear' };
+ }
+ }
+ return { valid: true };
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx
index 7198f431c4..bf892fb9bd 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/index.tsx
@@ -1,299 +1,190 @@
-/**
- * CronPanel 组件
- *
- * 定时任务面板,使用 cron 表达式管理定时任务
- */
-
-import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { ChevronDown, Search, TrendingUp, Newspaper, Briefcase } from 'lucide-react';
import { webRequest, webClient } from '../../services/webClient';
import { useSessionStore } from '../../stores/sessionStore';
import { useCronStore } from '../../stores';
-
-const DEFAULT_CRON_TIMEZONE = 'Asia/Shanghai';
-const DEFAULT_CRON_TARGET = 'web';
-// 由主动推荐配置自动维护的 job id(与后端 proactive_cron_sync.PROACTIVE_JOB_ID 一致)。
-// 该 job 的整体开关由 config 的 proactive_recommendation.enabled 驱动(关则删除,不在列表里),
-// 面板上禁用 启停/删除;编辑时仅 cron 表达式与时区可改,其余字段(名称/状态/描述/偏移/频道)只读。
+import { projectRegistryClient } from '../../features/workspace/projectRegistryClient';
+import type { ProjectInfo } from '../../features/workspace/projectTypes';
+import type { Session } from '../../types';
+import type { CronJobDTO, CronTaskUI, CronTemplateUI } from '../../types/cron';
+import { CRON_TEMPLATES } from './constants';
+import { cronExprToSchedule, summarizeSchedule } from './scheduleConvert';
+import StatusBadge, { BoldRingIcon, RunningIcon } from './StatusBadge';
+import ConfirmDialog from './ConfirmDialog';
+import CronTaskDrawer, { jobToForm, templateToForm, type CronTaskFormValue } from './CronTaskDrawer';
+import { useClickOutside } from './useClickOutside';
+import emptyIllustration from '../../assets/cron-empty.svg';
+
+// 主动推荐自动维护的 job id(与后端 proactive_cron_sync.PROACTIVE_JOB_ID 一致)。
+// 该 job 的整体开关由 config 的 proactive_recommendation.enabled 驱动(关则删除,不在列表里);
+// 面板上禁用停止/删除,编辑时仅 cron 表达式与时区可改,其余字段只读(沿用旧面板约束,见
+// upstream 提交 59cf6de7)。
const PROACTIVE_AUTO_JOB_ID = 'proactive-tick-auto';
-interface CronJob {
- id: string;
- name: string;
- enabled: boolean;
- expired?: boolean;
- cron_expr: string;
- timezone: string;
- wake_offset_seconds: number;
- description?: string;
- targets: string;
- schedule?: {
- kind: string;
- expr?: string;
- tz?: string;
- at?: string;
- everyMs?: number;
- };
- payload?: {
- kind: string;
- text?: string;
- message?: string;
- };
- delivery?: {
- mode: string;
- channel?: string;
- };
- session_target?: string;
- wake_mode?: string;
- compat_mode?: string;
- model_name?: string | null;
- project_id?: string;
- session_id?: string;
- created_at: number | string | null;
- updated_at: number | string | null;
-}
-
-interface CronPreviewItem {
- wake_at: string;
- push_at: string;
-}
+// 用于展示已有任务的推送频道(含历史数据可能存在的 wecom/wechat)
+const KNOWN_TARGET_KEYS = ['web', 'tui', 'xiaoyi', 'feishu', 'dingtalk', 'whatsapp', 'wecom', 'wechat'];
+// 创建/编辑时可选的推送频道:wecom/wechat 已被 upstream 下架(见提交 e12d1952、d57567e4),
+// 不在下拉里出现,但已有数据仍按上面 KNOWN_TARGET_KEYS 正常展示
+const SELECTABLE_TARGET_KEYS = ['web', 'tui', 'xiaoyi', 'feishu', 'dingtalk', 'whatsapp'];
-interface CronJobInput {
- name: string;
- enabled: boolean;
- cron_expr: string;
- timezone: string;
- wake_offset_seconds: number;
- description: string;
- targets: string;
- model_name?: string;
-}
-
-interface UpdateCronJob extends CronJobInput {
- id: string;
- created_at?: number | string | null;
- updated_at?: number | string | null;
-}
+// 执行历史目前只有"该功能即将上线"占位(等 backend-requests.md #1 的真实数据接口交付),
+// 用户要求先不在界面上露出入口(tab + 行内"运行历史"菜单项),但保留代码,等后端接口交付后
+// 把这个开关打开即可,不用再重写 UI
+const CRON_HISTORY_UI_ENABLED = false;
interface CronPanelProps {
sessionId: string;
+ onCreateViaChat: (initialInputValue: string) => void;
+ /**
+ * 跳转到"触发的会话",复用工作面板的会话导航逻辑(App.tsx 的 requestSessionNavigation)。
+ * 传 Session 对象(如"触发的会话"列表里已有完整数据)或直接传 session_id 字符串
+ * (如立即执行返回的 session_id,还没有完整 Session 数据)。
+ */
+ onSelectSession: (session: Session | string) => void;
}
-function createEmptyJobInput(): CronJobInput {
- return {
- name: '',
- enabled: true,
- cron_expr: '',
- timezone: DEFAULT_CRON_TIMEZONE,
- wake_offset_seconds: 300,
- description: '',
- targets: DEFAULT_CRON_TARGET,
- model_name: '',
- };
-}
+type TabKey = 'list' | 'template' | 'history';
-function renderScheduleSummary(job: CronJob): string {
- if (!job.schedule) {
- return job.cron_expr || '';
- }
- if (job.schedule.kind === 'cron') {
- return job.schedule.expr || job.cron_expr || '';
- }
- if (job.schedule.kind === 'every') {
- return `every ${job.schedule.everyMs || 0} ms`;
- }
- if (job.schedule.kind === 'at') {
- return job.schedule.at || job.cron_expr || '';
- }
- return job.cron_expr || '';
-}
-
-function isValidCronField(value: string, min: number, max: number, stepDivisor: number | null, allowQuestion: boolean = false): { valid: boolean; error?: string } {
- if (value === '*') return { valid: true };
- if (allowQuestion && value === '?') return { valid: true };
- const parts = value.split(',');
- for (const part of parts) {
- if (part.includes('/')) {
- const [range, stepStr] = part.split('/');
- const step = parseInt(stepStr, 10);
- if (isNaN(step) || step <= 0) return { valid: false, error: getStepRangeError(min, max) };
- if (stepDivisor !== null && stepDivisor % step !== 0) return { valid: false, error: getStepRangeError(min, max) };
- if (range === '*') continue;
- const rangeValid = isValidCronRange(range, min, max);
- if (!rangeValid) return { valid: false, error: getFieldError(min, max) };
- } else if (part.includes('-')) {
- if (!isValidCronRange(part, min, max)) return { valid: false, error: getFieldError(min, max) };
- } else {
- const num = parseInt(part, 10);
- if (isNaN(num) || num < min || num > max) return { valid: false, error: getFieldError(min, max) };
- }
- }
- return { valid: true };
-}
-
-function getFieldError(min: number, max: number): string {
- if (min === 0 && max === 59) return 'cron.errors.cronSecondOrMinute';
- if (min === 0 && max === 23) return 'cron.errors.cronHour';
- if (min === 1 && max === 31) return 'cron.errors.cronDay';
- if (min === 1 && max === 12) return 'cron.errors.cronMonth';
- if (min === 1 && max === 7) return 'cron.errors.cronWeek';
- return 'cron.errors.cronFormat';
-}
-
-function getStepRangeError(min: number, max: number): string {
- if (min === 0 && max === 59) return 'cron.errors.cronSecondOrMinuteStep';
- if (min === 0 && max === 23) return 'cron.errors.cronHourStep';
- return getFieldError(min, max);
-}
-
-function isValidCronRange(range: string, min: number, max: number): boolean {
- const [startStr, endStr] = range.split('-');
- if (!startStr || !endStr) return false;
- const start = parseInt(startStr, 10);
- const end = parseInt(endStr, 10);
- if (isNaN(start) || isNaN(end)) return false;
- if (start < min || end > max || start > end) return false;
- return true;
-}
-
-function validateCronExpr(expr: string): { valid: boolean; error?: string } {
- const parts = expr.trim().split(/\s+/);
- if (parts.length !== 7) {
- return { valid: false, error: 'cron.errors.cronFormat' };
- }
- const [second, minute, hour, day, month, week, year] = parts;
- const secondResult = isValidCronField(second, 0, 59, 60);
- if (!secondResult.valid) {
- return { valid: false, error: secondResult.error };
- }
- const minuteResult = isValidCronField(minute, 0, 59, 60);
- if (!minuteResult.valid) {
- return { valid: false, error: minuteResult.error };
- }
- const hourResult = isValidCronField(hour, 0, 23, 24);
- if (!hourResult.valid) {
- return { valid: false, error: hourResult.error };
- }
- const dayResult = isValidCronField(day, 1, 31, null, true);
- if (!dayResult.valid) {
- return { valid: false, error: dayResult.error };
- }
- const monthResult = isValidCronField(month, 1, 12, null);
- if (!monthResult.valid) {
- return { valid: false, error: monthResult.error };
- }
- const weekResult = isValidCronField(week, 1, 7, null, true);
- if (!weekResult.valid) {
- return { valid: false, error: weekResult.error };
- }
- if (year !== '*') {
- const yearNum = parseInt(year, 10);
- if (isNaN(yearNum) || yearNum < 1970 || yearNum > 2099) {
- return { valid: false, error: 'cron.errors.cronYear' };
- }
- }
- return { valid: true };
-}
-
-function resolveCronExpr(job: CronJob): string {
- if (job.schedule?.kind === 'cron') {
- return (job.schedule.expr || job.cron_expr || '').trim();
- }
- return (job.cron_expr || '').trim();
-}
-
-function resolveTimezone(job: CronJob): string {
- if (job.schedule?.kind === 'cron') {
- return (job.schedule.tz || job.timezone || DEFAULT_CRON_TIMEZONE).trim() || DEFAULT_CRON_TIMEZONE;
- }
- return (job.timezone || DEFAULT_CRON_TIMEZONE).trim() || DEFAULT_CRON_TIMEZONE;
+function TemplateIcon({ icon }: { icon: CronTemplateUI['icon'] }) {
+ const Icon = icon === 'trend' ? TrendingUp : icon === 'newspaper' ? Newspaper : Briefcase;
+ return (
+ <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-accent-subtle text-accent">
+ <Icon size={18} />
+ </span>
+ );
}
-function resolveDescription(job: CronJob): string {
- if (job.payload?.kind === 'agentTurn') {
- return (job.payload.message || job.description || '').trim();
- }
- if (job.payload?.kind === 'systemEvent') {
- return (job.payload.text || job.description || '').trim();
- }
- return (job.description || '').trim();
+// 任务总数统计行旁边的小标签(运行中/已暂停 各多少个),样式复刻自阶段1 demo 的 StatPill
+function StatPill({ icon, label, count }: { icon: React.ReactNode; label: string; count: number }) {
+ return (
+ <span className="inline-flex items-center gap-1.5 rounded-full border border-border bg-card px-2.5 py-1 text-xs text-text">
+ {icon}
+ {label} {count}
+ </span>
+ );
}
-function resolveTargets(job: CronJob): string {
- const deliveryChannel = (job.delivery?.channel || '').trim();
- if (deliveryChannel && deliveryChannel !== 'last') {
- return deliveryChannel;
- }
- return (job.targets || DEFAULT_CRON_TARGET).trim() || DEFAULT_CRON_TARGET;
+function Th({ children, first }: { children: React.ReactNode; first?: boolean }) {
+ return (
+ <th className="py-3 font-medium">
+ <span className={`inline-block ${first ? 'px-4' : 'border-l border-border pl-4 pr-4'}`}>{children}</span>
+ </th>
+ );
}
-function normalizeJobForEdit(job: CronJob): UpdateCronJob {
+function cronJobToUI(job: CronJobDTO, projects: ProjectInfo[]): CronTaskUI {
+ const project = job.project_id ? projects.find((p) => p.project_id === job.project_id) ?? null : null;
return {
id: job.id,
- name: (job.name || '').trim(),
- enabled: Boolean(job.enabled),
- cron_expr: resolveCronExpr(job),
- timezone: resolveTimezone(job),
- wake_offset_seconds: Number.isFinite(job.wake_offset_seconds) ? job.wake_offset_seconds : 300,
- description: resolveDescription(job),
- targets: resolveTargets(job),
- model_name: (job.model_name || '').trim(),
- created_at: job.created_at,
- updated_at: job.updated_at,
- };
-}
-
-function buildLegacyJobInput(job: CronJobInput | UpdateCronJob, mode?: string): Record<string, unknown> {
- const result: Record<string, unknown> = {
- name: job.name.trim(),
+ name: job.name,
+ projectId: job.project_id,
+ projectName: project ? project.name : null,
+ description: job.description,
+ modelName: job.model_name ?? null,
+ cronExpr: job.cron_expr,
+ timezone: job.timezone,
enabled: job.enabled,
- cron_expr: job.cron_expr.trim(),
- timezone: job.timezone.trim() || DEFAULT_CRON_TIMEZONE,
- wake_offset_seconds: Math.max(0, job.wake_offset_seconds || 0),
- description: job.description.trim(),
- targets: job.targets.trim() || DEFAULT_CRON_TARGET,
+ expired: job.expired,
+ deliveryChannel: job.targets,
};
- if (mode) {
- result['mode'] = mode;
- }
- if (job.model_name && job.model_name.trim()) {
- result['model_name'] = job.model_name.trim();
- }
- return result;
}
-export default function CronPanel({ sessionId }: CronPanelProps) {
+export default function CronPanel({ sessionId, onCreateViaChat, onSelectSession }: CronPanelProps) {
const { t } = useTranslation();
const mode = useSessionStore((s) => s.runtimes[sessionId]?.mode ?? 'agent');
+ // 工作面板侧边栏的"按项目分组展示定时任务"用的是独立的 useCronStore(见
+ // multi-session/sidebar/ConversationSidebar.tsx),跟这个面板自己的 jobs state 是两份数据;
+ // 在这里创建/编辑/停止/删除任务后也要通知它刷新,否则侧边栏那边的任务文件夹会显示过期数据
const reloadCronStore = useCronStore((s) => s.reload);
- const [cronJobs, setCronJobs] = useState<CronJob[]>([]);
+
+ const [jobs, setJobs] = useState<CronTaskUI[]>([]);
+ const [projects, setProjects] = useState<ProjectInfo[]>([]);
+ const [enabledChannels, setEnabledChannels] = useState<Set<string>>(new Set());
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
- const [newJob, setNewJob] = useState<CronJobInput>(createEmptyJobInput());
- const [isCreating, setIsCreating] = useState(false);
- const [editingJobs, setEditingJobs] = useState<Record<string, UpdateCronJob>>({});
- const [previewJobId, setPreviewJobId] = useState<string | null>(null);
- const [previewRuns, setPreviewRuns] = useState<CronPreviewItem[]>([]);
- const [previewLoading, setPreviewLoading] = useState(false);
- const [enabledChannels, setEnabledChannels] = useState<Set<string>>(new Set());
- // 时区选项
- const timezoneOptions = [
- { value: 'Asia/Shanghai', label: 'Asia/Shanghai' },
- { value: 'Asia/Bangkok', label: 'Asia/Bangkok' },
- { value: 'Asia/Tokyo', label: 'Asia/Tokyo' },
- { value: 'Asia/Seoul', label: 'Asia/Seoul' },
- { value: 'Asia/Singapore', label: 'Asia/Singapore' },
- { value: 'Europe/London', label: 'Europe/London' },
- { value: 'Europe/Paris', label: 'Europe/Paris' },
- { value: 'America/New_York', label: 'America/New_York' },
- { value: 'America/Los_Angeles', label: 'America/Los_Angeles' },
- { value: 'America/Chicago', label: 'America/Chicago' },
- ];
+ const [activeTab, setActiveTab] = useState<TabKey>('list');
+ const [search, setSearch] = useState('');
+
+ const [createMenuOpen, setCreateMenuOpen] = useState(false);
+ const createMenuRef = useRef<HTMLDivElement>(null);
+ useClickOutside(createMenuRef, createMenuOpen, () => setCreateMenuOpen(false));
+
+ const [rowMenuJobId, setRowMenuJobId] = useState<string | null>(null);
+ const rowMenuRef = useRef<HTMLDivElement>(null);
+ useClickOutside(rowMenuRef, rowMenuJobId !== null, () => setRowMenuJobId(null));
+
+ // "触发的会话"弹层:跟"更多"菜单同一套开合逻辑,但单独维护 ref/开关,因为触发的会话
+ // 弹层是从"更多"菜单里的一个按钮打开的,不共用同一个 ref(点击弹层内部会话行不应该被
+ // useClickOutside 判定为"点了外面")
+ const [sessionsPopoverJobId, setSessionsPopoverJobId] = useState<string | null>(null);
+ const sessionsPopoverRef = useRef<HTMLDivElement>(null);
+ useClickOutside(sessionsPopoverRef, sessionsPopoverJobId !== null, () => setSessionsPopoverJobId(null));
+ const [triggeredSessions, setTriggeredSessions] = useState<Record<string, Session[]>>({});
+ const [triggeredSessionsLoading, setTriggeredSessionsLoading] = useState<Record<string, boolean>>({});
+
+ // "预览"(接下来几次触发时间)弹层:功能在旧版 CronPanel 里有、阶段4重写时漏做了,
+ // 后端 cron.job.preview 接口一直都在,这次顺手加回来,跟"触发的会话"同一套弹层模式
+ const [previewPopoverJobId, setPreviewPopoverJobId] = useState<string | null>(null);
+ const previewPopoverRef = useRef<HTMLDivElement>(null);
+ useClickOutside(previewPopoverRef, previewPopoverJobId !== null, () => setPreviewPopoverJobId(null));
+ const [previewRuns, setPreviewRuns] = useState<Record<string, { wake_at: string; push_at: string }[]>>({});
+ const [previewLoading, setPreviewLoading] = useState<Record<string, boolean>>({});
+
+ const [drawer, setDrawer] = useState<
+ | { mode: 'create' | 'template'; initial?: CronTaskFormValue }
+ | { mode: 'edit'; initial: CronTaskFormValue; jobId: string }
+ | null
+ >(null);
+
+ const [confirmState, setConfirmState] = useState<{ type: 'delete' | 'stop' | 'runNow'; job: CronTaskUI } | null>(null);
+ const [confirmBusy, setConfirmBusy] = useState(false);
+
+ const channelLabel = useCallback(
+ (targets: string) => (KNOWN_TARGET_KEYS.includes(targets) ? t(`cron.targets.${targets}`) : targets),
+ [t],
+ );
+
+ // "计划于"列:能识别成 周期/按间隔/单次 六种模式之一的就转成人话摘要("每天 09:30"),
+ // 识别不了的(Agent工具/TUI建的、或手写 Cron表达式 tab 的任意表达式)原样展示 7 段式原文兜底
+ const scheduleLabel = useCallback(
+ (cronExpr: string) => {
+ const parsed = cronExprToSchedule(cronExpr);
+ return parsed ? summarizeSchedule(parsed, t) : <span className="mono">{cronExpr}</span>;
+ },
+ [t],
+ );
- // 加载频道列表
- const fetchChannels = useCallback(async () => {
+ const loadJobs = useCallback(async (projectList: ProjectInfo[]) => {
+ setLoading(true);
+ setError(null);
+ try {
+ const payload = await webRequest<{ jobs: CronJobDTO[] }>('cron.job.list');
+ setJobs((payload.jobs || []).map((j) => cronJobToUI(j, projectList)));
+ } catch (loadError) {
+ const message = loadError instanceof Error ? loadError.message : t('cron.errors.loadJobs');
+ setError(message);
+ setJobs([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [t]);
+
+ const loadProjects = useCallback(async () => {
+ try {
+ const payload = await projectRegistryClient.list('all');
+ const visible = (payload.projects || []).filter((p) => !p.hidden);
+ setProjects(visible);
+ return visible;
+ } catch {
+ return [];
+ }
+ }, []);
+
+ // 沿用旧 CronPanel 的做法:按已启用的推送频道决定"推送频道"下拉里哪些选项可选
+ const loadChannels = useCallback(async () => {
try {
const payload = await webRequest<{ channels?: unknown[] }>('channel.get');
const channels = payload?.channels || [];
@@ -308,43 +199,25 @@ export default function CronPanel({ sessionId }: CronPanelProps) {
}
setEnabledChannels(enabled);
} catch {
- // ignore errors, keep empty set
+ // 忽略错误,保持空集合(下拉里全部选项禁用,用户仍可看到但选不了,不阻塞其他功能)
}
}, []);
- // 目标选项 - 动态根据启用状态
- const targetOptions = useMemo(() => [
- { value: 'web', label: t('cron.targets.web'), disabled: !enabledChannels.has('web') },
- { value: 'tui', label: t('cron.targets.tui'), disabled: !enabledChannels.has('tui') },
- { value: 'xiaoyi', label: t('cron.targets.xiaoyi'), disabled: !enabledChannels.has('xiaoyi') },
- { value: 'feishu', label: t('cron.targets.feishu'), disabled: !enabledChannels.has('feishu') },
- { value: 'dingtalk', label: t('cron.targets.dingtalk'), disabled: !enabledChannels.has('dingtalk') },
- { value: 'whatsapp', label: t('cron.targets.whatsapp'), disabled: !enabledChannels.has('whatsapp') },
- ], [t, enabledChannels]);
-
- // 加载任务列表
- const loadJobs = useCallback(async () => {
- setLoading(true);
- setError(null);
- try {
- const payload = await webRequest<{ jobs: CronJob[] }>('cron.job.list');
- setCronJobs(payload.jobs || []);
- } catch (loadError) {
- const message = loadError instanceof Error ? loadError.message : t('cron.errors.loadJobs');
- setError(message);
- setCronJobs([]);
- } finally {
- setLoading(false);
- }
- }, [t]);
+ const targetOptions = useMemo(
+ () => SELECTABLE_TARGET_KEYS.map((id) => ({ value: id, label: t(`cron.targets.${id}`), disabled: !enabledChannels.has(id) })),
+ [enabledChannels, t],
+ );
- // 初始化加载
useEffect(() => {
- void loadJobs();
- void fetchChannels();
- }, [loadJobs, fetchChannels]);
-
- // 监听 agent 工具调用结果:当 cron 相关工具执行后刷新面板
+ void (async () => {
+ const projectList = await loadProjects();
+ await loadJobs(projectList);
+ await loadChannels();
+ })();
+ }, [loadChannels, loadJobs, loadProjects]);
+
+ // 监听 Agent 工具调用结果:cron_ 前缀的工具(比如通过聊天创建/改动定时任务)执行完后
+ // 自动刷新任务列表,不用用户手动刷新页面(复用的是 upstream 同款监听逻辑,见 progress.md)
useEffect(() => {
const CRON_TOOL_PREFIX = 'cron_';
const unsubscribe = webClient.on('chat.tool_result', (event) => {
@@ -352,712 +225,631 @@ export default function CronPanel({ sessionId }: CronPanelProps) {
const inner = (payload?.tool_result as Record<string, unknown>) ?? payload;
const toolName = String(inner?.tool_name ?? inner?.name ?? '');
if (toolName.startsWith(CRON_TOOL_PREFIX)) {
- void loadJobs();
+ void loadJobs(projects);
void reloadCronStore();
}
});
return unsubscribe;
- }, [loadJobs, reloadCronStore]);
+ }, [loadJobs, projects, reloadCronStore]);
- // 成功消息自动消失
useEffect(() => {
if (!success) return;
- const timer = window.setTimeout(() => {
- setSuccess(null);
- }, 2000);
+ const timer = window.setTimeout(() => setSuccess(null), 2000);
return () => window.clearTimeout(timer);
}, [success]);
- // 错误消息自动消失
useEffect(() => {
if (!error) return;
- const timer = window.setTimeout(() => {
- setError(null);
- }, 2000);
+ const timer = window.setTimeout(() => setError(null), 2000);
return () => window.clearTimeout(timer);
}, [error]);
- // 创建任务
- const handleCreateJob = async () => {
- if (!newJob.name) {
- setError(t('cron.errors.nameRequired'));
- return;
- }
- if (!newJob.cron_expr) {
- setError(t('cron.errors.cronRequired'));
- return;
- }
- const cronValidation = validateCronExpr(newJob.cron_expr);
- if (!cronValidation.valid) {
- setError(t(cronValidation.error || 'cron.errors.cronFormat'));
- return;
- }
- if (!newJob.timezone) {
- setError(t('cron.errors.timezoneRequired'));
- return;
- }
- if (!newJob.targets) {
- setError(t('cron.errors.targetRequired'));
- return;
- }
- if (!newJob.description) {
- setError(t('cron.errors.descriptionRequired'));
- return;
- }
+ const filteredJobs = useMemo(
+ () => jobs.filter((j) => j.name.toLowerCase().includes(search.trim().toLowerCase())),
+ [jobs, search],
+ );
+ const filteredTemplates = useMemo(
+ () => CRON_TEMPLATES.filter((tpl) => t(tpl.titleKey).toLowerCase().includes(search.trim().toLowerCase())),
+ [search, t],
+ );
+
+ // 任务总数统计行旁边的分类计数:跟 StatusBadge 的判断逻辑保持一致(expired 优先于 enabled)。
+ // 运行中/已暂停/过期是任务本身状态的完整三态,不依赖后端;"运行失败"是执行历史维度的概念
+ // (某一次执行的结果),不属于这里,见 StatusBadge.tsx 顶部注释
+ const runningCount = useMemo(() => jobs.filter((j) => !j.expired && j.enabled).length, [jobs]);
+ const pausedCount = useMemo(() => jobs.filter((j) => !j.expired && !j.enabled).length, [jobs]);
+ const expiredCount = useMemo(() => jobs.filter((j) => j.expired).length, [jobs]);
+ async function handleCreateSubmit(value: CronTaskFormValue) {
try {
- await webRequest<{ job: CronJob }>('cron.job.create', {
- ...buildLegacyJobInput(newJob, mode),
+ await webRequest<{ job: CronJobDTO }>('cron.job.create', {
+ name: value.name.trim(),
+ description: value.description.trim(),
+ cron_expr: value.cronExpr.trim(),
+ timezone: value.timezone,
+ targets: value.targets.trim() || 'web',
+ enabled: value.enabled,
+ ...(value.projectDir ? { project_dir: value.projectDir } : {}),
+ ...(value.modelName ? { model_name: value.modelName } : {}),
+ mode,
session_id: sessionId,
});
setSuccess(t('cron.success.created'));
- setIsCreating(false);
- setNewJob(createEmptyJobInput());
- await loadJobs();
+ setDrawer(null);
+ setActiveTab('list');
+ await loadJobs(projects);
void reloadCronStore();
} catch (createError) {
const message = createError instanceof Error ? createError.message : t('cron.errors.createFailed');
setError(message);
}
- };
+ }
- // 切换任务状态
- const handleToggleJob = async (id: string, enabled: boolean, expired?: boolean) => {
- if (expired && !enabled) {
- setSuccess(null);
- setError(t('cron.errors.expiredCannotEnable'));
- return;
- }
+ async function handleEditSubmit(jobId: string, value: CronTaskFormValue) {
try {
- await webRequest<{ job: CronJob }>('cron.job.toggle', {
- id,
- enabled: !enabled,
+ const isProactive = jobId === PROACTIVE_AUTO_JOB_ID;
+ // proactive 自动维护 job 只允许改 cron_expr 和 timezone;enabled/mode/name/description/
+ // targets/model_name 由 ConfigPanel/cron_sync 管理,不能带,否则会跟 proactive.tick 的
+ // 调度逻辑冲突(沿用 upstream 提交 e64dcf51/59cf6de7 的约束)。
+ const patch = isProactive
+ ? { cron_expr: value.cronExpr.trim(), timezone: value.timezone }
+ : {
+ name: value.name.trim(),
+ description: value.description.trim(),
+ cron_expr: value.cronExpr.trim(),
+ timezone: value.timezone,
+ targets: value.targets.trim() || 'web',
+ enabled: value.enabled,
+ ...(value.modelName ? { model_name: value.modelName } : {}),
+ mode,
+ };
+ await webRequest<{ job: CronJobDTO }>('cron.job.update', {
+ id: jobId,
+ patch,
+ session_id: sessionId,
});
+ setSuccess(t('cron.success.updated'));
+ setDrawer(null);
+ await loadJobs(projects);
+ void reloadCronStore();
+ } catch (updateError) {
+ const message = updateError instanceof Error ? updateError.message : t('cron.errors.updateFailed');
+ setError(message);
+ }
+ }
+
+ async function handleStopConfirm() {
+ if (!confirmState || confirmBusy) return;
+ setConfirmBusy(true);
+ try {
+ await webRequest<{ job: CronJobDTO }>('cron.job.toggle', { id: confirmState.job.id, enabled: false });
setSuccess(t('cron.success.statusUpdated'));
- await loadJobs();
+ await loadJobs(projects);
void reloadCronStore();
} catch (toggleError) {
const message = toggleError instanceof Error ? toggleError.message : t('cron.errors.toggleFailed');
setError(message);
+ } finally {
+ setConfirmBusy(false);
+ setConfirmState(null);
}
- };
+ }
- // 删除任务
- const handleDeleteJob = async (id: string) => {
- if (!window.confirm(t('cron.deleteConfirm'))) return;
+ async function handleRunNowConfirm() {
+ if (!confirmState || confirmBusy) return;
+ setConfirmBusy(true);
+ try {
+ const result = await webRequest<{ accepted: boolean; run_id: string; session_id: string }>('cron.job.run_now', { id: confirmState.job.id });
+ setSuccess(t('cron.success.runNow'));
+ // 后端首次执行(job 还没有 last_session_id)时 session_id 会是空串,此时不跳转,
+ // 用户仍可通过"触发的会话"列表在会话就绪后手动打开
+ if (result.session_id) {
+ onSelectSession(result.session_id);
+ }
+ } catch (runNowError) {
+ const message = runNowError instanceof Error ? runNowError.message : t('cron.errors.runNowFailed');
+ setError(message);
+ } finally {
+ setConfirmBusy(false);
+ setConfirmState(null);
+ }
+ }
+ async function handleDeleteConfirm() {
+ if (!confirmState || confirmBusy) return;
+ setConfirmBusy(true);
try {
- await webRequest<{ deleted: boolean }>('cron.job.delete', { id });
+ await webRequest<{ deleted: boolean }>('cron.job.delete', { id: confirmState.job.id });
setSuccess(t('cron.success.deleted'));
- await loadJobs();
+ await loadJobs(projects);
void reloadCronStore();
} catch (deleteError) {
const message = deleteError instanceof Error ? deleteError.message : t('cron.errors.deleteFailed');
setError(message);
+ } finally {
+ setConfirmBusy(false);
+ setConfirmState(null);
}
- };
+ }
- const handleRunNow = async (id: string, expired?: boolean) => {
- if (expired) {
- setSuccess(null);
- setError(t('cron.errors.expiredCannotRunNow'));
+ function openTemplateDrawer(tpl: CronTemplateUI) {
+ setDrawer({ mode: 'template', initial: templateToForm(tpl, t(tpl.titleKey), t(tpl.descriptionKey)) });
+ }
+
+ // "触发的会话":查这个定时任务名下有哪些会话(含手动/自动触发的执行),点了直接跳转过去。
+ // 注意:定时任务真正执行时生成的会话 id 是 `cron_<ts>_<job.id>` 这种格式,不是正常聊天的
+ // `sess_...`,工作面板目前只认 `sess_` 前缀的会话可以跳转(App.tsx 多处判断),这部分不是
+ // 我们这次要修的范围——能跳的正常跳,跳不了的属于已知限制,等负责这块的同事处理。
+ async function toggleSessionsPopover(job: CronTaskUI) {
+ if (sessionsPopoverJobId === job.id) {
+ setSessionsPopoverJobId(null);
return;
}
-
+ setSessionsPopoverJobId(job.id);
+ setTriggeredSessionsLoading((prev) => ({ ...prev, [job.id]: true }));
try {
- await webRequest<{ run_id: string }>('cron.job.run_now', { id, session_id: sessionId });
- setSuccess(t('cron.success.runNow'));
- } catch (runError) {
- const message = runError instanceof Error ? runError.message : t('cron.errors.runNowFailed');
- setError(message);
+ const payload = await projectRegistryClient.getCronSessions(job.projectId || 'default', job.id);
+ setTriggeredSessions((prev) => ({ ...prev, [job.id]: payload.sessions || [] }));
+ } catch {
+ setTriggeredSessions((prev) => ({ ...prev, [job.id]: [] }));
+ } finally {
+ setTriggeredSessionsLoading((prev) => ({ ...prev, [job.id]: false }));
}
- };
+ }
- const handlePreviewRuns = async (id: string) => {
- setPreviewJobId(id);
- setPreviewLoading(true);
+ async function togglePreviewPopover(job: CronTaskUI) {
+ if (previewPopoverJobId === job.id) {
+ setPreviewPopoverJobId(null);
+ return;
+ }
+ setPreviewPopoverJobId(job.id);
+ setPreviewLoading((prev) => ({ ...prev, [job.id]: true }));
try {
- const payload = await webRequest<{ next: CronPreviewItem[] }>('cron.job.preview', {
- id,
+ const payload = await webRequest<{ next: { wake_at: string; push_at: string }[] }>('cron.job.preview', {
+ id: job.id,
count: 3,
session_id: sessionId,
});
- setPreviewRuns(payload.next || []);
+ setPreviewRuns((prev) => ({ ...prev, [job.id]: payload.next || [] }));
} catch (previewError) {
const message = previewError instanceof Error ? previewError.message : t('cron.errors.previewFailed');
setError(message);
- setPreviewRuns([]);
+ setPreviewRuns((prev) => ({ ...prev, [job.id]: [] }));
} finally {
- setPreviewLoading(false);
+ setPreviewLoading((prev) => ({ ...prev, [job.id]: false }));
}
- };
+ }
- const formatPreviewTime = (value: string) => {
+ function formatPreviewTime(value: string): string {
const parsed = new Date(value);
- if (Number.isNaN(parsed.getTime())) {
- return value;
- }
- return parsed.toLocaleString();
- };
-
- // 准备更新任务
- const handleUpdateJob = async (id: string) => {
- try {
- const payload = await webRequest<{ job: CronJob }>('cron.job.get', { id, session_id: sessionId });
- setEditingJobs((prev) => ({
- ...prev,
- [id]: normalizeJobForEdit(payload.job),
- }));
- } catch (viewError) {
- const message = viewError instanceof Error ? viewError.message : t('cron.errors.loadDetailFailed');
- setError(message);
- }
- };
-
- // 执行更新任务
- const handleSubmitUpdate = async (jobId: string) => {
- const editJob = editingJobs[jobId];
- if (!editJob) return;
-
- if (!editJob.name) {
- setError(t('cron.errors.nameRequired'));
- return;
- }
- if (!editJob.cron_expr) {
- setError(t('cron.errors.cronRequired'));
- return;
- }
- const cronValidationEdit = validateCronExpr(editJob.cron_expr);
- if (!cronValidationEdit.valid) {
- setError(t(cronValidationEdit.error || 'cron.errors.cronFormat'));
- return;
- }
- if (!editJob.timezone) {
- setError(t('cron.errors.timezoneRequired'));
- return;
- }
- if (!editJob.targets) {
- setError(t('cron.errors.targetRequired'));
- return;
- }
- if (!editJob.description) {
- setError(t('cron.errors.descriptionRequired'));
- return;
- }
-
- try {
- const patch = buildLegacyJobInput(editJob, mode);
- // proactive 自动维护 job 的 enabled 由 ConfigPanel 开关驱动,
- // 面板编辑提交时不带 enabled,避免与配置侧开关冲突。
- // 同样不带 mode——proactive.tick 的 mode 必须保持 proactive.tick,
- // 否则会被会话 mode(agent)覆盖,导致走普通 cron 流程而非引擎。
- // 不带 wake_offset_seconds——proactive.tick 到点就执行,偏移由后端强制 0。
- if (jobId === PROACTIVE_AUTO_JOB_ID) {
- // proactive job 只允许改 cron_expr 和 timezone,其余由 ConfigPanel/cron_sync 管
- delete patch['enabled'];
- delete patch['mode'];
- delete patch['wake_offset_seconds'];
- delete patch['name'];
- delete patch['description'];
- delete patch['targets'];
- }
- const updateData: Record<string, unknown> = {
- id: editJob.id,
- patch,
- };
-
- await webRequest<{ job: CronJob }>('cron.job.update', {
- ...updateData,
- session_id: sessionId,
- });
- setSuccess(t('cron.success.updated'));
- setEditingJobs((prev) => {
- const next = { ...prev };
- delete next[jobId];
- return next;
- });
- await loadJobs();
- void reloadCronStore();
- } catch (updateError) {
- const message = updateError instanceof Error ? updateError.message : t('cron.errors.updateFailed');
- setError(message);
- }
- };
+ return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString();
+ }
return (
- <div className="flex-1 min-h-0 relative" data-testid="cron-panel" data-session-id={sessionId}>
+ <div className="flex-1 min-h-0 relative overflow-y-auto" data-testid="cron-panel" data-session-id={sessionId}>
{success && (
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 z-20" data-testid="cron-success">
- <div className="bg-ok text-text-inverse px-4 py-2 rounded-lg shadow-lg animate-rise text-sm">
- {success}
- </div>
+ <div className="bg-ok px-4 py-2 text-sm text-text-inverse rounded-lg shadow-lg animate-rise">{success}</div>
</div>
)}
{error && (
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 z-20" data-testid="cron-error">
- <div className="bg-danger text-text-inverse px-4 py-2 rounded-lg shadow-lg animate-rise text-sm">
- {error}
- </div>
+ <div className="bg-danger px-4 py-2 text-sm text-text-inverse rounded-lg shadow-lg animate-rise">{error}</div>
</div>
)}
- <div className="card w-full h-full flex flex-col">
- <div className="flex items-center justify-between gap-4 mb-4">
+ {/* 宽度跟随主窗口自适应(w-[90%]),但用 max-w 封顶避免超宽屏上被拉得过宽,
+ 两侧留白也不会随窗口变宽而无限增大 */}
+ <div className="mx-auto w-[90%] max-w-[1600px] py-8">
+ {/* 页头 */}
+ <div className="mb-5 flex items-start justify-between">
<div>
- <h2 className="text-lg font-semibold">{t('cron.title')}</h2>
- <p className="text-sm text-text-muted mt-1">{t('cron.subtitle')}</p>
+ <h1 className="text-xl font-semibold text-text-strong">{t('cron.pageTitle')}</h1>
+ <p className="mt-1 text-sm text-text-muted">{t('cron.pageSubtitle')}</p>
+ </div>
+ <div className="relative" ref={createMenuRef}>
+ <button
+ onClick={() => setCreateMenuOpen((v) => !v)}
+ className="flex items-center gap-2 rounded-full bg-cron-action px-6 py-1.5 text-sm font-bold text-cron-action-foreground hover:bg-cron-action-hover"
+ data-testid="cron-create-toggle"
+ >
+ {t('cron.createMenu.trigger')} <ChevronDown size={14} />
+ </button>
+ {createMenuOpen && (
+ <div className="absolute right-0 top-[calc(100%+6px)] z-20 w-44 rounded-lg border border-border bg-card py-1.5 shadow-lg">
+ <button
+ onClick={() => {
+ setCreateMenuOpen(false);
+ setDrawer({ mode: 'create' });
+ }}
+ className="block w-full px-3 py-2 text-left text-sm font-semibold text-text hover:bg-bg-hover"
+ >
+ {t('cron.createMenu.manual')}
+ </button>
+ <button
+ onClick={() => {
+ setCreateMenuOpen(false);
+ onCreateViaChat(t('cron.createMenu.viaChatPrompt'));
+ }}
+ className="block w-full px-3 py-2 text-left text-sm font-semibold text-text hover:bg-bg-hover"
+ >
+ {t('cron.createMenu.viaChat')}
+ </button>
+ </div>
+ )}
</div>
- <button
- onClick={() => setIsCreating(!isCreating)}
- className="btn primary !px-4 !py-2"
- data-testid="cron-create-toggle"
- >
- {isCreating ? t('cron.cancelCreate') : t('cron.createJob')}
- </button>
</div>
- <div className="flex-1 min-h-0">
- {loading ? (
- <div className="rounded-lg border border-border bg-secondary/30 px-3 py-4 flex items-center justify-center">
- {t('cron.loading')}
+ {/* Tab 导航 */}
+ <div className="mb-4 flex items-center gap-6 border-b border-border">
+ {([
+ ['list', t('cron.tabs.list')],
+ ['template', t('cron.tabs.template')],
+ ...(CRON_HISTORY_UI_ENABLED ? [['history', t('cron.tabs.history')]] : []),
+ ] as [TabKey, string][]).map(([key, label]) => (
+ <button
+ key={key}
+ onClick={() => setActiveTab(key)}
+ className={`-mb-px border-b-2 px-1 py-2.5 text-sm font-bold transition-colors ${
+ activeTab === key ? 'border-text-strong text-text-strong' : 'border-transparent text-text-muted hover:text-text'
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {/* 任务总数统计行;任务列表/执行历史都显示,"任务总数"字号跟任务列表表格正文一致(text-sm),
+ 不用 text-lg 那么突出。任务列表额外带运行中/已暂停/过期三个分类计数(StatPill,复刻自
+ 阶段1 demo)——这是任务本身状态的完整三态,不依赖后端。"运行失败"属于执行历史维度
+ (某一次执行的结果),不属于任务列表,不会出现在这里,见 backend-requests.md #1。
+ 执行历史目前没有真实执行记录数据(tab 本身也被 CRON_HISTORY_UI_ENABLED 隐藏),先只保留
+ 总数展示,不编造假的分类计数。空状态页面不显示这一行 */}
+ {(activeTab === 'list' || activeTab === 'history') && jobs.length > 0 && (
+ <div className="mb-4 flex items-center gap-3">
+ <span className="text-sm font-bold text-text-strong">{t('cron.stats.total', { count: jobs.length })}</span>
+ {activeTab === 'list' && (
+ <>
+ <StatPill icon={<span className="text-cron-running"><RunningIcon size={15} /></span>} label={t('cron.status.running')} count={runningCount} />
+ <StatPill icon={<span className="text-text-muted"><BoldRingIcon /></span>} label={t('cron.status.paused')} count={pausedCount} />
+ <StatPill icon={<span className="text-warn"><BoldRingIcon /></span>} label={t('cron.status.expired')} count={expiredCount} />
+ </>
+ )}
+ </div>
+ )}
+
+ {/* 搜索框 */}
+ {!(activeTab === 'list' && jobs.length === 0) && activeTab !== 'history' && (
+ <div className="mb-4">
+ <div className="relative w-full">
+ <Search size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
+ <input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t('cron.search.placeholder') ?? undefined}
+ className="w-full rounded-md border border-border bg-card py-1.5 pl-9 pr-3 text-sm text-text outline-none focus:border-accent"
+ />
</div>
- ) : (
- <div className="overflow-auto rounded-lg border border-border max-h-[750px]">
- <table className="w-full border-collapse">
- <thead>
- <tr className="border-b border-border sticky top-0 bg-bg">
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted w-[160px]">{t('cron.columns.name')}</th>
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted w-[200px]">{t('cron.columns.cron')}</th>
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted">{t('cron.columns.status')}</th>
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted w-[300px]">{t('cron.columns.description')}</th>
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted w-[120px]">{t('cron.columns.wakeOffset')}</th>
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted">{t('cron.columns.timezone')}</th>
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted">{t('cron.columns.target')}</th>
- <th className="px-4 py-3 text-left text-sm font-medium text-text-muted w-[160px]">{t('cron.columns.actions')}</th>
- </tr>
- </thead>
- <tbody>
- {/* 创建任务行 */}
- {isCreating && (
- <tr className="border-b border-border bg-secondary/10 sticky top-[41px] z-5">
- <td className="px-4 py-3">
- <input
- type="text"
- value={newJob.name}
- onChange={(e) => setNewJob({ ...newJob, name: e.target.value })}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"
- placeholder={t('cron.placeholders.name')}
- data-testid="cron-create-name"
- />
- </td>
- <td className="px-4 py-3">
- <div className="relative">
- <input
- type="text"
- value={newJob.cron_expr}
- onChange={(e) => setNewJob({ ...newJob, cron_expr: e.target.value })}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent pr-8"
- placeholder={t('cron.placeholders.cronShort')}
- data-testid="cron-create-expr"
- />
- <span
- className="absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-text cursor-help"
- title={t('cron.placeholders.cron')}
- >
- <svg width="16" height="16" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
- <circle cx="20" cy="20" r="18" fill="transparent" stroke="currentColor" strokeWidth="2" />
- <text x="20" y="22" fontSize="24" fill="currentColor" textAnchor="middle" dominantBaseline="middle">?</text>
- </svg>
- </span>
- </div>
- </td>
- <td className="px-4 py-3">
- <div className="flex items-center">
- <span className="text-sm mr-2">{newJob.enabled ? t('cron.status.enabled') : t('cron.status.disabled')}</span>
- <div
- className="relative inline-block w-10 h-6 align-middle select-none rounded-full cursor-pointer"
- onClick={() => setNewJob({ ...newJob, enabled: !newJob.enabled })}
- style={{ backgroundColor: newJob.enabled ? 'var(--color-toggle-enabled)' : 'var(--color-toggle-disabled)' }}
- >
- <div
- className="absolute left-1 top-1 h-4 w-4 rounded-full bg-[var(--color-control-thumb)] "
- style={{ transform: newJob.enabled ? 'translateX(16px)' : 'none' }}
- />
- </div>
+ </div>
+ )}
+
+ {/* tab: 任务列表 */}
+ {activeTab === 'list' && loading && (
+ <div className="rounded-lg border border-border bg-secondary/30 px-3 py-4 flex items-center justify-center">
+ {t('cron.loading')}
+ </div>
+ )}
+ {activeTab === 'list' && !loading && jobs.length === 0 && (
+ <div className="flex min-h-[70vh] flex-col items-center">
+ {/* 创建定时任务模块保持在可视区域垂直居中 */}
+ <div className="flex flex-1 flex-col items-center justify-center gap-4">
+ <img src={emptyIllustration} alt="" className="h-20 w-20" />
+ <button onClick={() => setDrawer({ mode: 'create' })} className="btn !px-4 !py-2">
+ {t('cron.empty.createButton')}
+ </button>
+ </div>
+ {/* 任务模板模块沉到页面下方,不紧跟在创建按钮下面 */}
+ <div className="w-full pb-4">
+ <div className="mb-3 flex items-center justify-between">
+ <span className="text-sm font-bold text-text-strong">{t('cron.empty.templateSectionTitle')}</span>
+ <button onClick={() => setActiveTab('template')} className="text-xs text-accent hover:text-accent-hover">
+ {t('cron.empty.templateMore')}
+ </button>
+ </div>
+ <div className="grid grid-cols-3 gap-4">
+ {CRON_TEMPLATES.map((tpl) => (
+ <button
+ key={tpl.id}
+ onClick={() => openTemplateDrawer(tpl)}
+ className="rounded-lg border border-border bg-card p-4 text-left transition-colors hover:border-accent"
+ >
+ <div className="mb-2 flex items-center gap-2">
+ <TemplateIcon icon={tpl.icon} />
+ <span className="text-sm font-bold text-text-strong">{t(tpl.titleKey)}</span>
+ </div>
+ <p className="line-clamp-3 text-xs leading-relaxed text-text-muted">{t(tpl.descriptionKey)}</p>
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+ {activeTab === 'list' && !loading && jobs.length > 0 && (
+ <div className="overflow-visible rounded-lg border border-border">
+ <table className="w-full border-collapse text-sm">
+ <thead>
+ <tr className="border-b border-border bg-bg-muted text-left text-text">
+ <Th first>{t('cron.table.name')}</Th>
+ <Th>{t('cron.table.project')}</Th>
+ <Th>{t('cron.table.schedule')}</Th>
+ <Th>{t('cron.table.status')}</Th>
+ <Th>{t('cron.table.timezone')}</Th>
+ <Th>{t('cron.table.channel')}</Th>
+ <Th>{t('cron.table.actions')}</Th>
+ </tr>
+ </thead>
+ <tbody>
+ {filteredJobs.map((job) => {
+ const isProactive = job.id === PROACTIVE_AUTO_JOB_ID;
+ return (
+ <tr key={job.id} className="border-b border-border last:border-0">
+ <td className="px-4 py-3 text-text">
+ <div className="flex items-center gap-1">
+ {job.name}
+ {isProactive && (
+ <span
+ className="inline-flex shrink-0 items-center rounded-full bg-cron-auto-managed-surface px-1.5 py-0.5 text-[10px] font-medium text-cron-auto-managed-text"
+ title={t('cron.autoManagedHint') ?? undefined}
+ >
+ {t('cron.autoManaged')}
+ </span>
+ )}
</div>
</td>
+ <td className="px-4 py-3 text-text">{job.projectName ?? t('cron.table.noProject')}</td>
+ <td className="px-4 py-3 text-text">{scheduleLabel(job.cronExpr)}</td>
+ {/* proactive 自动维护 job 的整体开关由 config 控制(关了就删除,不在列表里),
+ 因此这里只有两态:过期 → 过期;否则 → 启用,不显示"禁用"中间态
+ (沿用 upstream 提交 59cf6de7 的约束) */}
<td className="px-4 py-3">
- <input
- type="text"
- value={newJob.description}
- onChange={(e) => setNewJob({ ...newJob, description: e.target.value })}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"
- placeholder={t('cron.placeholders.description')}
- data-testid="cron-create-description"
- />
+ <StatusBadge enabled={isProactive ? !job.expired : job.enabled} expired={job.expired} />
</td>
- <td className="px-4 py-3">
- <input
- type="number"
- value={newJob.wake_offset_seconds}
- onChange={(e) => setNewJob({ ...newJob, wake_offset_seconds: parseInt(e.target.value, 10) || 0 })}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"
- placeholder={t('cron.placeholders.wakeOffset')}
- data-testid="cron-create-wake-offset"
- />
- </td>
- <td className="px-4 py-3">
- <select
- value={newJob.timezone}
- onChange={(e) => setNewJob({ ...newJob, timezone: e.target.value })}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"
- data-testid="cron-create-timezone"
- >
- {timezoneOptions.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- </td>
- <td className="px-4 py-3">
- <select
- value={newJob.targets}
- onChange={(e) => setNewJob({ ...newJob, targets: e.target.value })}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"
- data-testid="cron-create-target"
- >
- {targetOptions.map((option) => (
- <option key={option.value} value={option.value} disabled={option.disabled}>
- {option.label}
- </option>
- ))}
- </select>
- </td>
- <td className="px-4 py-3 text-right">
- <div className="flex items-enter gap-2">
- <button
- onClick={() => {
- setIsCreating(false);
- setNewJob({
- name: '',
- enabled: true,
- cron_expr: '',
- timezone: DEFAULT_CRON_TIMEZONE,
- wake_offset_seconds: 300,
- description: '',
- targets: DEFAULT_CRON_TARGET,
- });
- }}
- className="btn !px-3 !py-1.5"
- >
- {t('common.cancel')}
- </button>
- <button
- onClick={handleCreateJob}
- className="btn primary !px-3 !py-1.5"
- data-testid="cron-create-submit"
- >
- {t('cron.create')}
- </button>
- </div>
- </td>
- </tr>
- )}
-
- {/* 任务列表 */}
- {cronJobs.length === 0 ? (
- <tr>
- <td colSpan={8} className="px-4 py-8 text-center text-text-muted">
- {t('cron.empty')}
- </td>
- </tr>
- ) : (
- cronJobs.map((job) => {
- const isEditing = editingJobs[job.id] !== undefined;
- const editJob = editingJobs[job.id];
- const displayCron = renderScheduleSummary(job);
- const displayDescription = resolveDescription(job);
- const displayTimezone = resolveTimezone(job);
- const displayTarget = resolveTargets(job);
-
- return isEditing && editJob ? (
- <tr key={job.id} className="border-b border-border bg-secondary/10">
- <td className="px-4 py-3">
- <input
- type="text"
- value={editJob.name}
- onChange={(e) => setEditingJobs((prev) => ({
- ...prev,
- [job.id]: { ...prev[job.id], name: e.target.value },
- }))}
- disabled={job.id === PROACTIVE_AUTO_JOB_ID}
- className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}
- placeholder={t('cron.placeholders.name')}
- />
- </td>
- <td className="px-4 py-3">
- <div className="relative">
- <input
- type="text"
- value={editJob.cron_expr}
- onChange={(e) => setEditingJobs((prev) => ({
- ...prev,
- [job.id]: { ...prev[job.id], cron_expr: e.target.value },
- }))}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent pr-8"
- placeholder={t('cron.placeholders.cronShort')}
- />
- <span
- className="absolute right-2 top-1/2 -translate-y-1/2 text-text-muted hover:text-text cursor-help"
- title={t('cron.placeholders.cron')}
- >
- <svg width="16" height="16" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
- <circle cx="20" cy="20" r="18" fill="transparent" stroke="currentColor" strokeWidth="2" />
- <text x="20" y="22" fontSize="24" fill="currentColor" textAnchor="middle" dominantBaseline="middle">?</text>
- </svg>
- </span>
- </div>
- </td>
- <td className="px-4 py-3">
- <div className="flex items-center">
- <span className="text-sm mr-2">{editJob.enabled ? t('cron.status.enabled') : t('cron.status.disabled')}</span>
- <div
- className={`relative inline-block w-10 h-6 align-middle select-none rounded-full ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
- onClick={job.id === PROACTIVE_AUTO_JOB_ID ? undefined : () => setEditingJobs((prev) => ({
- ...prev,
- [job.id]: { ...prev[job.id], enabled: !prev[job.id].enabled },
- }))}
- title={job.id === PROACTIVE_AUTO_JOB_ID ? t('cron.autoManagedToggleDisabled') : undefined}
- style={{ backgroundColor: editJob.enabled ? 'var(--color-toggle-enabled)' : 'var(--color-toggle-disabled)' }}
- >
- <div
- className="absolute left-1 top-1 h-4 w-4 rounded-full bg-[var(--color-control-thumb)] "
- style={{ transform: editJob.enabled ? 'translateX(16px)' : 'none' }}
- />
- </div>
- </div>
- </td>
- <td className="px-4 py-3">
- <input
- type="text"
- value={editJob.description || ''}
- onChange={(e) => setEditingJobs((prev) => ({
- ...prev,
- [job.id]: { ...prev[job.id], description: e.target.value },
- }))}
- disabled={job.id === PROACTIVE_AUTO_JOB_ID}
- className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}
- placeholder={t('cron.placeholders.description')}
- />
- </td>
- <td className="px-4 py-3">
- <input
- type="number"
- value={job.id === PROACTIVE_AUTO_JOB_ID ? 0 : editJob.wake_offset_seconds}
- onChange={(e) => setEditingJobs((prev) => ({
- ...prev,
- [job.id]: { ...prev[job.id], wake_offset_seconds: parseInt(e.target.value, 10) || 0 },
- }))}
- disabled={job.id === PROACTIVE_AUTO_JOB_ID}
- className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}
- placeholder={t('cron.placeholders.wakeOffset')}
- />
- </td>
- <td className="px-4 py-3">
- <select
- value={editJob.timezone}
- onChange={(e) => setEditingJobs((prev) => ({
- ...prev,
- [job.id]: { ...prev[job.id], timezone: e.target.value },
- }))}
- className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"
+ <td className="px-4 py-3 text-text">{job.timezone}</td>
+ <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}>
+ {t('cron.table.runNow')}
+ </span>
+ ) : (
+ <button
+ onClick={() => setConfirmState({ type: 'runNow', job })}
+ className="text-sm text-cron-action-link hover:opacity-80"
>
- {timezoneOptions.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- </td>
- <td className="px-4 py-3">
- <select
- value={editJob.targets}
- onChange={(e) => setEditingJobs((prev) => ({
- ...prev,
- [job.id]: { ...prev[job.id], targets: e.target.value },
- }))}
- disabled={job.id === PROACTIVE_AUTO_JOB_ID}
- className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent ${job.id === PROACTIVE_AUTO_JOB_ID ? 'opacity-50 cursor-not-allowed' : ''}`}
+ {t('cron.table.runNow')}
+ </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>
+ ) : (
+ <button
+ onClick={() => setConfirmState({ type: 'stop', job })}
+ className="text-sm text-cron-action-link hover:opacity-80"
>
- {targetOptions.map((option) => (
- <option key={option.value} value={option.value} disabled={option.disabled}>
- {option.label}
- </option>
- ))}
- </select>
- </td>
- <td className="px-4 py-3 text-left">
- <div className="flex items-center gap-2">
- <button
- onClick={() => setEditingJobs((prev) => {
- const next = { ...prev };
- delete next[job.id];
- return next;
- })}
- className="btn !px-3 !py-1.5"
- >
- {t('common.cancel')}
- </button>
- <button
- onClick={() => handleSubmitUpdate(job.id)}
- className="btn primary !px-3 !py-1.5"
- >
- {t('cron.update')}
- </button>
- </div>
- </td>
- </tr>
- ) : (
- <tr
- key={job.id}
- className="border-b border-border hover:bg-secondary/10"
- data-testid={`cron-row-${job.id}`}
- data-cron-id={job.id}
- data-cron-name={job.name}
- >
- <td className="px-4 py-3 text-sm">
- <div className="flex items-center gap-1">
- <div className="max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap" title={job.name}>
- {job.name}
- </div>
- {job.id === PROACTIVE_AUTO_JOB_ID && (
- <span
- className="shrink-0 inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-sky-100 text-sky-700"
- title={t('cron.autoManagedHint')}
+ {t('cron.table.stop')}
+ </button>
+ )}
+ <div className="relative" ref={rowMenuJobId === job.id ? rowMenuRef : undefined}>
+ <button
+ onClick={() => setRowMenuJobId(rowMenuJobId === job.id ? null : job.id)}
+ className="flex items-center gap-0.5 text-sm text-cron-action-link hover:opacity-80"
+ >
+ {t('cron.table.more')} <ChevronDown size={13} />
+ </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.autoManaged')}
- </span>
- )}
- </div>
- </td>
- <td className="px-4 py-3 text-sm mono" data-testid={`cron-schedule-${job.id}`}>
- {displayCron}
- </td>
- <td className="px-4 py-3">
- {(() => {
- // proactive 自动维护 job 的整体开关由 config 控制(关了就删除,不在列表里),
- // 因此状态只有两态:cron 过期 → 过期;否则 → 启用。不显示"禁用"中间态。
- const isProactiveRow = job.id === PROACTIVE_AUTO_JOB_ID;
- const isExpired = Boolean(job.expired);
- const isEnabled = isProactiveRow ? !isExpired : Boolean(job.enabled);
- return (
- <span
- className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
- isExpired ? 'bg-amber-100 text-amber-700' : isEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'
- }`}
+ {t('cron.table.edit')}
+ </button>
+ <button
+ onClick={() => {
+ setRowMenuJobId(null);
+ void toggleSessionsPopover(job);
+ }}
+ className="block w-full px-3 py-2 text-left text-sm text-cron-action-link hover:bg-bg-hover"
>
- {isExpired ? t('cron.status.expired') : isEnabled ? t('cron.status.enabled') : t('cron.status.disabled')}
- </span>
- );
- })()}
- </td>
- <td className="px-4 py-3 text-sm text-text-muted">
- <div className="max-w-[300px] overflow-hidden text-ellipsis whitespace-nowrap" title={displayDescription || '-'}>
- {displayDescription || '-'}
- </div>
- {previewJobId === job.id && (
- <div className="mt-2 space-y-1 text-xs text-text-muted" data-testid={`cron-preview-${job.id}`}>
- {previewLoading ? (
- <div>{t('cron.preview.loading')}</div>
- ) : previewRuns.length > 0 ? (
- previewRuns.map((item, index) => (
- <div key={`${job.id}-${index}`} data-testid={`cron-preview-${job.id}-${index}`}>
- {t('cron.preview.label', { index: index + 1 })}: {formatPreviewTime(item.push_at)}
- </div>
- ))
+ {t('cron.table.triggeredSessions')}
+ </button>
+ <button
+ onClick={() => {
+ setRowMenuJobId(null);
+ void togglePreviewPopover(job);
+ }}
+ className="block w-full px-3 py-2 text-left text-sm text-cron-action-link hover:bg-bg-hover"
+ >
+ {t('cron.previewAction')}
+ </button>
+ {isProactive ? (
+ <span
+ className="block w-full px-3 py-2 text-left text-sm text-text-muted/50 cursor-not-allowed"
+ title={t('cron.autoManagedToggleDisabled') ?? undefined}
+ >
+ {t('cron.delete')}
+ </span>
) : (
- <div>{t('cron.preview.empty')}</div>
+ <button
+ onClick={() => {
+ setRowMenuJobId(null);
+ setConfirmState({ type: 'delete', job });
+ }}
+ className="block w-full px-3 py-2 text-left text-sm text-danger hover:bg-bg-hover"
+ >
+ {t('cron.delete')}
+ </button>
+ )}
+ {CRON_HISTORY_UI_ENABLED && (
+ <button
+ onClick={() => {
+ setRowMenuJobId(null);
+ setSuccess(t('cron.history.comingSoon'));
+ }}
+ className="block w-full px-3 py-2 text-left text-sm text-cron-action-link hover:bg-bg-hover"
+ >
+ {t('cron.table.history')}
+ </button>
)}
</div>
)}
- </td>
- <td className="px-4 py-3 text-sm text-text-muted">
- {job.wake_offset_seconds}
- </td>
- <td className="px-4 py-3 text-sm text-text-muted">
- {displayTimezone}
- </td>
- <td className="px-4 py-3 text-sm text-text-muted">
- {displayTarget || '-'}
- </td>
- <td className="px-4 py-3 text-left">
- <div className="flex items-center gap-4">
- <span
- onClick={() => handleRunNow(job.id, job.expired)}
- className="cursor-pointer text-sm text-accent"
- data-testid={`cron-run-${job.id}`}
- >
- {t('cron.runNow')}
- </span>
- <span
- onClick={() => handlePreviewRuns(job.id)}
- className="cursor-pointer text-sm text-accent"
- data-testid={`cron-preview-action-${job.id}`}
- >
- {t('cron.previewAction')}
- </span>
- {job.id === PROACTIVE_AUTO_JOB_ID ? (
- <span
- className="text-sm text-text-muted/50 cursor-not-allowed select-none"
- title={t('cron.autoManagedToggleDisabled')}
- data-testid={`cron-toggle-${job.id}`}
- >
- {job.enabled ? t('cron.disable') : t('cron.enable')}
- </span>
- ) : (
- <span
- onClick={() => handleToggleJob(job.id, job.enabled, job.expired)}
- className={`cursor-pointer text-sm ${job.enabled ? 'text-danger' : 'text-accent'}`}
- data-testid={`cron-toggle-${job.id}`}
- >
- {job.enabled ? t('cron.disable') : t('cron.enable')}
- </span>
- )}
- <span
- onClick={() => handleUpdateJob(job.id)}
- className="cursor-pointer text-sm text-accent"
- >
- {t('cron.update')}
- </span>
- {job.id === PROACTIVE_AUTO_JOB_ID ? (
- <span
- className="text-sm text-text-muted/50 cursor-not-allowed select-none"
- title={t('cron.autoManagedToggleDisabled')}
- data-testid={`cron-delete-${job.id}`}
- >
- {t('cron.delete')}
- </span>
- ) : (
- <span
- onClick={() => handleDeleteJob(job.id)}
- className="cursor-pointer text-sm text-accent"
- data-testid={`cron-delete-${job.id}`}
- >
- {t('cron.delete')}
- </span>
- )}
- </div>
- </td>
- </tr>
- );
- })
- )}
- </tbody>
- </table>
- </div>
- )}
- </div>
+ </div>
+ </div>
+ {sessionsPopoverJobId === job.id && (
+ <div
+ ref={sessionsPopoverRef}
+ className="absolute right-4 top-[calc(100%+4px)] z-20 w-64 rounded-lg border border-border bg-card py-1.5 shadow-lg"
+ >
+ <div className="px-3 py-1.5 text-xs font-bold text-text-muted">{t('cron.table.triggeredSessions')}</div>
+ {triggeredSessionsLoading[job.id] && (
+ <div className="px-3 py-2 text-sm text-text-muted">{t('common.loading')}</div>
+ )}
+ {!triggeredSessionsLoading[job.id] && (triggeredSessions[job.id]?.length ?? 0) > 0 && (
+ <div className="max-h-64 overflow-y-auto">
+ {triggeredSessions[job.id].map((s) => (
+ <button
+ key={s.session_id}
+ onClick={() => {
+ setSessionsPopoverJobId(null);
+ onSelectSession(s);
+ }}
+ className="block w-full truncate px-3 py-2 text-left text-sm text-text hover:bg-bg-hover"
+ title={s.title}
+ >
+ {s.title || s.session_id}
+ </button>
+ ))}
+ </div>
+ )}
+ {!triggeredSessionsLoading[job.id] && (triggeredSessions[job.id]?.length ?? 0) === 0 && (
+ <div className="px-3 py-2 text-sm text-text-muted">{t('cron.table.noTriggeredSessions')}</div>
+ )}
+ </div>
+ )}
+ {previewPopoverJobId === job.id && (
+ <div
+ ref={previewPopoverRef}
+ className="absolute right-4 top-[calc(100%+4px)] z-20 w-64 rounded-lg border border-border bg-card py-1.5 shadow-lg"
+ >
+ <div className="truncate px-3 py-1.5 text-xs font-bold text-text-muted" title={job.name}>{job.name}</div>
+ {previewLoading[job.id] && (
+ <div className="px-3 py-2 text-sm text-text-muted">{t('cron.preview.loading')}</div>
+ )}
+ {!previewLoading[job.id] && (previewRuns[job.id]?.length ?? 0) > 0 && (
+ <div className="px-3 py-2 text-xs text-text">
+ {previewRuns[job.id].map((item, index) => (
+ <div key={`${job.id}-${index}`} className="py-0.5">
+ {t('cron.preview.label', { index: index + 1 })}:{formatPreviewTime(item.push_at)}
+ </div>
+ ))}
+ </div>
+ )}
+ {!previewLoading[job.id] && (previewRuns[job.id]?.length ?? 0) === 0 && (
+ <div className="px-3 py-2 text-sm text-text-muted">{t('cron.preview.empty')}</div>
+ )}
+ </div>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ {/* tab: 任务模板 */}
+ {activeTab === 'template' && (
+ <div className="grid grid-cols-3 gap-4">
+ {filteredTemplates.map((tpl) => (
+ <button
+ key={tpl.id}
+ onClick={() => openTemplateDrawer(tpl)}
+ className="rounded-lg border border-border bg-card p-4 text-left transition-colors hover:border-accent"
+ >
+ <div className="mb-2 flex items-center gap-2">
+ <TemplateIcon icon={tpl.icon} />
+ <span className="text-sm font-bold text-text-strong">{t(tpl.titleKey)}</span>
+ </div>
+ <p className="text-xs leading-relaxed text-text-muted">{t(tpl.descriptionKey)}</p>
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* tab: 执行历史(等 backend-requests.md #1 交付后接入真实数据,见 plan.md §5) */}
+ {activeTab === 'history' && (
+ <div className="flex flex-col items-center gap-2 rounded-lg border border-border py-16 text-text-muted">
+ <p className="text-sm">{t('cron.history.comingSoon')}</p>
+ </div>
+ )}
+
+ {/* 创建/编辑/模板抽屉 */}
+ {drawer && (
+ <CronTaskDrawer
+ mode={drawer.mode}
+ initial={drawer.initial}
+ projects={projects}
+ targetOptions={targetOptions}
+ proactiveLocked={drawer.mode === 'edit' && drawer.jobId === PROACTIVE_AUTO_JOB_ID}
+ onClose={() => setDrawer(null)}
+ onSwitchToManual={drawer.mode === 'template' ? () => setDrawer({ mode: 'create', initial: drawer.initial }) : undefined}
+ onSwitchToTemplate={drawer.mode === 'create' ? () => { setDrawer(null); setActiveTab('template'); } : undefined}
+ onSubmit={(value) => {
+ if (drawer.mode === 'edit') void handleEditSubmit(drawer.jobId, value);
+ else void handleCreateSubmit(value);
+ }}
+ />
+ )}
+
+ {/* 删除确认弹窗 */}
+ {confirmState?.type === 'delete' && (
+ <ConfirmDialog
+ title={t('cron.confirm.deleteTitle')}
+ message={t('cron.confirm.deleteMessage', { name: confirmState.job.name })}
+ onConfirm={() => void handleDeleteConfirm()}
+ onCancel={() => setConfirmState(null)}
+ loading={confirmBusy}
+ />
+ )}
+
+ {/* 停止确认弹窗 */}
+ {confirmState?.type === 'stop' && (
+ <ConfirmDialog
+ title={t('cron.confirm.stopTitle')}
+ message={t('cron.confirm.stopMessage', { name: confirmState.job.name })}
+ onConfirm={() => void handleStopConfirm()}
+ onCancel={() => setConfirmState(null)}
+ loading={confirmBusy}
+ />
+ )}
+
+ {/* 立即执行确认弹窗 */}
+ {confirmState?.type === 'runNow' && (
+ <ConfirmDialog
+ title={t('cron.confirm.runNowTitle')}
+ message={t('cron.confirm.runNowMessage', { name: confirmState.job.name })}
+ onConfirm={() => void handleRunNowConfirm()}
+ onCancel={() => setConfirmState(null)}
+ loading={confirmBusy}
+ />
+ )}
</div>
</div>
);
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/scheduleConvert.ts b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/scheduleConvert.ts
new file mode 100644
index 0000000000..d164a5c326
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/scheduleConvert.ts
@@ -0,0 +1,249 @@
+import type { CronSchedule } from '../../types/cron';
+
+// schedule ⇄ cron_expr(7段式:秒 分 时 日 月 周 年,croniter 语法)双向转换。
+// 星期字段用 croniter 实测出的真实编号:0=周日...6=周六(不是 Quartz 的 1=SUN),见 plan.md §2.3.1。
+// 6 种模式各自占据互不冲突的字段形状(是否有步长/日或月是否具体/年是否固定),可以无损双向转换;
+// 匹配不到任何一种形状的表达式(比如 Agent 工具/TUI 建的、或日周字段同时给了具体值的)返回 null,
+// 调用方应当回退展示"Cron表达式"原文,不强行拆解。
+
+function pad2(n: number): string {
+ return String(n).padStart(2, '0');
+}
+
+function parseTime(time: string | undefined): { h: number; m: number } | null {
+ if (!time) return null;
+ const match = time.match(/^(\d{1,2}):(\d{1,2})$/);
+ if (!match) return null;
+ const h = Number(match[1]);
+ const m = Number(match[2]);
+ if (h < 0 || h > 23 || m < 0 || m > 59) return null;
+ return { h, m };
+}
+
+function isWildcard(field: string): boolean {
+ return field === '*' || field === '?';
+}
+
+/** field 是单个具体整数(不含逗号/区间/步长),返回该数字;否则 null */
+function parseSingleInt(field: string): number | null {
+ if (!/^\d+$/.test(field)) return null;
+ return Number(field);
+}
+
+/** field 是逗号分隔的整数列表(不含区间/步长),返回排序去重后的数组;否则 null */
+function parseIntList(field: string): number[] | null {
+ const parts = field.split(',');
+ const nums: number[] = [];
+ for (const p of parts) {
+ if (!/^\d+$/.test(p)) return null;
+ nums.push(Number(p));
+ }
+ if (nums.length === 0) return null;
+ return Array.from(new Set(nums)).sort((a, b) => a - b);
+}
+
+/**
+ * field 是"每月第几周的星期几"形状(`{dow}#{1-5}` 或 `L{dow}`,逗号分隔多个星期几),
+ * 且所有段用的是同一个"第几周"(不支持混用,见 plan.md §2.3.8 第3点);否则 null。
+ */
+function parseMonthlyWeekdayField(field: string): { weekdays: number[]; weekOfMonth: number | 'L' } | null {
+ const parts = field.split(',');
+ const weekdays: number[] = [];
+ let weekOfMonth: number | 'L' | null = null;
+ for (const p of parts) {
+ const hashMatch = p.match(/^(\d)#([1-5])$/);
+ const lastMatch = p.match(/^L(\d)$/);
+ if (hashMatch) {
+ const dow = Number(hashMatch[1]);
+ const n = Number(hashMatch[2]);
+ if (dow > 6) return null;
+ if (weekOfMonth === null) weekOfMonth = n;
+ else if (weekOfMonth !== n) return null;
+ weekdays.push(dow);
+ } else if (lastMatch) {
+ const dow = Number(lastMatch[1]);
+ if (dow > 6) return null;
+ if (weekOfMonth === null) weekOfMonth = 'L';
+ else if (weekOfMonth !== 'L') return null;
+ weekdays.push(dow);
+ } else {
+ return null;
+ }
+ }
+ if (weekOfMonth === null || weekdays.length === 0) return null;
+ return { weekdays: Array.from(new Set(weekdays)).sort((a, b) => a - b), weekOfMonth };
+}
+
+export function scheduleToCronExpr(schedule: CronSchedule): string {
+ switch (schedule.kind) {
+ case 'daily': {
+ const t = parseTime(schedule.time);
+ if (!t) return '';
+ return `0 ${t.m} ${t.h} * * ? *`;
+ }
+ case 'weekly': {
+ const t = parseTime(schedule.time);
+ if (!t || !schedule.weekdays || schedule.weekdays.length === 0) return '';
+ const days = Array.from(new Set(schedule.weekdays)).sort((a, b) => a - b).join(',');
+ return `0 ${t.m} ${t.h} ? * ${days} *`;
+ }
+ case 'monthly': {
+ const t = parseTime(schedule.time);
+ if (!t || schedule.day === undefined) return '';
+ return `0 ${t.m} ${t.h} ${schedule.day} * ? *`;
+ }
+ case 'monthlyWeekday': {
+ const t = parseTime(schedule.time);
+ if (!t || !schedule.weekdays || schedule.weekdays.length === 0 || schedule.weekOfMonth === undefined) return '';
+ const days = Array.from(new Set(schedule.weekdays)).sort((a, b) => a - b)
+ .map((d) => (schedule.weekOfMonth === 'L' ? `L${d}` : `${d}#${schedule.weekOfMonth}`))
+ .join(',');
+ return `0 ${t.m} ${t.h} ? * ${days} *`;
+ }
+ case 'yearly': {
+ const t = parseTime(schedule.time);
+ if (!t || !schedule.month || !schedule.day) return '';
+ 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(',')
+ : '*';
+ return `0 0 */${schedule.everyHours} * * ${days} *`;
+ }
+ case 'once': {
+ const t = parseTime(schedule.time);
+ if (!t || !schedule.date) return '';
+ const m = schedule.date.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
+ if (!m) return '';
+ const [, y, mo, d] = m;
+ return `0 ${t.m} ${t.h} ${Number(d)} ${Number(mo)} ? ${y}`;
+ }
+ default:
+ return '';
+ }
+}
+
+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;
+
+ const min = parseSingleInt(minute);
+ const hr = parseSingleInt(hour);
+
+ // once:年份是固定值
+ if (!isWildcard(year)) {
+ const y = parseSingleInt(year);
+ const d = parseSingleInt(day);
+ const mo = parseSingleInt(month);
+ if (y === null || d === null || mo === null || hr === null || min === null) return null;
+ if (!isWildcard(week)) return null;
+ return { kind: 'once', time: `${pad2(hr)}:${pad2(min)}`, date: `${y}-${pad2(mo)}-${pad2(d)}` };
+ }
+
+ // interval:小时字段带步长
+ 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 };
+ }
+ const days = parseIntList(week);
+ if (!days) return null;
+ return { kind: 'interval', everyHours: n, weekdays: days };
+ }
+
+ if (hr === null || min === null) return null;
+ const time = `${pad2(hr)}:${pad2(min)}`;
+
+ // 日字段通配、周字段非通配:先试"每月第几周星期几"形状,再试普通"每周"形状
+ if (isWildcard(day) && month === '*' && !isWildcard(week)) {
+ const monthlyWeekday = parseMonthlyWeekdayField(week);
+ if (monthlyWeekday) {
+ return { kind: 'monthlyWeekday', time, weekdays: monthlyWeekday.weekdays, weekOfMonth: monthlyWeekday.weekOfMonth };
+ }
+ const days = parseIntList(week);
+ if (!days) return null;
+ return { kind: 'weekly', time, weekdays: days };
+ }
+
+ // daily:日、月、周都通配
+ if (isWildcard(day) && month === '*' && isWildcard(week)) {
+ return { kind: 'daily', time };
+ }
+
+ // monthly:日字段是具体数字或 'L',月字段通配
+ if ((day === 'L' || parseSingleInt(day) !== null) && month === '*' && isWildcard(week)) {
+ return { kind: 'monthly', time, day: day === 'L' ? 'L' : Number(day) };
+ }
+
+ // yearly:日、月字段都是具体数字
+ const d = parseSingleInt(day);
+ const mo = parseSingleInt(month);
+ if (d !== null && mo !== null && isWildcard(week)) {
+ return { kind: 'yearly', time, day: d, month: mo };
+ }
+
+ return null;
+}
+
+type TFn = (key: string, options?: Record<string, unknown>) => string;
+
+// 星期真实编号(0=周日...6=周六)→ i18n key 后缀,供拼接"每周一、三、五"这样的摘要文案用
+const WEEKDAY_KEY_BY_VALUE: Record<number, string> = {
+ 0: 'sun', 1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5: 'fri', 6: 'sat',
+};
+
+function joinWeekdays(weekdays: number[], t: TFn): string {
+ return weekdays
+ .map((d) => t(`cron.schedule.weekday.${WEEKDAY_KEY_BY_VALUE[d]}`))
+ .join(t('cron.schedule.listSeparator'));
+}
+
+/**
+ * 把结构化 schedule 转成人类可读的摘要文案("每天 09:30"这种),用于任务列表"计划于"列展示,
+ * 替代直接显示 7 段式 cron_expr 原文——原文对普通用户来说太不直观了。
+ * 只有 index.tsx 的 cronExprToSchedule(job.cronExpr) 解析成功时才调用这个函数;
+ * 解析不出来的(非 6 种模式生成的表达式)由调用方自行回退展示 cron_expr 原文。
+ */
+export function summarizeSchedule(schedule: CronSchedule, t: TFn): string {
+ switch (schedule.kind) {
+ case 'daily':
+ return t('cron.schedule.summary.daily', { time: schedule.time ?? '' });
+ case 'weekly':
+ return t('cron.schedule.summary.weekly', {
+ days: joinWeekdays(schedule.weekdays ?? [], t),
+ time: schedule.time ?? '',
+ });
+ case 'monthly':
+ return t('cron.schedule.summary.monthly', {
+ // "每月" + "月末最后一天" 会重复"月"字,摘要场景下用更短的"月末"
+ day: schedule.day === 'L' ? t('cron.schedule.summary.lastDay') : t('cron.schedule.dayOption', { day: schedule.day }),
+ time: schedule.time ?? '',
+ });
+ case 'monthlyWeekday':
+ return t('cron.schedule.summary.monthlyWeekday', {
+ weekOfMonth: t(`cron.schedule.weekOfMonth.${schedule.weekOfMonth === 'L' ? 'last' : schedule.weekOfMonth}`),
+ days: joinWeekdays(schedule.weekdays ?? [], t),
+ time: schedule.time ?? '',
+ });
+ case 'yearly':
+ return t('cron.schedule.summary.yearly', {
+ month: schedule.month ?? '',
+ day: schedule.day ?? '',
+ time: schedule.time ?? '',
+ });
+ case '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 });
+ case 'once':
+ return t('cron.schedule.summary.once', { date: schedule.date ?? '', time: schedule.time ?? '' });
+ default:
+ return '';
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/CronPanel/useClickOutside.ts b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/useClickOutside.ts
new file mode 100644
index 0000000000..6c58a499bf
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/CronPanel/useClickOutside.ts
@@ -0,0 +1,14 @@
+import { useEffect, type RefObject } from 'react';
+
+export function useClickOutside(ref: RefObject<HTMLElement>, active: boolean, onOutside: () => void) {
+ useEffect(() => {
+ if (!active) return;
+ function handlePointerDown(e: PointerEvent) {
+ if (ref.current && !ref.current.contains(e.target as Node)) {
+ onOutside();
+ }
+ }
+ document.addEventListener('pointerdown', handlePointerDown);
+ return () => document.removeEventListener('pointerdown', handlePointerDown);
+ }, [active, ref, onOutside]);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
index d799b9d278..ec3b09a4ea 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionSidebar/index.tsx
@@ -17,7 +17,6 @@ import logoIcon from '/logo.svg';
import AdvancedConfigIcon from '../../assets/sidebar/advanced-config-new.svg?react';
import UpdateIcon from '../../assets/sidebar/advanced-config.svg?react';
import WorkIcon from '../../assets/工作.svg?react';
-import CronDesignIcon from '../../assets/定时任务.svg?react';
import SkillDesignIcon from '../../assets/技能.svg?react';
import AgentDesignIcon from '../../assets/智能体.svg?react';
import MoreDesignIcon from '../../assets/更多.svg?react';
@@ -50,7 +49,6 @@ const teamNavIcon = (
const mainNavItems: NavItem[] = [
{ key: 'chat', labelKey: 'nav.work', icon: <WorkIcon aria-hidden /> },
- { key: 'cron', labelKey: 'nav.cron', icon: <CronDesignIcon aria-hidden /> },
{ key: 'skills', labelKey: 'nav.skills', icon: <SkillDesignIcon aria-hidden /> },
{ key: 'channels', labelKey: 'nav.channels', icon: <ChannelIcon aria-hidden /> },
{ key: 'agents', labelKey: 'nav.agent', icon: <AgentDesignIcon aria-hidden /> },
diff --git a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.css b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.css
index af7a22682e..810a2b00bb 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.css
+++ b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.css
@@ -8,26 +8,11 @@
}
.share-image-document {
- --accent-subtle: #eef4ff;
- --accent: #3370ff;
- --bg: #f5f7f9;
- --bg-muted: #ffffff;
- --bg-content: #ffffff;
- --border: #dde4ee;
- --card: #ffffff;
- --chat-text: #1f2937;
- --muted: #667085;
- --radius-full: 999px;
- --radius-lg: 8px;
- --secondary: #f2f4f7;
- --text: #1f2937;
- --text-strong: #101828;
-
width: 750px;
min-height: 1px;
box-sizing: border-box;
- background: #f5f7f9;
- color: var(--text);
+ background: var(--color-surface-page);
+ color: var(--color-text-primary);
padding: 26px 18px 28px;
font-family: var(--font-body);
}
@@ -64,7 +49,7 @@
}
.share-image-brand__name {
- color: var(--text-strong);
+ color: var(--color-text-strong);
font-size: 24px;
font-weight: 800;
line-height: 1;
@@ -72,21 +57,21 @@
}
.share-image-content {
- border: 1px solid color-mix(in srgb, var(--border) 86%, transparent);
+ border: 1px solid color-mix(in srgb, var(--color-border-default) 86%, transparent);
border-radius: 8px;
- background: var(--bg-content);
+ background: var(--color-surface-content);
padding: 26px 28px 30px;
}
.share-image-content-header {
- border-bottom: 1px solid var(--border);
+ border-bottom: 1px solid var(--color-border-default);
padding-bottom: 22px;
margin-bottom: 26px;
}
.share-image-content-header h1 {
margin: 0;
- color: var(--text-strong);
+ color: var(--color-text-strong);
font-size: 20px;
font-weight: 750;
line-height: 1.25;
@@ -101,7 +86,7 @@
flex-wrap: wrap;
gap: 8px 14px;
margin-top: 12px;
- color: var(--muted);
+ color: var(--color-text-secondary);
font-size: 15px;
line-height: 1.4;
}
@@ -115,7 +100,7 @@
align-items: center;
gap: 10px;
margin-bottom: 18px;
- color: var(--text-strong);
+ color: var(--color-text-strong);
font-size: 20px;
font-weight: 750;
line-height: 1.2;
@@ -125,13 +110,13 @@
width: 6px;
height: 22px;
border-radius: 3px;
- background: #3370ff;
- content: "";
+ background: var(--color-action-primary);
+ content: '';
}
.share-image-section--group {
margin-top: 30px;
- border-top: 1px solid var(--border);
+ border-top: 1px solid var(--color-border-default);
padding-top: 28px;
}
@@ -141,12 +126,12 @@
justify-content: space-between;
gap: 20px;
padding: 18px 16px 0;
- color: var(--muted);
+ color: var(--color-text-secondary);
}
.share-image-footer__note {
flex: 0 0 auto;
- color: color-mix(in srgb, var(--muted) 88%, var(--text));
+ color: color-mix(in srgb, var(--color-text-secondary) 88%, var(--color-text-primary));
font-size: 11px;
font-weight: 600;
line-height: 1.35;
@@ -159,7 +144,7 @@
min-width: 0;
max-width: 430px;
gap: 9px;
- color: color-mix(in srgb, var(--muted) 72%, var(--text));
+ color: color-mix(in srgb, var(--color-text-secondary) 72%, var(--color-text-primary));
font-size: 10px;
font-weight: 500;
line-height: 1.3;
@@ -184,11 +169,11 @@
width: 1px;
height: 12px;
flex: 0 0 auto;
- background: color-mix(in srgb, var(--muted) 28%, transparent);
+ background: color-mix(in srgb, var(--color-text-secondary) 28%, transparent);
}
.share-image-empty {
- color: var(--muted);
+ color: var(--color-text-secondary);
font-size: 16px;
}
@@ -210,7 +195,7 @@
.share-image-document .chat-bubble,
.share-image-document .chat-text,
.share-image-document .chat-markdown {
- color: var(--chat-text);
+ color: var(--color-text-primary);
}
.share-image-document .chat-markdown pre,
@@ -265,7 +250,7 @@
gap: 7px;
max-width: 100%;
margin-bottom: 5px;
- color: var(--muted);
+ color: var(--color-text-secondary);
font-size: 13px;
line-height: 1.4;
}
@@ -275,12 +260,12 @@
}
.share-image-group-message__member {
- color: var(--text-strong);
+ color: var(--color-text-strong);
font-weight: 700;
}
.share-image-group-message__time {
- color: var(--muted);
+ color: var(--color-text-secondary);
font-size: 12px;
font-weight: 500;
}
@@ -292,13 +277,13 @@
border-radius: 0;
background: transparent;
padding: 0;
- color: var(--text);
+ color: var(--color-text-primary);
}
.share-image-group-message.is-user .share-image-group-message__bubble {
border-color: transparent;
border-radius: 8px;
- background: var(--accent-subtle);
+ background: var(--color-action-primary-subtle);
padding: 8px 12px;
}
@@ -309,9 +294,9 @@
margin-right: 6px;
margin-bottom: 4px;
border-radius: 999px;
- background: rgba(51, 112, 255, 0.11);
+ background: var(--color-action-primary-subtle);
padding: 2px 8px;
- color: #2458cc;
+ color: var(--color-text-link);
font-size: 13px;
}
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index c0cabb5fa5..ff11d47ae5 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -960,10 +960,181 @@
"autoManaged": "Auto-managed",
"autoManagedHint": "This task is auto-created/deleted by the proactive recommendation toggle (Settings → Proactive Recommendation). Only the cron expression and timezone can be edited here; other fields (name/status/description/offset/channel) are read-only. To remove it, turn off the toggle in Settings.",
"autoManagedToggleDisabled": "The toggle of an auto-managed task is controlled by Settings → Proactive Recommendation and cannot be switched here.",
+ "pageTitle": "Scheduled Tasks",
+ "pageSubtitle": "Configure automated tasks that Jiuwen runs on schedule.",
+ "actions": {
+ "confirm": "Confirm"
+ },
+ "createMenu": {
+ "trigger": "Create",
+ "manual": "Create manually",
+ "viaChat": "Create via chat",
+ "viaChatPrompt": "Let's set up a scheduled task together. First, explain how scheduled tasks work in JiuwenSwarm. Then ask me what I'd like to schedule and when it should run."
+ },
+ "stats": {
+ "total": "Total tasks ({{count}})"
+ },
+ "tabs": {
+ "list": "Tasks",
+ "template": "Templates",
+ "history": "Run History"
+ },
+ "search": {
+ "placeholder": "Search"
+ },
+ "table": {
+ "name": "Name",
+ "project": "Project",
+ "schedule": "Scheduled",
+ "status": "Status",
+ "timezone": "Timezone",
+ "channel": "Channel",
+ "actions": "Actions",
+ "noProject": "–",
+ "runNow": "Run now",
+ "stop": "Stop",
+ "edit": "Edit",
+ "more": "More",
+ "history": "Run history",
+ "triggeredSessions": "Triggered sessions",
+ "noTriggeredSessions": "No trigger records"
+ },
+ "empty": {
+ "createButton": "Create scheduled task",
+ "templateSectionTitle": "Templates",
+ "templateMore": "More"
+ },
+ "history": {
+ "comingSoon": "Coming soon"
+ },
+ "confirm": {
+ "deleteTitle": "Delete",
+ "deleteMessage": "Delete task \"{{name}}\"?",
+ "stopTitle": "Stop",
+ "stopMessage": "Stop task \"{{name}}\"?",
+ "runNowTitle": "Run now",
+ "runNowMessage": "Run task \"{{name}}\" now?"
+ },
+ "drawer": {
+ "titleCreate": "Create scheduled task",
+ "titleEdit": "Edit",
+ "titleTemplate": "Create from template",
+ "switchToManual": "Create manually",
+ "switchToTemplate": "Create from template",
+ "fieldName": "Task name",
+ "fieldProject": "Project (optional)",
+ "fieldModel": "Model",
+ "fieldDescription": "Description",
+ "fieldChannel": "Channel",
+ "fieldTimezone": "Timezone",
+ "fieldEffectiveDate": "Effective date (optional)",
+ "effectiveDateComingSoon": "Coming soon — your selection does not take effect yet",
+ "fieldEnabled": "Enabled",
+ "placeholderInput": "Enter",
+ "placeholderSelect": "Select",
+ "placeholderEffectiveDate": "Select effective date",
+ "missingFieldsHint": "Still needed: {{fields}}"
+ },
+ "schedule": {
+ "title": "Schedule",
+ "help": "Choose how often this task runs",
+ "modePeriod": "Recurring",
+ "modeInterval": "Interval",
+ "modeOnce": "Once",
+ "modeCronExpr": "Cron expression",
+ "cronExprPlaceholder": "e.g. 0 0 9 * * ? *",
+ "cronExprHelp": "7-field Quartz: second minute hour day month weekday year",
+ "daily": "Daily",
+ "weekly": "Weekly",
+ "monthly": "Monthly",
+ "yearly": "Yearly",
+ "selectTime": "Select time",
+ "selectMonth": "Select month",
+ "selectDay": "Select day",
+ "every": "Every",
+ "everyHoursPlaceholder": "Hours",
+ "hoursUnit": "hours",
+ "dayOption": "{{day}}",
+ "monthOption": "{{month}}",
+ "lastDayOfMonth": "Last day of month",
+ "listSeparator": ", ",
+ "weekday": {
+ "mon": "Mon",
+ "tue": "Tue",
+ "wed": "Wed",
+ "thu": "Thu",
+ "fri": "Fri",
+ "sat": "Sat",
+ "sun": "Sun"
+ },
+ "summary": {
+ "daily": "Daily at {{time}}",
+ "weekly": "Weekly on {{days}} at {{time}}",
+ "monthly": "Monthly on {{day}} at {{time}}",
+ "monthlyWeekday": "Monthly, {{weekOfMonth}}, {{days}} at {{time}}",
+ "yearly": "Yearly on {{month}}/{{day}} at {{time}}",
+ "interval": "Every {{n}}h",
+ "intervalWithWeekdays": "Every {{n}}h ({{days}})",
+ "once": "{{date}} {{time}}",
+ "lastDay": "the last day"
+ },
+ "monthlySubMode": {
+ "date": "By date",
+ "week": "By week"
+ },
+ "weekOfMonth": {
+ "1": "week 1",
+ "2": "week 2",
+ "3": "week 3",
+ "4": "week 4",
+ "last": "last week"
+ }
+ },
+ "modelPicker": {
+ "configured": "Configured",
+ "empty": "No models available yet, add one in the config panel first"
+ },
+ "timePicker": {
+ "hour": "Hr",
+ "minute": "Min"
+ },
+ "datePicker": {
+ "prevYear": "Previous year",
+ "prevMonth": "Previous month",
+ "nextMonth": "Next month",
+ "nextYear": "Next year",
+ "yearMonthHeader": "{{month}}/{{year}}",
+ "monthItem": "{{month}}",
+ "weekday": {
+ "sun": "Su",
+ "mon": "Mo",
+ "tue": "Tu",
+ "wed": "We",
+ "thu": "Th",
+ "fri": "Fr",
+ "sat": "Sa"
+ }
+ },
+ "template": {
+ "trend": {
+ "title": "Daily industry news",
+ "description": "Every day at 8am, send me the latest industry news for [your industry, e.g. customer service / finance / new energy], organized into a structured document."
+ },
+ "newspaper": {
+ "title": "Market sentiment tracking",
+ "description": "Every day at noon, search and summarize the latest news and sentiment about [a company or product] from the past 24 hours"
+ },
+ "briefcase": {
+ "title": "Weekly work report",
+ "description": "Every Friday at 6pm, generate my weekly report based on this week's chats, docs and sheets, including task progress and next week's plan, delivered as a document."
+ }
+ },
"status": {
"enabled": "Enabled",
"disabled": "Disabled",
- "expired": "Expired"
+ "expired": "Expired",
+ "running": "Running",
+ "paused": "Paused"
},
"columns": {
"name": "Task Name",
@@ -1024,7 +1195,7 @@
"cronHourStep": "Hour step must divide 24",
"cronDay": "Invalid day field (1-31, supports * ? - ,)",
"cronMonth": "Invalid month field (1-12, supports * - ,)",
- "cronWeek": "Invalid dow field (1-7, supports * ? - ,, 1=SUN)",
+ "cronWeek": "Invalid dow field (0-6, supports * ? - ,, 0=Sun, 1=Mon...6=Sat)",
"cronYear": "Invalid year field (1970-2099 or *)",
"timezoneRequired": "Time zone is required",
"targetRequired": "Target channel is required",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 9dff225a1d..3e9e2dbe7a 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -960,10 +960,181 @@
"autoManaged": "自动维护",
"autoManagedHint": "此任务由主动推荐开关自动创建/删除;开关在设置→主动推荐。仅 Cron 表达式与时区可在此面板编辑,其余字段(名称/状态/描述/偏移/频道)不可改;删除请到设置关闭开关。",
"autoManagedToggleDisabled": "自动维护任务的开关由设置→主动推荐控制,不可在此切换。",
+ "pageTitle": "定时任务",
+ "pageSubtitle": "配置和管理自动化任务,Jiuwen 将按计划执行。",
+ "actions": {
+ "confirm": "确定"
+ },
+ "createMenu": {
+ "trigger": "创建",
+ "manual": "手动创建",
+ "viaChat": "通过聊天创建",
+ "viaChatPrompt": "我们一起来设置一个定时任务吧。首先,说明定时任务在 JiuwenSwarm 中的工作方式。然后询问我需要安排什么,以及应该在什么时候运行。"
+ },
+ "stats": {
+ "total": "任务总数({{count}})"
+ },
+ "tabs": {
+ "list": "任务列表",
+ "template": "任务模板",
+ "history": "执行历史"
+ },
+ "search": {
+ "placeholder": "请输入搜索内容"
+ },
+ "table": {
+ "name": "名称",
+ "project": "项目",
+ "schedule": "计划于",
+ "status": "运行状态",
+ "timezone": "时区",
+ "channel": "推送频道",
+ "actions": "操作",
+ "noProject": "–",
+ "runNow": "立即执行",
+ "stop": "停止",
+ "edit": "编辑",
+ "more": "更多",
+ "history": "运行历史",
+ "triggeredSessions": "触发的会话",
+ "noTriggeredSessions": "暂无触发记录"
+ },
+ "empty": {
+ "createButton": "创建定时任务",
+ "templateSectionTitle": "任务模板",
+ "templateMore": "更多"
+ },
+ "history": {
+ "comingSoon": "该功能即将上线"
+ },
+ "confirm": {
+ "deleteTitle": "删除",
+ "deleteMessage": "确定要删除自动化任务\"{{name}}\"吗?",
+ "stopTitle": "停止",
+ "stopMessage": "确定要停止自动化任务\"{{name}}\"吗?",
+ "runNowTitle": "立即执行",
+ "runNowMessage": "确定要立即执行任务\"{{name}}\"吗?"
+ },
+ "drawer": {
+ "titleCreate": "创建定时任务",
+ "titleEdit": "编辑",
+ "titleTemplate": "从模板创建",
+ "switchToManual": "手动创建",
+ "switchToTemplate": "从模板创建",
+ "fieldName": "任务名称",
+ "fieldProject": "项目(可选)",
+ "fieldModel": "模型",
+ "fieldDescription": "描述",
+ "fieldChannel": "推送频道",
+ "fieldTimezone": "时区",
+ "fieldEffectiveDate": "生效周期(可选)",
+ "effectiveDateComingSoon": "该功能即将上线,当前选择暂不影响任务生效",
+ "fieldEnabled": "启用",
+ "placeholderInput": "请输入",
+ "placeholderSelect": "请选择",
+ "placeholderEffectiveDate": "请选择生效日期",
+ "missingFieldsHint": "还需要填写:{{fields}}"
+ },
+ "schedule": {
+ "title": "执行计划",
+ "help": "选择任务的执行频率",
+ "modePeriod": "周期",
+ "modeInterval": "按间隔",
+ "modeOnce": "单次",
+ "modeCronExpr": "Cron表达式",
+ "cronExprPlaceholder": "请输入 Cron 表达式,如 0 0 9 * * ? *",
+ "cronExprHelp": "7段式(Quartz):秒 分 时 日 月 周 年",
+ "daily": "每天",
+ "weekly": "每周",
+ "monthly": "每月",
+ "yearly": "每年",
+ "selectTime": "请选择时间",
+ "selectMonth": "请选择月份",
+ "selectDay": "请选择日期",
+ "every": "每",
+ "everyHoursPlaceholder": "小时数",
+ "hoursUnit": "小时",
+ "dayOption": "{{day}}日",
+ "monthOption": "{{month}}月",
+ "lastDayOfMonth": "月末最后一天",
+ "listSeparator": "、",
+ "weekday": {
+ "mon": "一",
+ "tue": "二",
+ "wed": "三",
+ "thu": "四",
+ "fri": "五",
+ "sat": "六",
+ "sun": "日"
+ },
+ "summary": {
+ "daily": "每天 {{time}}",
+ "weekly": "每周{{days}} {{time}}",
+ "monthly": "每月{{day}} {{time}}",
+ "monthlyWeekday": "每月{{weekOfMonth}} 周{{days}} {{time}}",
+ "yearly": "每年{{month}}月{{day}}日 {{time}}",
+ "interval": "每{{n}}小时",
+ "intervalWithWeekdays": "每{{n}}小时({{days}})",
+ "once": "{{date}} {{time}}",
+ "lastDay": "月末"
+ },
+ "monthlySubMode": {
+ "date": "按日期",
+ "week": "按星期"
+ },
+ "weekOfMonth": {
+ "1": "第一周",
+ "2": "第二周",
+ "3": "第三周",
+ "4": "第四周",
+ "last": "最后一周"
+ }
+ },
+ "modelPicker": {
+ "configured": "已配置",
+ "empty": "暂无可用模型,请先在配置面板添加模型"
+ },
+ "timePicker": {
+ "hour": "时",
+ "minute": "分"
+ },
+ "datePicker": {
+ "prevYear": "上一年",
+ "prevMonth": "上一月",
+ "nextMonth": "下一月",
+ "nextYear": "下一年",
+ "yearMonthHeader": "{{year}}年 {{month}}月",
+ "monthItem": "{{month}}月",
+ "weekday": {
+ "sun": "日",
+ "mon": "一",
+ "tue": "二",
+ "wed": "三",
+ "thu": "四",
+ "fri": "五",
+ "sat": "六"
+ }
+ },
+ "template": {
+ "trend": {
+ "title": "每日行业资讯",
+ "description": "每天早上8点,给我推送当天【你所在行业,例如:人工客服/金融/新能源】点最新行业资讯动态,整理成结构化文档发出。"
+ },
+ "newspaper": {
+ "title": "市场舆情追踪",
+ "description": "每天中午12点,帮我搜索并汇总竞争对手【某公司或某某产品】过去24小时在全网点最新动态和舆情报道"
+ },
+ "briefcase": {
+ "title": "工作周报",
+ "description": "每周五下午6点,帮我根据本周聊天、文档、表格,生成我的周报,任务进度,下周事项工作安排,并且以文档形式发出。"
+ }
+ },
"status": {
"enabled": "启用",
"disabled": "禁用",
- "expired": "过期"
+ "expired": "过期",
+ "running": "运行中",
+ "paused": "已暂停"
},
"columns": {
"name": "任务名称",
@@ -1024,7 +1195,7 @@
"cronHourStep": "小时步长需能被24整除",
"cronDay": "日字段错误(取值 1-31,支持 * ? - ,)",
"cronMonth": "月字段错误(取值 1-12,支持 * - ,)",
- "cronWeek": "周字段错误(取值 1-7,支持 * ? - ,,1=SUN)",
+ "cronWeek": "周字段错误(取值 0-6,支持 * ? - ,,0=周日、1=周一...6=周六)",
"cronYear": "年份字段错误(取值 1970-2099 或 *)",
"timezoneRequired": "时区不能为空",
"targetRequired": "推送频道不能为空",
diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.css b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.css
index a31f9b7da6..afd8c37144 100644
--- a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.css
+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.css
@@ -63,6 +63,15 @@
outline-offset: 2px;
}
+/* 选中态沿用 .conversation-list-item.is-active 的配色约定 */
+.conversation-sidebar__new.is-active {
+ background: var(--color-sidebar-nav-active);
+}
+
+.conversation-sidebar__new.is-active:hover {
+ background: var(--color-sidebar-nav-active-hover);
+}
+
.conversation-sidebar__body {
min-height: 0;
flex: 1 1 auto;
diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx
index f1b017db41..b48eefda31 100644
--- a/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/sidebar/ConversationSidebar.tsx
@@ -53,6 +53,8 @@ const RELATIVE_TIME_REFRESH_MS = 60_000;
export type NewConversationOptions = {
preserveProject?: boolean;
project?: Pick<ProjectInfo, 'project_id' | 'project_dir'>;
+ /** 进入新对话时预填到输入框的文本(例如"通过聊天创建定时任务"引导语),见 App.tsx enterNewConversation */
+ initialInputValue?: string;
};
function isDefaultProject(project: ProjectInfo): boolean {
@@ -64,6 +66,10 @@ interface ConversationSidebarProps {
onNew: (options?: NewConversationOptions) => void;
onSelect: (session: Session) => void;
onDelete: (session: Session) => void;
+ /** 跳转到"定时任务"主面板;该入口原来在最左侧图标栏,现移到工作小窗口的"新建任务"下方 */
+ onOpenCron: () => void;
+ /** 当前是否正停留在定时任务面板,用于给下面这个入口按钮加选中态 */
+ isCronActive: boolean;
}
interface ConversationListItemProps {
@@ -586,6 +592,8 @@ export function ConversationSidebar({
onNew,
onSelect,
onDelete,
+ onOpenCron,
+ isCronActive,
}: ConversationSidebarProps) {
const { t } = useTranslation();
const runtimes = useChatStore((state) => state.runtimes);
@@ -1035,6 +1043,14 @@ export function ConversationSidebar({
<NewTaskIcon aria-hidden />
<span>{t('multiSession.newConversation')}</span>
</button>
+ <button
+ type="button"
+ className={`conversation-sidebar__new${isCronActive ? ' is-active' : ''}`}
+ onClick={onOpenCron}
+ >
+ <CronIcon aria-hidden />
+ <span>{t('nav.cron')}</span>
+ </button>
</div>
<div className="conversation-sidebar__body">
{hasPinnedSection ? (
diff --git a/jiuwenswarm/channels/web/frontend/src/styles/themes/default/light.css b/jiuwenswarm/channels/web/frontend/src/styles/themes/default/light.css
index ec7e42c8c1..7b55adc95a 100644
--- a/jiuwenswarm/channels/web/frontend/src/styles/themes/default/light.css
+++ b/jiuwenswarm/channels/web/frontend/src/styles/themes/default/light.css
@@ -74,6 +74,7 @@
/* Feature accents whose identity is stable across color modes */
--color-chat-accent: #1476ff;
--color-chat-accent-subtle: #deecff;
+ --color-cron-running: var(--color-feedback-success);
/* Utility color roles */
--color-focus: rgba(37, 99, 235, 0.2);
@@ -212,6 +213,14 @@
--color-control-emphasis-hover-strong: #333333;
--color-config-team-icon: rgb(217, 70, 239);
--color-channel-backdrop: rgba(0, 0, 0, 0.45);
+ --color-cron-action: #141414;
+ --color-cron-action-hover: #000000;
+ --color-cron-action-foreground: #ffffff;
+ --color-cron-action-link: #1476ff;
+ --color-cron-auto-managed-surface: #e0f2fe;
+ --color-cron-auto-managed-text: #0369a1;
+ --color-overlay-cron-dialog: rgba(0, 0, 0, 0.4);
+ --color-overlay-cron-drawer: rgba(0, 0, 0, 0.3);
color-scheme: light;
}
diff --git a/jiuwenswarm/channels/web/frontend/src/types/cron.ts b/jiuwenswarm/channels/web/frontend/src/types/cron.ts
new file mode 100644
index 0000000000..64d5048f0f
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/types/cron.ts
@@ -0,0 +1,73 @@
+/** 后端 cron.job.* 系列 RPC 实际收发的字段,对齐 jiuwenswarm/gateway/cron/models.py 的 CronJob.to_dict() */
+export interface CronJobDTO {
+ id: string;
+ name: string;
+ enabled: boolean;
+ expired: boolean;
+ cron_expr: string;
+ timezone: string;
+ wake_offset_seconds: number;
+ description: string;
+ targets: string;
+ created_at: number | null;
+ updated_at: number | null;
+ session_id?: string;
+ chat_type?: string;
+ mode?: string;
+ delete_after_run?: boolean;
+ timeout_seconds?: number;
+ project_id: string;
+ last_session_id?: string;
+ model_name?: string;
+}
+
+/** create/update 请求体;project_dir 而非 project_id,见 CronController.create_job */
+export interface CronJobUpsertParams {
+ name: string;
+ cron_expr: string;
+ timezone: string;
+ enabled: boolean;
+ description: string;
+ targets: string;
+ wake_offset_seconds?: number;
+ model_name?: string;
+ project_dir?: string;
+ mode?: string;
+}
+
+/** UI 层展示用结构,来自 CronJobDTO 派生(见 cronJobToUI) */
+export interface CronTaskUI {
+ id: string;
+ name: string;
+ projectId: string;
+ projectName: string | null;
+ description: string;
+ modelName: string | null;
+ cronExpr: string;
+ timezone: string;
+ enabled: boolean;
+ expired: boolean;
+ deliveryChannel: string;
+}
+
+export interface CronTemplateUI {
+ id: string;
+ icon: 'trend' | 'newspaper' | 'briefcase';
+ titleKey: string;
+ descriptionKey: string;
+ cronExpr: string;
+}
+
+/** 执行计划编辑器(ScheduleEditor)内部结构化状态,见 _migration/plan.md §2.3.6/§2.3.8 */
+export type CronScheduleKind = 'daily' | 'weekly' | 'monthly' | 'monthlyWeekday' | 'yearly' | 'interval' | 'once';
+
+export interface CronSchedule {
+ kind: CronScheduleKind;
+ time?: string; // HH:mm,daily/weekly/monthly/monthlyWeekday/yearly/once 用
+ weekdays?: number[]; // 0=周日...6=周六(croniter 真实编号),weekly/interval/monthlyWeekday 用
+ day?: number | 'L'; // monthly 用:"每月第几天",或 'L' 表示月末最后一天
+ 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)
+}
diff --git a/jiuwenswarm/channels/web/frontend/tailwind.config.js b/jiuwenswarm/channels/web/frontend/tailwind.config.js
index 3dad03190a..ee1c6d3630 100644
--- a/jiuwenswarm/channels/web/frontend/tailwind.config.js
+++ b/jiuwenswarm/channels/web/frontend/tailwind.config.js
@@ -74,6 +74,19 @@ export default {
subtle: color('--color-feedback-danger-subtle'),
},
info: color('--color-feedback-info'),
+ cron: {
+ running: color('--color-cron-running'),
+ action: color('--color-cron-action'),
+ 'action-hover': color('--color-cron-action-hover'),
+ 'action-foreground': color('--color-cron-action-foreground'),
+ 'action-link': color('--color-cron-action-link'),
+ 'auto-managed-surface': color('--color-cron-auto-managed-surface'),
+ 'auto-managed-text': color('--color-cron-auto-managed-text'),
+ },
+ overlay: {
+ 'cron-dialog': color('--color-overlay-cron-dialog'),
+ 'cron-drawer': color('--color-overlay-cron-drawer'),
+ },
muted: {
DEFAULT: color('--color-text-secondary'),
foreground: color('--color-text-secondary'),
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.py
index 758105e275..adf9e1ecdf 100644
--- a/jiuwenswarm/gateway/cron/scheduler.py
+++ b/jiuwenswarm/gateway/cron/scheduler.py
@@ -435,7 +435,20 @@ class CronSchedulerService:
else:
logger.warning("[Cron] compute next run failed job=%s: %s", job.id, exc)
continue
- self._schedule_event(wake_dt, "wake", job.id, run_id)
+ # 幂等保护:reload 清空事件队列后重新排入,但同一 run_id
+ # 可能已执行中或已完成(wake_offset 过大时 wake_dt 在过去,
+ # 每次 reload 都会立刻触发)。跳过已活跃 run 的 wake 事件,
+ # 但 push 事件仍需排入——_on_push 内部有 pushed_final 兜底。
+ existing = self._runs.get(run_id)
+ already_active = (
+ existing is not None
+ and existing.status in ("running", "succeeded", "failed")
+ ) or (
+ run_id in self._run_tasks
+ and not self._run_tasks[run_id].done()
+ )
+ if not already_active:
+ self._schedule_event(wake_dt, "wake", job.id, run_id)
self._schedule_event(push_dt, "push", job.id, run_id)
self._sync_store_mtime()
@@ -759,6 +772,20 @@ class CronSchedulerService:
)
self._runs[run_id] = state
+ # 幂等保护:reload 可能对同一 run_id 重复排入 wake 事件。
+ # 如果该 run 已完成(succeeded/failed)或已有结果文本,不再重复执行 agent。
+ if state.status in ("succeeded", "failed"):
+ logger.info(
+ "[Cron] _on_wake skipped: already %s run_id=%s job=%s",
+ state.status, run_id, job.id,
+ )
+ return
+ if state.result_text and state.pushed_final:
+ logger.info(
+ "[Cron] _on_wake skipped: result already pushed run_id=%s job=%s",
+ run_id, job.id,
+ )
+ return
if run_id in self._run_tasks and not self._run_tasks[run_id].done():
return