"use client"; import { type ChangeEvent, useEffect, useMemo, useRef, useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { AlertCircle, BellOff, BellRing, CheckCircle2, Download, Edit3, Eye, Globe, Heart, HeartOff, Loader2, Lock, Pause, Play, Plus, RefreshCw, TagsIcon, Trash2, Upload, X, } from "lucide-react"; import { useSearchParams } from "react-router-dom"; import { useRouteNavigate as useNavigate } from "@/core/route-base"; import { toast } from "sonner"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Textarea } from "@/components/ui/textarea"; import { WorkspaceBody, WorkspaceContainer, WorkspaceHeader, } from "@/components/workspace/workspace-container"; import { CompactShortcutButtons, LayoutModeSwitcher, ThemeSwitcher, } from "@/components/workspace/appearance-controls"; import { TagChipList } from "@/components/workspace/tags/tag-chip"; import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog"; import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar"; import { useAgents } from "@/core/agents"; import { useModels } from "@/core/models/hooks"; import { downloadScheduledTaskRun, type PublishedScheduledTask, type ScheduledTask, type ScheduledTaskExecutionContext, useHtmlPageFavoriteActions, useHtmlPageFavorites, useHtmlTemplates, useScheduledTaskActions, useScheduledTaskDeliveryProfile, useScheduledTaskRuns, useScheduledTasks, usePublishedScheduledTasks, } from "@/core/scheduled-tasks"; import { buildCron, DEFAULT_SCHEDULE_CONFIG, parseCron, ScheduleBuilder, type ScheduleConfig, statusLabel, statusVariant, } from "@/components/workspace/scheduled-tasks/schedule-builder"; import { useTheme } from "@/contexts/ThemeContext"; import { desensitize } from "@/lib/desensitize"; import { cn } from "@/lib/utils"; /** 成功 toast:仅暗色模式,浅色走 Sonner 默认 */ const successToastDarkOptions = { classNames: { toast: "!rounded-[2px] !border !border-[#106455] !bg-[#052934] !text-[#FFFFFF] shadow-md", title: "!text-[#FFFFFF]", description: "!text-[#FFFFFF]", }, icon: , } as const; /** 失败 toast:仅暗色模式,浅色走 Sonner 默认 */ const errorToastDarkOptions = { classNames: { toast: "!rounded-[2px] !border !border-[#7F1A2A] !bg-[#311629] !text-[#FFFFFF] shadow-md", title: "!text-[#FFFFFF]", description: "!text-[#FFFFFF]", }, icon: , } as const; function formatDate(value?: string | null) { return value ? new Date(value).toLocaleString() : "暂无"; } /** Render a creator-like identifier without the email domain part. */ function displayUsername(value?: string | null): string { const raw = (value ?? "").trim(); if (!raw) return ""; const at = raw.indexOf("@"); return at === -1 ? raw : raw.slice(0, at); } /** 内置「模板数据转换器」agent 的稳定 id(后端 seed)。选中它时表单露出 HTML 模板下拉。 */ const TEMPLATE_BUILDER_AGENT_ID = "template-json-builder"; const emptyForm = { name: "", description: "", schedule: "", timezone: "Asia/Shanghai", prompt: "", execution_agent_name: "", // 模板填充模式:选中「模板数据转换器」后要把源 JSON 填进哪个 HTML 模板。 template_id: "", // Two independent output switches (may both be on): require a Markdown file // and/or render an HTML page. The form no longer splits into "普通任务 / HTML // 页面" tabs. require_markdown: false, require_html: false, // HTML-only extra fields, shown when ``require_html`` is on. The main // ``prompt`` above doubles as the page requirement, so there is no separate // page-prompt field. ``html_model_name`` empty means "use the first available // model" — never a hardcoded GLM-5. html_negative_prompt: "", html_reference_favorite_id: "", html_model_name: "", // 参考选了内置模板(tpl:)时的「数据抽取」开关:默认开启(检索抽取+抽不到回退 // 模板原数据),仅可转换模板生效;显式关闭=直接用模板默认数据。 html_template_extract: true, }; /** 覆盖 Textarea 默认 field-sizing-content,避免输入过多时撑破弹窗 */ const SCHEDULED_TASK_TEXTAREA_CLASS = "field-sizing-fixed resize-y overflow-y-auto"; const DESCRIPTION_TEXTAREA_ROWS = 4; const PROMPT_TEXTAREA_ROWS = 10; export default function ScheduledTasksPage({ compactChrome = false, }: { compactChrome?: boolean; }) { const queryClient = useQueryClient(); const { theme } = useTheme(); const darkToastOpts = theme === "dark" ? { success: successToastDarkOptions, error: errorToastDarkOptions } : { success: undefined, error: undefined }; const navigate = useNavigate(); const [searchParams] = useSearchParams(); // When returning from a run-detail page the task id is carried in ?task=, // so the list re-selects (and scrolls to) the task the user was viewing. const initialTaskId = searchParams.get("task"); const [search, setSearch] = useState(""); const [tagIds, setTagIds] = useState([]); // Plaza (广场) name search is resolved client-side over the fetched published // list, kept separate from the server-side 我的任务 search above. const [plazaSearch, setPlazaSearch] = useState(""); // Publisher (创建者) filter for the 我的任务 tab — click a task's 创建者 to keep // only that creator's tasks. {id} is creator_user_id; {label} the display name. const [publisher, setPublisher] = useState<{ id: string; label: string } | null>( null, ); // Name + tag filtering is resolved server-side via the /api/scheduled-tasks query. const { data: tasks = [], isLoading, isFetching } = useScheduledTasks({ search, tagIds }); const { data: deliveryProfile } = useScheduledTaskDeliveryProfile(); const { agents } = useAgents(); const actions = useScheduledTaskActions(); const [activeTab, setActiveTab] = useState<"mine" | "plaza">("mine"); const { data: published = [], isLoading: publishedLoading } = usePublishedScheduledTasks(activeTab === "plaza"); const [selectedTaskId, setSelectedTaskId] = useState(initialTaskId); // One-shot scroll target: scroll the task into view after a back-navigation. const pendingScrollRef = useRef(initialTaskId); const [elementUserId, setElementUserId] = useState(""); const [editing, setEditing] = useState(null); const [creating, setCreating] = useState(false); const [form, setForm] = useState(emptyForm); // 模板填充模式的 .json 上传:读入文件文本填进 prompt 框(不改后端契约)。 const jsonUploadRef = useRef(null); const handleJsonUpload = async (event: ChangeEvent) => { const file = event.target.files?.[0]; event.target.value = ""; // 允许重复上传同名文件 if (!file) return; try { const text = await file.text(); // 校验是 JSON,给即时反馈;非法也照样填入让用户修正。 try { JSON.parse(text); } catch { toast.error("文件不是合法 JSON,已填入文本框请检查", darkToastOpts.error); } setForm((value) => ({ ...value, prompt: text })); } catch { toast.error("读取文件失败", darkToastOpts.error); } }; const dialogOpen = creating || !!editing; const { data: htmlFavorites = [] } = useHtmlPageFavorites(dialogOpen); const htmlFavoriteActions = useHtmlPageFavoriteActions(); const { models: availableModels } = useModels({ enabled: dialogOpen }); const handleDeleteFavorite = async (favoriteId: string) => { try { await htmlFavoriteActions.remove.mutateAsync(favoriteId); // Clear the selection if the removed favorite was the chosen reference. setForm((value) => value.html_reference_favorite_id === favoriteId ? { ...value, html_reference_favorite_id: "" } : value, ); toast.success("收藏已删除", darkToastOpts.success); } catch (error) { toast.error(error instanceof Error ? error.message : "删除失败", darkToastOpts.error); } }; const [scheduleConfig, setScheduleConfig] = useState(DEFAULT_SCHEDULE_CONFIG); const [runsTimeFilter, setRunsTimeFilter] = useState<"all" | "today" | "7d" | "30d">("all"); const [subscribeTarget, setSubscribeTarget] = useState(null); const [subscribeNotify, setSubscribeNotify] = useState(false); const [tagPickerTask, setTagPickerTask] = useState(null); const sortedTasks = useMemo( () => [...tasks].sort((a, b) => { // Newest task first. Fall back to next_run_at so tasks that lack a // created_at (older rows / subscribed tasks) still order consistently. const aKey = a.created_at ?? a.next_run_at ?? ""; const bKey = b.created_at ?? b.next_run_at ?? ""; return String(bKey).localeCompare(String(aKey)); }), [tasks], ); // The rendered 我的任务 list, optionally narrowed to one creator. Selection // logic still runs against the full sortedTasks so the detail panel keeps // working even when the picked task is from a filtered-out creator. const visibleTasks = useMemo( () => publisher ? sortedTasks.filter((task) => task.creator_user_id === publisher.id) : sortedTasks, [sortedTasks, publisher], ); // Plaza search: filter the fetched published list client-side. Match against // both the raw and desensitized forms so typing what's shown on screen (the // desensitized name) and the underlying text both hit. const visiblePublished = useMemo(() => { const q = plazaSearch.trim().toLowerCase(); if (!q) return published; return published.filter((item) => [ item.name, desensitize(item.name), item.prompt_summary, desensitize(item.prompt_summary ?? ""), item.schedule_text, displayUsername(item.creator_email), ].some((field) => (field ?? "").toLowerCase().includes(q)), ); }, [published, plazaSearch]); const selectedTask = sortedTasks.find((task) => task.task_id === selectedTaskId) ?? null; const selectedTaskCanEditRuns = !!selectedTask && selectedTask.role !== "subscriber"; const { data: runs = [], isLoading: runsLoading } = useScheduledTaskRuns(selectedTaskId); const filteredRuns = useMemo(() => { if (runsTimeFilter === "all") return runs; const now = Date.now(); const ms = runsTimeFilter === "today" ? Date.now() - new Date().setHours(0, 0, 0, 0) : runsTimeFilter === "7d" ? 7 * 86400_000 : 30 * 86400_000; const cutoff = now - ms; return runs.filter((r) => r.scheduled_for && new Date(r.scheduled_for).getTime() >= cutoff); }, [runs, runsTimeFilter]); useEffect(() => { setElementUserId(deliveryProfile?.element_user_id ?? ""); }, [deliveryProfile?.element_user_id]); useEffect(() => { if (!selectedTaskId && sortedTasks[0]) { setSelectedTaskId(sortedTasks[0].task_id); } if (selectedTaskId && !sortedTasks.some((task) => task.task_id === selectedTaskId)) { setSelectedTaskId(sortedTasks[0]?.task_id ?? null); } }, [selectedTaskId, sortedTasks]); const openCreate = () => { setCreating(true); setEditing(null); setForm(emptyForm); setScheduleConfig(DEFAULT_SCHEDULE_CONFIG); }; const openEdit = (task: ScheduledTask) => { setCreating(false); setEditing(task); const html = task.execution_context?.html_config ?? {}; setForm({ name: task.name, description: task.description ?? "", schedule: task.schedule_text, timezone: task.timezone, // The main prompt doubles as the HTML page requirement; legacy HTML tasks // stored that under ``html_config.page_prompt``, so prefer it on edit. prompt: html.page_prompt || task.prompt, execution_agent_name: task.execution_agent_name ?? "", template_id: task.execution_context?.template_config?.template_id ?? "", require_markdown: !!task.execution_context?.require_markdown, // Backward compatible: legacy HTML tasks only carry ``task_kind``. require_html: !!task.execution_context?.require_html || task.execution_context?.task_kind === "html_page", html_negative_prompt: html.negative_prompt ?? "", html_reference_favorite_id: html.reference_favorite_id ?? "", html_model_name: html.model_name ?? "", // 与后端缺省一致:未存该键(老任务)视为开启,仅显式 false 才关闭。 html_template_extract: html.template_extract !== false, }); // Prefer the canonical cron_expr over the user-typed schedule_text: the // latter may be natural language ("每天9点") that parseCron can't read, // which is what made the dialog default back to "每天9点 → 每小时0分". setScheduleConfig( parseCron(task.cron_expr) ?? parseCron(task.schedule_text) ?? DEFAULT_SCHEDULE_CONFIG, ); }; const closeDialog = () => { setCreating(false); setEditing(null); setForm(emptyForm); setScheduleConfig(DEFAULT_SCHEDULE_CONFIG); }; // 模板填充模式:选中内置「模板数据转换器」agent。此时表单露出 HTML 模板下拉, // 并隐藏「必须生成 HTML/Markdown」开关(本模式必产出 HTML)。 const isTemplateAgent = form.execution_agent_name === TEMPLATE_BUILDER_AGENT_ID; // 模板清单:模板填充模式需要(选模板),require_html 模式也需要(作为「参考收藏页面」选项)。 const { data: htmlTemplates = [] } = useHtmlTemplates( isTemplateAgent || form.require_html, ); const selectedTemplate = htmlTemplates.find((t) => t.id === form.template_id); // 「参考收藏页面」选中的内置模板(require_html 模式,值形如 tpl:)。 const selectedTplRef = htmlTemplates.find( (t) => `tpl:${t.id}` === form.html_reference_favorite_id, ); // 选中的模板是「只展示」型(convertible===false)时,不需要源 JSON,隐藏上传/输入。 const templateDisplayOnly = isTemplateAgent && selectedTemplate?.convertible === false; const isHtmlTask = !isTemplateAgent && form.require_html; // The model actually shown/used: the user's choice, else the first configured // model. Never a hardcoded GLM-5 — it follows config order and the selection. const effectiveHtmlModel = form.html_model_name || availableModels[0]?.name || ""; // Build the execution_context for the current form. ``require_html`` and // ``require_markdown`` are independent toggles (both may be on). HTML tasks // persist their extra config under ``html_config`` and reuse the main prompt // as the page requirement; ``task_kind`` is kept in sync only for backward // compatibility with older readers. const buildExecutionContext = (): ScheduledTaskExecutionContext => { // 模板填充模式:只带 template_config,后端据此走「转换 JSON → 填充模板」分支。 if (isTemplateAgent && form.template_id) { return { template_config: { template_id: form.template_id }, require_html: false, task_kind: "agent", html_config: undefined, }; } if (!isHtmlTask) { return { require_html: false, task_kind: "agent", html_config: undefined, template_config: undefined, }; } return { require_html: true, task_kind: "html_page", html_config: { // The main prompt doubles as the page requirement. page_prompt: form.prompt.trim() || null, negative_prompt: form.html_negative_prompt.trim() || null, reference_favorite_id: form.html_reference_favorite_id || null, // Send the user's selection; fall back to the first configured model, // else null (backend then uses the system default). No hardcoded GLM-5. model_name: form.html_model_name.trim() || availableModels[0]?.name || null, // 仅当参考是内置模板(tpl:)时有意义:关闭=用模板默认数据,开启=检索抽取。 template_extract: form.html_reference_favorite_id.startsWith("tpl:") ? form.html_template_extract : false, }, }; }; const saveTask = async () => { try { const cronSchedule = buildCron(scheduleConfig); const executionContext = buildExecutionContext(); // The (non-null) prompt column always needs something useful; HTML tasks // may leave it sparse, so fall back to a generic instruction. const effectivePrompt = form.prompt.trim() || (isHtmlTask ? "生成 HTML 页面" : form.prompt); if (creating) { const task = await actions.create.mutateAsync({ name: form.name || "定时任务", description: form.description.trim() || null, schedule: cronSchedule, timezone: form.timezone || "Asia/Shanghai", prompt: effectivePrompt, execution_agent_name: form.execution_agent_name || null, require_markdown: form.require_markdown, execution_context: executionContext, }); setSelectedTaskId(task.task_id); toast.success("任务已创建", darkToastOpts.success); } else if (editing) { await actions.update.mutateAsync({ taskId: editing.task_id, data: { name: form.name, description: form.description.trim() || null, schedule: cronSchedule, timezone: form.timezone, prompt: effectivePrompt, execution_agent_name: form.execution_agent_name || null, require_markdown: form.require_markdown, execution_context: executionContext, }, }); toast.success("任务已更新", darkToastOpts.success); } closeDialog(); } catch (error) { toast.error( error instanceof Error ? error.message : "保存失败", darkToastOpts.error, ); } }; const handleDownload = async (runId: string) => { try { await downloadScheduledTaskRun(runId); } catch (error) { toast.error( error instanceof Error ? error.message : "下载失败", darkToastOpts.error, ); } }; const handleDeleteRun = async (runId: string) => { try { await actions.removeRun.mutateAsync(runId); toast.success("执行记录已删除", darkToastOpts.success); } catch (error) { toast.error( error instanceof Error ? error.message : "删除失败", darkToastOpts.error, ); } }; const handleTriggerTask = async (task: ScheduledTask) => { setSelectedTaskId(task.task_id); setRunsTimeFilter("all"); try { await actions.trigger.mutateAsync(task.task_id); await queryClient.invalidateQueries({ queryKey: ["scheduled-tasks", task.task_id, "runs"], }); await queryClient.invalidateQueries({ queryKey: ["scheduled-tasks", "list"], }); toast.success("已触发执行", darkToastOpts.success); } catch (error) { toast.error( error instanceof Error ? error.message : "触发失败", darkToastOpts.error, ); } }; return ( ) : null } />
定时任务

选择任务后,在右侧查看全部执行记录

setElementUserId(event.target.value)} placeholder="Element 用户 ID,可选" />
setActiveTab(v as typeof activeTab)}> 我的任务 广场 {activeTab === "mine" && ( )} {activeTab === "plaza" && ( )} {activeTab === "mine" && publisher && (
筛选创建者:
)}
{activeTab === "mine" ? (
{isLoading && (
正在加载任务...
)} {!isLoading && visibleTasks.length === 0 && (
{publisher ? `没有「${publisher.label}」创建的任务。` : "还没有定时任务。点击新建创建第一个任务,或去“广场”收藏他人发布的任务。"}
)} {visibleTasks.map((task) => { const isOwner = task.role !== "subscriber"; const isSubscriber = task.role === "subscriber"; const notifyOn = !!task._subscription?.notify_element; const isRunningNow = task.last_status === "running" || task.last_status === "pending"; return (
{(task.tags?.length ?? 0) > 0 && ( )}
{isOwner ? ( <> ) : ( <> )}
); })}
) : (
{publishedLoading && (
正在加载广场任务...
)} {!publishedLoading && visiblePublished.length === 0 && (
{plazaSearch.trim() ? `没有匹配「${plazaSearch.trim()}」的任务。` : "广场上还没有发布的任务。"}
)} {visiblePublished.map((item) => { const subscribed = tasks.some((t) => t.task_id === item.task_id); return (
{desensitize(item.name)}
{desensitize(item.schedule_text ?? "")} · {item.timezone}
{subscribed && ( 已收藏 )}
{item.prompt_summary ? desensitize(item.prompt_summary) : "(无摘要)"}
); })}
)}
执行记录 {selectedTask && ( )}

