"use client"; import { useCallback, useEffect, useMemo, useState } from "react"; import { Activity, ChevronDown, ChevronLeft, Download, Edit3, FileText, Heart, Loader2, Maximize2, Save, Code2, Trash2, X } from "lucide-react"; import { useParams, 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, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { ScrollArea } from "@/components/ui/scroll-area"; 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 { MarkdownContent } from "@/components/workspace/messages/markdown-content"; import { HtmlPreviewFrame } from "@/components/html-preview-frame"; import { downloadScheduledTaskRun, downloadScheduledTaskRunFile, getScheduledTaskRunFileContent, type ScheduledTaskResultFileContent, type ScheduledTaskRun, type ScheduledTaskRunMessage, updateScheduledTaskRunFile, useHtmlPageFavoriteActions, useHtmlPageFavorites, useScheduledTaskActions, useScheduledTaskRun, useScheduledTaskRunHtml, useScheduledTaskRunMessages, } from "@/core/scheduled-tasks"; import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx"; import { cn } from "@/lib/utils"; function formatDate(value?: string | null) { return value ? new Date(value).toLocaleString() : "暂无"; } function formatDuration(run?: ScheduledTaskRun | null) { if (!run?.started_at || !run.finished_at) return "暂无"; const duration = new Date(run.finished_at).getTime() - new Date(run.started_at).getTime(); if (!Number.isFinite(duration) || duration < 0) return "暂无"; return `${Math.round(duration / 1000)} 秒`; } function statusLabel(status?: string | null) { switch (status) { case "succeeded": return "成功"; case "failed": return "失败"; case "running": return "执行中"; case "pending": return "等待中"; default: return status || "未知"; } } function statusVariant(status?: string | null): "default" | "secondary" | "destructive" | "outline" { if (status === "succeeded") return "default"; if (status === "failed") return "destructive"; if (status === "running") return "secondary"; return "outline"; } function isMarkdownFile(file: ScheduledTaskResultFileContent) { const name = file.name.toLowerCase(); return ( file.kind === "markdown" || file.mime_type === "text/markdown" || name.endsWith(".md") || name.endsWith(".markdown") ); } function RenderPreview({ file }: { file: ScheduledTaskResultFileContent }) { if (!file.previewable || !file.content) { return (
该文件不是文本内容,无法直接预览,请下载查看。
); } if (isMarkdownFile(file)) { return ( ); } return
{file.content}
; } type FullscreenPreview = | { mode: "html"; title: string; html: string } | { mode: "markdown"; title: string; content: string } | { mode: "text"; title: string; content: string } | { mode: "file"; title: string; file: ScheduledTaskResultFileContent }; function FullscreenPreviewContent({ preview }: { preview: FullscreenPreview }) { if (preview.mode === "html") { return ; } if (preview.mode === "markdown") { return ( ); } if (preview.mode === "file") { return ; } return
{preview.content || "无正文内容"}
; } type EditState = { draft: string; saving: boolean }; /** Flatten a LangChain-style message content (string | parts | nested) to text. */ function messageText(content: unknown): string { if (content == null) return ""; if (typeof content === "string") return content; if (Array.isArray(content)) { return content .map((part) => { if (typeof part === "string") return part; if (part && typeof part === "object" && "text" in part) { return String((part as { text?: unknown }).text ?? ""); } return ""; }) .filter(Boolean) .join("\n"); } if (typeof content === "object" && "content" in content) { return messageText((content as { content?: unknown }).content); } return JSON.stringify(content, null, 2); } const EXECUTION_ROLE: Record = { "llm.human.input": { label: "触发输入", tone: "bg-muted text-foreground" }, "llm.ai.response": { label: "智能体", tone: "bg-primary/10 text-primary" }, "llm.tool.result": { label: "工具结果", tone: "bg-amber-500/10 text-amber-600 dark:text-amber-400" }, }; /** One agent message rendered inside the execution-process tab. */ function ExecutionMessage({ message }: { message: ScheduledTaskRunMessage }) { const role = EXECUTION_ROLE[message.event_type] ?? { label: message.event_type, tone: "bg-muted text-foreground", }; const raw = message.content; const obj = raw && typeof raw === "object" ? (raw as Record) : null; const text = messageText(raw); const toolName = typeof obj?.name === "string" ? obj.name : null; const toolCalls = Array.isArray(obj?.tool_calls) ? (obj!.tool_calls as Array>) : []; const isAi = message.event_type === "llm.ai.response"; return (
{role.label} {toolName ? ` · ${toolName}` : ""} {message.created_at && ( {new Date(message.created_at).toLocaleString()} )}
{text ? ( isAi ? ( ) : (
{text}
) ) : ( !toolCalls.length &&
(无文本内容)
)} {toolCalls.length > 0 && (
{toolCalls.map((call, index) => (
调用工具:{String(call.name ?? "未知")} {call.args != null && (
                    {typeof call.args === "string" ? call.args : JSON.stringify(call.args, null, 2)}
                  
)}
))}
)}
); } export default function ScheduledTaskRunDetailPage() { const navigate = useNavigate(); const { run_id } = useParams(); const [searchParams] = useSearchParams(); const actions = useScheduledTaskActions(); const { data: run, isLoading } = useScheduledTaskRun(run_id); const result = run?.result ?? null; // A run still executing — drives live polling of its agent messages. const runLive = run?.status === "running" || run?.status === "pending"; const hasExecution = !!run?.agent_run_id; const { data: messagesData, isLoading: messagesLoading } = useScheduledTaskRunMessages( hasExecution ? run_id : null, { live: runLive }, ); const runMessages = messagesData?.messages ?? []; // Back navigation returns to the originating list (admin vs. mine) and // re-selects the task the user came from (carried in ?task=). const handleBack = useCallback(() => { const base = searchParams.get("from") === "admin" ? "/page/workspace/admin/scheduled-tasks" : "/page/workspace/scheduled/tasks"; const taskId = run?.task_id ?? searchParams.get("task"); navigate(taskId ? `${base}?task=${encodeURIComponent(taskId)}` : base); }, [navigate, run?.task_id, searchParams]); const [fileContents, setFileContents] = useState([]); const [filesLoading, setFilesLoading] = useState(false); const [showMeta, setShowMeta] = useState(false); const [edits, setEdits] = useState>({}); const [fullscreenPreview, setFullscreenPreview] = useState(null); const canEditRun = run?.can_edit === true; const canDeleteRun = canEditRun; // HTML page run: surface a sandboxed iframe preview + favorite button. const isHtmlRun = useMemo(() => { if (!result) return false; if (result.format === "html") return true; return (result.files ?? []).some( (f) => f.kind === "html" || (f.name ?? "").toLowerCase().endsWith(".html"), ); }, [result]); const { data: htmlData } = useScheduledTaskRunHtml(run_id, { enabled: isHtmlRun, live: runLive, }); const htmlContent = htmlData?.html ?? result?.html ?? null; const htmlPageId = htmlData?.page_id ?? null; const favoriteActions = useHtmlPageFavoriteActions(); const { data: htmlFavorites = [] } = useHtmlPageFavorites(isHtmlRun); const alreadyFavorited = !!htmlPageId && htmlFavorites.some((f) => f.page_id === htmlPageId); const handleFavorite = async () => { if (!htmlPageId) { toast.error("页面尚未生成或无法收藏"); return; } if (alreadyFavorited) { toast.error("该页面已收藏,请勿重复收藏"); return; } try { await favoriteActions.create.mutateAsync({ page_id: htmlPageId }); toast.success("已收藏,可在新建 HTML 任务时作为参考风格"); } catch (error) { toast.error(error instanceof Error ? error.message : "收藏失败"); } }; // The generated HTML document is already shown in the dedicated "HTML 预览" // tab, so it is excluded from the "结果文件" list — that list surfaces the // Markdown (and any other non-HTML artifact) only. const resultFiles = useMemo( () => (result?.files ?? []).filter( (f) => !(f.kind === "html" || (f.name ?? "").toLowerCase().endsWith(".html")), ), [result], ); const fileCount = resultFiles.length; const resultMetadata = useMemo(() => { if (!result) return ""; return JSON.stringify( { title: result.title, format: result.format, created_at: result.created_at, files: result.files, }, null, 2, ); }, [result]); useEffect(() => { let cancelled = false; async function loadFiles() { if (!run || !result || resultFiles.length === 0) { setFileContents([]); return; } setFilesLoading(true); try { // Load each file independently. A single failing file (e.g. an archive // that 404s) must NOT blank the whole panel — otherwise the tab shows // "结果文件(2)" while the body says "没有生成文件". Render every file // that loads and skip the ones that don't. const settled = await Promise.allSettled( resultFiles.map((f) => { const index = result.files.indexOf(f); return getScheduledTaskRunFileContent(run.id, index); }), ); if (!cancelled) { const loaded = settled .filter( (r): r is PromiseFulfilledResult => r.status === "fulfilled", ) .map((r) => r.value); setFileContents(loaded); const failed = settled.length - loaded.length; if (failed > 0 && loaded.length === 0) { toast.error("结果文件已不可用(可能已被清理)"); } } } finally { if (!cancelled) { setFilesLoading(false); } } } loadFiles(); return () => { cancelled = true; }; }, [run, result, resultFiles]); const handleDownloadResult = async () => { if (!run) return; try { await downloadScheduledTaskRun(run.id); } catch (error) { toast.error(error instanceof Error ? error.message : "下载失败"); } }; const handleDownloadFile = async (index: number) => { if (!run) return; try { await downloadScheduledTaskRunFile(run.id, index); } catch (error) { toast.error(error instanceof Error ? error.message : "下载失败"); } }; const handleDownloadFileAsWord = async (file: ScheduledTaskResultFileContent) => { // Prefer the in-progress draft if the user is editing the file. const source = edits[file.index]?.draft ?? file.content ?? ""; if (!source) { toast.error("文件内容未加载,无法转换为 Word"); return; } try { await downloadMarkdownAsDocx(source, file.name, result?.title); toast.success("Word 文件已生成"); } catch (error) { toast.error(error instanceof Error ? error.message : "生成 Word 失败"); } }; const handleEnterEdit = useCallback((file: ScheduledTaskResultFileContent) => { setEdits((prev) => ({ ...prev, [file.index]: { draft: file.content ?? "", saving: false }, })); }, []); const handleCancelEdit = useCallback((index: number) => { setEdits((prev) => ({ ...prev, [index]: null })); }, []); const handleSaveEdit = useCallback( async (file: ScheduledTaskResultFileContent) => { if (!run) return; const current = edits[file.index]; if (!current) return; setEdits((prev) => ({ ...prev, [file.index]: { ...current, saving: true }, })); try { const updated = await updateScheduledTaskRunFile(run.id, file.index, current.draft); setFileContents((prev) => prev.map((entry) => entry.index === file.index ? { ...entry, content: current.draft, size: updated.size ?? entry.size } : entry, ), ); setEdits((prev) => ({ ...prev, [file.index]: null })); toast.success(`文件 ${file.name} 已保存`); } catch (error) { setEdits((prev) => ({ ...prev, [file.index]: { ...current, saving: false }, })); toast.error(error instanceof Error ? error.message : "保存失败"); } }, [edits, run], ); const handleDownloadBodyAsWord = async () => { if (!result?.content) { toast.error("正文为空,无法转换为 Word"); return; } try { await downloadMarkdownAsDocx( result.content, result.title || "scheduled-task-result", result.title || undefined, ); toast.success("Word 文件已生成"); } catch (error) { toast.error(error instanceof Error ? error.message : "生成 Word 失败"); } }; const handleDeleteRun = async () => { if (!run || !canDeleteRun) return; try { await actions.removeRun.mutateAsync(run.id); toast.success("执行记录已删除"); handleBack(); } catch (error) { toast.error(error instanceof Error ? error.message : "删除失败"); } }; return ( <> !open && setFullscreenPreview(null)}> {fullscreenPreview?.title ?? "预览"} {fullscreenPreview && (
)}
{/* 工具栏 */}
{result?.title || (isLoading ? "正在加载..." : "执行结果详情")} {run && {statusLabel(run.status)}}
{canDeleteRun && ( )}
{/* 执行信息(可折叠) */} {showMeta && run && (
ID:{run.id}
计划:{formatDate(run.scheduled_for)}
开始:{formatDate(run.started_at)}
结束:{formatDate(run.finished_at)}
耗时:{formatDuration(run)}
{run.error && (
{run.error}
)}
)} {showMeta && !isLoading && !run && (
没有找到这条执行记录。
)} {/* 内容区 */} {run && !result && !hasExecution && (
这条记录暂时还没有结果,任务可能仍在执行中。
)} {run && (result || hasExecution) && ( 0 ? "files" : "body") : "execution" } className="flex min-h-0 flex-1 flex-col" >
{result && isHtmlRun && ( HTML 预览 )} {result && ( 正文 )} {result && ( 结果文件{fileCount > 0 && `(${fileCount})`} )} {hasExecution && ( 执行过程{runMessages.length > 0 && `(${runMessages.length})`} )} {result && ( 元数据 )}
{result && ( <> {isHtmlRun && (
{htmlContent ? ( ) : (
HTML 页面尚未生成或正在生成中。
)}
)}
{result.format === "markdown" || result.format === "mixed" ? ( ) : (
                      {result.content || "无正文内容"}
                    
)}
{filesLoading && (
正在加载文件内容...
)} {!filesLoading && fileContents.length === 0 && (
{fileCount > 0 ? `本次执行生成了 ${fileCount} 个文件,但当前无法读取(文件可能已被清理或移动)。可尝试「下载全部」。` : "本次执行没有生成文件。"}
)}
{fileContents.map((file) => { const isMarkdown = isMarkdownFile(file); const editable = canEditRun && file.previewable; const editState = edits[file.index] ?? null; const isEditing = editState !== null; return (
{file.name}
{file.mime_type || file.kind || "附件"} {typeof file.size === "number" ? ` · ${file.size} bytes` : ""}
{file.previewable && !isEditing && ( )} {isMarkdown && ( )} {editable && !isEditing && ( )} {isEditing && ( <> )}
{isEditing ? (