"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: false, }; /** 覆盖 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 ?? "", html_template_extract: !!html.template_extract, }); // 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); // 选中的模板是「只展示」型(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,可选" /> { try { await actions.updateDeliveryProfile.mutateAsync({ element_user_id: elementUserId || null, }); toast.success("Element 配置已保存", darkToastOpts.success); } catch (error) { toast.error( error instanceof Error ? error.message : "保存失败", darkToastOpts.error, ); } }} > 保存 setActiveTab(v as typeof activeTab)}> 我的任务 广场 {activeTab === "mine" && ( )} {activeTab === "plaza" && ( )} {activeTab === "mine" && publisher && ( 筛选创建者: setPublisher(null)} className="bg-primary/10 text-primary hover:bg-primary/20 inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-medium transition-colors" title="点击清除创建者筛选" > {publisher.label} )} {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 ( { if (el && pendingScrollRef.current === task.task_id) { pendingScrollRef.current = null; el.scrollIntoView({ block: "center" }); } }} className={cn( "bg-card text-card-foreground rounded-md border p-4 text-left transition-colors hover:bg-accent/60", selectedTaskId === task.task_id && "border-primary bg-accent", )} onClick={() => setSelectedTaskId(task.task_id)} > {desensitize(task.name)} {isRunningNow && ( 正在执行 )} {isSubscriber && ( 收藏 )} {isOwner && task.published && ( 已发布 )} {(task.execution_context?.require_html || task.execution_context?.task_kind === "html_page") && ( HTML 页面 )} {desensitize(task.schedule_text ?? "")} · {task.timezone} {task.enabled ? "启用" : "暂停"} 下次执行:{formatDate(task.next_run_at)} 上次执行:{formatDate(task.last_run_at)} 最近状态:{statusLabel(task.last_status)} {isRunningNow && ( )} {(task.creator_email || task.creator_user_id) && ( // The card itself is a , so this clickable // creator must be a (no nested buttons). { if (!task.creator_user_id) return; event.stopPropagation(); setPublisher({ id: task.creator_user_id, label: displayUsername(task.creator_email) || task.creator_user_id, }); }} className={cn( "block max-w-full truncate text-sm font-medium", task.creator_user_id && "hover:text-primary cursor-pointer transition-colors hover:underline", )} title={ task.creator_user_id ? `点击筛选创建者:${displayUsername(task.creator_email) || task.creator_user_id}` : undefined } > 创建者: {displayUsername(task.creator_email) || task.creator_user_id} )} {(task.tags?.length ?? 0) > 0 && ( )} { event.stopPropagation(); setTagPickerTask(task); }} > {isOwner ? ( <> { event.stopPropagation(); openEdit(task); }} > { event.stopPropagation(); task.enabled ? actions.pause.mutate(task.task_id) : actions.resume.mutate(task.task_id); }} > {task.enabled ? : } { event.stopPropagation(); void handleTriggerTask(task); }} > { event.stopPropagation(); try { if (task.published) { await actions.unpublish.mutateAsync(task.task_id); toast.success( "已取消发布(已订阅者保留)", darkToastOpts.success, ); } else { await actions.publish.mutateAsync(task.task_id); toast.success("已发布到广场", darkToastOpts.success); } } catch (error) { toast.error( error instanceof Error ? error.message : "操作失败", darkToastOpts.error, ); } }} > {task.published ? : } { event.stopPropagation(); actions.remove.mutate(task.task_id); }} > > ) : ( <> { event.stopPropagation(); try { await actions.updateSubscription.mutateAsync({ taskId: task.task_id, notifyElement: !notifyOn, }); toast.success( notifyOn ? "已关闭 Element 通知" : "已开启 Element 通知", darkToastOpts.success, ); } catch (error) { toast.error( error instanceof Error ? error.message : "操作失败", darkToastOpts.error, ); } }} > {notifyOn ? : } {notifyOn ? "通知中" : "未通知"} { event.stopPropagation(); try { await actions.unsubscribe.mutateAsync(task.task_id); toast.success("已取消收藏", darkToastOpts.success); } catch (error) { toast.error( error instanceof Error ? error.message : "操作失败", darkToastOpts.error, ); } }} > 取消收藏 > )} ); })} ) : ( {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) : "(无摘要)"} { setSubscribeTarget(item); setSubscribeNotify(false); }} > {subscribed ? "已收藏" : "收藏到我的任务"} ); })} )} 执行记录 {selectedTask && ( { const url = `${window.location.origin}${window.location.pathname}#/public/scheduled-tasks/${encodeURIComponent(selectedTask.task_id)}`; window.open(url, "_blank", "noopener,noreferrer"); }} > 公开页 )} setRunsTimeFilter(v as typeof runsTimeFilter)}> 全部时间 今天 近 7 天 近 30 天 {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)} )} navigate( `/page/workspace/scheduled/runs/${run.id}?from=mine&task=${encodeURIComponent(run.task_id)}`, ) } > 查看结果 handleDownload(run.id)} disabled={!run.result} > 下载结果 {selectedTaskCanEditRuns && run.can_edit !== false && ( handleDeleteRun(run.id)} > 删除 )} ); })} { 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。 )} { setSubscribeTarget(null); setSubscribeNotify(false); }} > 取消 { if (!subscribeTarget) return; try { await actions.subscribe.mutateAsync({ taskId: subscribeTarget.task_id, notifyElement: subscribeNotify, }); toast.success("已收藏到我的任务", darkToastOpts.success); setSubscribeTarget(null); setSubscribeNotify(false); setActiveTab("mine"); } catch (error) { toast.error( error instanceof Error ? error.message : "收藏失败", darkToastOpts.error, ); } }} > 确认收藏 !open && closeDialog()}> {creating ? "新建定时任务" : "编辑定时任务"} setForm((value) => ({ ...value, name: event.target.value })) } placeholder="任务名称" /> setForm((value) => ({ ...value, description: event.target.value })) } placeholder="任务描述(可选,将显示在公开页标题下方)" /> 执行频率 setForm((value) => ({ ...value, timezone: event.target.value })) } placeholder="时区,例如:Asia/Shanghai" /> setForm((value) => ({ ...value, execution_agent_name: v === "__default__" ? "" : v, })) } > 默认助手(不指定) {agents.map((agent) => ( {desensitize(agent.name)} {agent.description ? ` — ${desensitize(agent.description)}` : ""} ))} {isTemplateAgent && ( HTML 模板 {templateDisplayOnly ? ( <>选择要展示的 HTML 模板。该模板暂为「直接展示已有数据」,执行时将原样输出其现有页面。> ) : ( <> 选择要把源数据填充进去的 HTML 模板。执行时智能体会把下方源 JSON 转换成该模板所需的结构,校验后填充生成可预览的页面。 未提供源 JSON 时,将直接展示该模板的默认数据。 > )} setForm((value) => ({ ...value, template_id: v })) } > {htmlTemplates.map((tpl) => ( {tpl.name} {tpl.description ? ` — ${tpl.description}` : ""} ))} {htmlTemplates.length === 0 && ( 暂无可用模板 )} {templateDisplayOnly ? ( 该模板暂为「直接展示已有数据」,无需填写源 JSON;执行时将原样输出模板的现有页面。 ) : ( jsonUploadRef.current?.click()} > 上传 .json 文件 也可直接在下方粘贴源 JSON(上传会填入下方文本框) )} )} {!templateDisplayOnly && ( setForm((value) => ({ ...value, prompt: event.target.value })) } placeholder={ isTemplateAgent ? "源 JSON 数据(粘贴或上传 .json),将被智能体转换并填充进所选 HTML 模板;留空则展示模板默认数据" : isHtmlTask ? "任务 / 页面生成要求,例如:检索新能源车最新舆情,生成适合领导快速浏览的态势页" : "任务 Prompt" } /> )} {!isTemplateAgent && ( <> 必须生成 Markdown 文件 开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。 setForm((value) => ({ ...value, require_markdown: v })) } /> 必须生成 HTML 页面 开启后会先用智能体检索整理真实数据,再渲染为完整 HTML 页面(可在执行记录中预览)。可与“必须生成 Markdown”同时开启。 setForm((value) => ({ ...value, require_html: v })) } /> > )} {isHtmlTask && ( <> setForm((value) => ({ ...value, html_negative_prompt: event.target.value })) } placeholder="HTML 限制条件(可选),例如:不要使用深色背景,不要出现外部链接脚本" /> 参考收藏页面(可选) setForm((value) => ({ ...value, html_reference_favorite_id: "" })) } className={cn( "rounded px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent/60", !form.html_reference_favorite_id && "bg-accent", )} > 不参考(默认) {/* 内置 HTML 模板作为风格参考:值存为 ``tpl:``,生成时参照其 CSS/版式。 */} {htmlTemplates.map((tpl) => { const refValue = `tpl:${tpl.id}`; const selected = form.html_reference_favorite_id === refValue; return ( setForm((value) => ({ ...value, html_reference_favorite_id: refValue, })) } className={cn( "rounded px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent/60", selected && "bg-accent", )} title={`参照模板「${tpl.name}」的视觉风格与版式`} > 模板:{tpl.name} ); })} {htmlFavorites.map((fav) => { const selected = form.html_reference_favorite_id === fav.id; return ( setForm((value) => ({ ...value, html_reference_favorite_id: fav.id })) } className={cn( "min-w-0 flex-1 truncate rounded px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent/60", selected && "bg-accent", )} title={fav.title} > {fav.title} handleDeleteFavorite(fav.id)} disabled={htmlFavoriteActions.remove.isPending} title="删除该收藏" > ); })} {htmlFavorites.length === 0 && ( 暂无收藏页面。可在执行记录的 HTML 预览中收藏页面后在此引用。 )} {/* 参考选了内置模板(tpl:)时:数据抽取开关。关闭=用模板默认数据。 */} {form.html_reference_favorite_id.startsWith("tpl:") && ( 执行数据抽取 关闭则直接用所选模板的默认数据生成(含全部子页面);开启才检索并按模板结构抽取数据填充。 setForm((value) => ({ ...value, html_template_extract: v })) } /> )} 生成模型 setForm((value) => ({ ...value, html_model_name: v })) } > {availableModels.map((model) => ( {model.display_name || model.name} ))} 执行流程:智能体运用自身检索技能整理真实数据 → 选定模型渲染为完整 HTML → 自动安全清洗与结构校验 → 可在执行记录中预览。 > )} 取消 保存 {tagPickerTask && ( !open && setTagPickerTask(null)} targetType="scheduled_task" targetId={tagPickerTask.task_id} currentTags={tagPickerTask.tags ?? []} /> )} ); }
选择任务后,在右侧查看全部执行记录
{selectedTask ? desensitize(selectedTask.name) : "请选择左侧任务"}
创建者: {displayUsername(selectedTask.creator_email) || selectedTask.creator_user_id}
执行频率
HTML 模板
{templateDisplayOnly ? ( <>选择要展示的 HTML 模板。该模板暂为「直接展示已有数据」,执行时将原样输出其现有页面。> ) : ( <> 选择要把源数据填充进去的 HTML 模板。执行时智能体会把下方源 JSON 转换成该模板所需的结构,校验后填充生成可预览的页面。 未提供源 JSON 时,将直接展示该模板的默认数据。 > )}
该模板暂为「直接展示已有数据」,无需填写源 JSON;执行时将原样输出模板的现有页面。
必须生成 Markdown 文件
开启后会提示大模型生成 Markdown(.md) 文件;系统会校验本次是否生成了 .md 文件且文件正文超过 100 字,未达到则记为失败。
必须生成 HTML 页面
开启后会先用智能体检索整理真实数据,再渲染为完整 HTML 页面(可在执行记录中预览)。可与“必须生成 Markdown”同时开启。
参考收藏页面(可选)
执行数据抽取
关闭则直接用所选模板的默认数据生成(含全部子页面);开启才检索并按模板结构抽取数据填充。
生成模型
执行流程:智能体运用自身检索技能整理真实数据 → 选定模型渲染为完整 HTML → 自动安全清洗与结构校验 → 可在执行记录中预览。