{selectedTask ? desensitize(selectedTask.name) : "请选择左侧任务"}

{selectedTask && (selectedTask.creator_email || selectedTask.creator_user_id) && (

创建者: {displayUsername(selectedTask.creator_email) || selectedTask.creator_user_id}

)}
{runsLoading && (
正在加载执行记录...
)} {!runsLoading && selectedTask && filteredRuns.length === 0 && (
{runs.length === 0 ? "这个任务还没有执行记录。" : "当前时间范围内没有执行记录。"}
)} {!selectedTask && (
请先选择一个定时任务。
)} {filteredRuns.map((run) => { const runRunning = run.status === "running" || run.status === "pending"; return (
{run.result?.title ? desensitize(run.result.title) : formatDate(run.scheduled_for)}
计划:{formatDate(run.scheduled_for)} · 开始: {formatDate(run.started_at)}
{runRunning && } {statusLabel(run.status)}
{run.error && (
{desensitize(run.error)}
)}
{selectedTaskCanEditRuns && run.can_edit !== false && ( )}
); })}
{ if (!open) { setSubscribeTarget(null); setSubscribeNotify(false); } }} > 收藏到我的任务
{desensitize(subscribeTarget?.name ?? "")}
{desensitize(subscribeTarget?.schedule_text ?? "")} · {subscribeTarget?.timezone}
{subscribeTarget?.prompt_summary ? desensitize(subscribeTarget.prompt_summary) : "(无摘要)"}
同步接收 Element 通知
开启后,每次执行结果将复制一份发送到你设置的 Element 用户。 {!deliveryProfile?.element_user_id && ( 你尚未配置 Element 用户 ID。 )}
!open && closeDialog()}> {creating ? "新建定时任务" : "编辑定时任务"}
setForm((value) => ({ ...value, name: event.target.value })) } placeholder="任务名称" />