"use client"; import { useCallback, useEffect, useMemo, useState } from "react"; import { Activity, ChevronDown, ChevronLeft, Download, Edit3, FileText, Loader2, Save, 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 { 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 { downloadScheduledTaskRun, downloadScheduledTaskRunFile, getScheduledTaskRunFileContent, type ScheduledTaskResultFileContent, type ScheduledTaskRun, type ScheduledTaskRunMessage, updateScheduledTaskRunFile, useScheduledTaskActions, useScheduledTaskRun, 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 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 canEditRun = run?.can_edit === true; const canDeleteRun = canEditRun; const resultFiles = useMemo(() => result?.files ?? [], [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 { const loaded = await Promise.all( resultFiles.map((f) => { const index = result.files.indexOf(f); return getScheduledTaskRunFileContent(run.id, index); }), ); if (!cancelled) { setFileContents(loaded); } } catch (error) { if (!cancelled) { toast.error(error instanceof Error ? error.message : "加载文件内容失败"); } } 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 (
{/* 工具栏 */}
{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 && ( 正文 )} {result && ( 结果文件{fileCount > 0 && `(${fileCount})`} )} {hasExecution && ( 执行过程{runMessages.length > 0 && `(${runMessages.length})`} )} {result && ( 元数据 )}
{result && ( <> {result.format === "markdown" || result.format === "mixed" ? ( ) : (
                      {result.content || "无正文内容"}
                    
)}
{filesLoading && (
正在加载文件内容...
)} {!filesLoading && fileContents.length === 0 && (
本次执行没有生成文件。
)}
{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` : ""}
{isMarkdown && ( )} {editable && !isEditing && ( )} {isEditing && ( <> )}
{isEditing ? (