- 排行榜改为按天预计算快照(admin_leaderboard_daily_stats),请求只读取合并,重统计移至后台调度;过去日不可变、当天 TTL 刷新,避免在线聚合长时间占用数据库 - 为 runs/tool_call_metrics/llm_call_metrics/threads_meta 增加面向时间段+用户聚合的复合索引(model __table_args__ + migration 20260608_01) - 连接池可调:DatabaseConfig 新增 max_overflow / pool_timeout,接入 postgres/mysql 引擎;config.yaml 上调 pool_size=20/max_overflow=20 - 新增手动执行的索引脚本 scripts/sql/leaderboard_indexes_mysql.sql(幂等,适用于已存在数据、create_all 不补索引且 alembic 关闭的部署) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
828 lines
33 KiB
TypeScript
828 lines
33 KiB
TypeScript
"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 (
|
||
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
||
该文件不是文本内容,无法直接预览,请下载查看。
|
||
</div>
|
||
);
|
||
}
|
||
if (isMarkdownFile(file)) {
|
||
return (
|
||
<MarkdownContent
|
||
className="max-w-none"
|
||
content={file.content}
|
||
isLoading={false}
|
||
rehypePlugins={[]}
|
||
/>
|
||
);
|
||
}
|
||
return <pre className="whitespace-pre-wrap break-words text-sm">{file.content}</pre>;
|
||
}
|
||
|
||
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 <HtmlPreviewFrame html={preview.html} className="h-full w-full border-0 bg-white" />;
|
||
}
|
||
if (preview.mode === "markdown") {
|
||
return (
|
||
<MarkdownContent
|
||
className="max-w-none"
|
||
content={preview.content || "无正文内容"}
|
||
isLoading={false}
|
||
rehypePlugins={[]}
|
||
/>
|
||
);
|
||
}
|
||
if (preview.mode === "file") {
|
||
return <RenderPreview file={preview.file} />;
|
||
}
|
||
return <pre className="whitespace-pre-wrap break-words text-sm">{preview.content || "无正文内容"}</pre>;
|
||
}
|
||
|
||
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<string, { label: string; tone: string }> = {
|
||
"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<string, unknown>) : 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<Record<string, unknown>>)
|
||
: [];
|
||
const isAi = message.event_type === "llm.ai.response";
|
||
|
||
return (
|
||
<div className="min-w-0 rounded-md border">
|
||
<div className="flex min-w-0 flex-wrap items-center gap-2 border-b px-3 py-1.5">
|
||
<span className={cn("max-w-full break-all rounded px-1.5 py-0.5 text-xs font-medium", role.tone)}>
|
||
{role.label}
|
||
{toolName ? ` · ${toolName}` : ""}
|
||
</span>
|
||
{message.created_at && (
|
||
<span className="text-muted-foreground text-xs">
|
||
{new Date(message.created_at).toLocaleString()}
|
||
</span>
|
||
)}
|
||
</div>
|
||
<div className="p-3">
|
||
{text ? (
|
||
isAi ? (
|
||
<MarkdownContent className="max-w-none" content={text} isLoading={false} rehypePlugins={[]} />
|
||
) : (
|
||
<pre className="whitespace-pre-wrap break-words text-xs">{text}</pre>
|
||
)
|
||
) : (
|
||
!toolCalls.length && <div className="text-muted-foreground text-xs">(无文本内容)</div>
|
||
)}
|
||
{toolCalls.length > 0 && (
|
||
<div className="mt-2 flex flex-col gap-1">
|
||
{toolCalls.map((call, index) => (
|
||
<div key={index} className="bg-muted rounded px-2 py-1 text-xs">
|
||
<span className="font-medium">调用工具:{String(call.name ?? "未知")}</span>
|
||
{call.args != null && (
|
||
<pre className="mt-1 whitespace-pre-wrap break-words">
|
||
{typeof call.args === "string" ? call.args : JSON.stringify(call.args, null, 2)}
|
||
</pre>
|
||
)}
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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<ScheduledTaskResultFileContent[]>([]);
|
||
const [filesLoading, setFilesLoading] = useState(false);
|
||
const [showMeta, setShowMeta] = useState(false);
|
||
const [edits, setEdits] = useState<Record<number, EditState | null>>({});
|
||
const [fullscreenPreview, setFullscreenPreview] = useState<FullscreenPreview | null>(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<ScheduledTaskResultFileContent> =>
|
||
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 (
|
||
<>
|
||
<Dialog open={fullscreenPreview !== null} onOpenChange={(open) => !open && setFullscreenPreview(null)}>
|
||
<DialogContent className="flex h-[96vh] w-[96vw] max-w-none flex-col gap-0 p-0 sm:max-w-none">
|
||
<DialogHeader className="shrink-0 border-b px-4 py-3 pr-12">
|
||
<DialogTitle className="truncate text-base">
|
||
{fullscreenPreview?.title ?? "预览"}
|
||
</DialogTitle>
|
||
</DialogHeader>
|
||
{fullscreenPreview && (
|
||
<div
|
||
className={cn(
|
||
"min-h-0 flex-1",
|
||
fullscreenPreview.mode === "html" ? "" : "overflow-auto p-4",
|
||
)}
|
||
>
|
||
<FullscreenPreviewContent preview={fullscreenPreview} />
|
||
</div>
|
||
)}
|
||
</DialogContent>
|
||
</Dialog>
|
||
<WorkspaceContainer>
|
||
<WorkspaceHeader />
|
||
<WorkspaceBody>
|
||
<div className="flex size-full min-h-0 flex-col p-3">
|
||
<Card className="flex min-h-0 min-w-0 flex-1 flex-col">
|
||
{/* 工具栏 */}
|
||
<div className="flex min-w-0 flex-wrap items-center gap-2 border-b px-3 py-2">
|
||
<div className="mr-auto flex min-w-0 items-center gap-2">
|
||
<span className="truncate text-sm font-medium">
|
||
{result?.title || (isLoading ? "正在加载..." : "执行结果详情")}
|
||
</span>
|
||
{run && <Badge variant={statusVariant(run.status)} className="shrink-0">{statusLabel(run.status)}</Badge>}
|
||
</div>
|
||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => setShowMeta((v) => !v)}>
|
||
<ChevronDown className={cn("size-3 transition-transform", showMeta && "rotate-180")} />
|
||
执行信息
|
||
</Button>
|
||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={handleBack}>
|
||
<ChevronLeft className="size-3" />
|
||
返回
|
||
</Button>
|
||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={handleDownloadResult} disabled={!result}>
|
||
<Download className="size-3" />
|
||
下载全部
|
||
</Button>
|
||
<Button
|
||
variant="ghost"
|
||
size="sm"
|
||
className="h-7 px-2 text-xs"
|
||
onClick={handleDownloadBodyAsWord}
|
||
disabled={!result?.content}
|
||
title="将正文 Markdown 导出为 .docx"
|
||
>
|
||
<FileText className="size-3" />
|
||
下载正文 Word
|
||
</Button>
|
||
{canDeleteRun && (
|
||
<Button variant="destructive" size="sm" className="h-7 px-2 text-xs" onClick={handleDeleteRun}>
|
||
<Trash2 className="size-3" />
|
||
删除
|
||
</Button>
|
||
)}
|
||
</div>
|
||
{/* 执行信息(可折叠) */}
|
||
{showMeta && run && (
|
||
<div className="border-b px-3 py-2">
|
||
<div className="text-muted-foreground grid min-w-0 gap-x-4 gap-y-1 text-xs md:grid-cols-3 xl:grid-cols-5">
|
||
<div className="min-w-0 break-all">ID:{run.id}</div>
|
||
<div>计划:{formatDate(run.scheduled_for)}</div>
|
||
<div>开始:{formatDate(run.started_at)}</div>
|
||
<div>结束:{formatDate(run.finished_at)}</div>
|
||
<div>耗时:{formatDuration(run)}</div>
|
||
</div>
|
||
{run.error && (
|
||
<div className="text-destructive mt-2 break-words rounded border border-destructive/30 bg-destructive/5 p-2 text-xs">
|
||
{run.error}
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
{showMeta && !isLoading && !run && (
|
||
<div className="text-muted-foreground border-b px-3 py-2 text-xs">
|
||
没有找到这条执行记录。
|
||
</div>
|
||
)}
|
||
{/* 内容区 */}
|
||
{run && !result && !hasExecution && (
|
||
<div className="text-muted-foreground p-4 text-sm">
|
||
这条记录暂时还没有结果,任务可能仍在执行中。
|
||
</div>
|
||
)}
|
||
{run && (result || hasExecution) && (
|
||
<Tabs
|
||
defaultValue={
|
||
result ? (isHtmlRun ? "html" : fileCount > 0 ? "files" : "body") : "execution"
|
||
}
|
||
className="flex min-h-0 flex-1 flex-col"
|
||
>
|
||
<div className="min-w-0 overflow-x-auto border-b px-3 pt-1">
|
||
<TabsList className="h-8 w-max">
|
||
{result && isHtmlRun && (
|
||
<TabsTrigger value="html" className="text-xs">
|
||
<Code2 className="mr-1 size-3" />
|
||
HTML 预览
|
||
</TabsTrigger>
|
||
)}
|
||
{result && (
|
||
<TabsTrigger value="body" className="text-xs">
|
||
<FileText className="mr-1 size-3" />
|
||
正文
|
||
</TabsTrigger>
|
||
)}
|
||
{result && (
|
||
<TabsTrigger value="files" className="text-xs">
|
||
结果文件{fileCount > 0 && `(${fileCount})`}
|
||
</TabsTrigger>
|
||
)}
|
||
{hasExecution && (
|
||
<TabsTrigger value="execution" className="text-xs">
|
||
<Activity className="mr-1 size-3" />
|
||
执行过程{runMessages.length > 0 && `(${runMessages.length})`}
|
||
</TabsTrigger>
|
||
)}
|
||
{result && (
|
||
<TabsTrigger value="meta" className="text-xs">
|
||
元数据
|
||
</TabsTrigger>
|
||
)}
|
||
</TabsList>
|
||
</div>
|
||
<ScrollArea className="min-h-0 flex-1">
|
||
{result && (
|
||
<>
|
||
{isHtmlRun && (
|
||
<TabsContent value="html" className="m-0 p-4">
|
||
<div className="mb-3 flex flex-wrap items-center justify-end gap-2">
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={() =>
|
||
htmlContent &&
|
||
setFullscreenPreview({
|
||
mode: "html",
|
||
title: result.title || "HTML 预览",
|
||
html: htmlContent,
|
||
})
|
||
}
|
||
disabled={!htmlContent}
|
||
title="全屏查看 HTML"
|
||
>
|
||
<Maximize2 className="size-4" />
|
||
全屏
|
||
</Button>
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={handleFavorite}
|
||
disabled={!htmlPageId || alreadyFavorited || favoriteActions.create.isPending}
|
||
title={
|
||
alreadyFavorited
|
||
? "该页面已收藏"
|
||
: "收藏此页面,作为后续 HTML 任务的参考风格"
|
||
}
|
||
>
|
||
<Heart className={cn("size-4", alreadyFavorited && "fill-current text-rose-500")} />
|
||
{alreadyFavorited ? "已收藏" : "收藏页面"}
|
||
</Button>
|
||
</div>
|
||
{htmlContent ? (
|
||
<HtmlPreviewFrame html={htmlContent} />
|
||
) : (
|
||
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
||
HTML 页面尚未生成或正在生成中。
|
||
</div>
|
||
)}
|
||
</TabsContent>
|
||
)}
|
||
<TabsContent value="body" className="m-0 p-4">
|
||
<div className="mb-3 flex justify-end">
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={() =>
|
||
setFullscreenPreview({
|
||
mode: result.format === "markdown" || result.format === "mixed" ? "markdown" : "text",
|
||
title: result.title || "正文预览",
|
||
content: result.content || "无正文内容",
|
||
})
|
||
}
|
||
disabled={!result.content}
|
||
title="全屏查看正文"
|
||
>
|
||
<Maximize2 className="size-4" />
|
||
全屏
|
||
</Button>
|
||
</div>
|
||
{result.format === "markdown" || result.format === "mixed" ? (
|
||
<MarkdownContent
|
||
className="max-w-none"
|
||
content={result.content || "无正文内容"}
|
||
isLoading={false}
|
||
rehypePlugins={[]}
|
||
/>
|
||
) : (
|
||
<pre className="whitespace-pre-wrap break-words text-sm">
|
||
{result.content || "无正文内容"}
|
||
</pre>
|
||
)}
|
||
</TabsContent>
|
||
<TabsContent value="files" className="m-0 p-3">
|
||
{filesLoading && (
|
||
<div className="text-muted-foreground text-sm">正在加载文件内容...</div>
|
||
)}
|
||
{!filesLoading && fileContents.length === 0 && (
|
||
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
||
{fileCount > 0
|
||
? `本次执行生成了 ${fileCount} 个文件,但当前无法读取(文件可能已被清理或移动)。可尝试「下载全部」。`
|
||
: "本次执行没有生成文件。"}
|
||
</div>
|
||
)}
|
||
<div className="flex flex-col gap-3">
|
||
{fileContents.map((file) => {
|
||
const isMarkdown = isMarkdownFile(file);
|
||
const editable = canEditRun && file.previewable;
|
||
const editState = edits[file.index] ?? null;
|
||
const isEditing = editState !== null;
|
||
return (
|
||
<div key={file.index} className="min-w-0 rounded-md border">
|
||
<div className="flex flex-wrap items-center justify-between gap-2 border-b p-2">
|
||
<div className="min-w-0 flex-1">
|
||
<div className="truncate text-sm font-medium">{file.name}</div>
|
||
<div className="text-muted-foreground text-xs">
|
||
{file.mime_type || file.kind || "附件"}
|
||
{typeof file.size === "number" ? ` · ${file.size} bytes` : ""}
|
||
</div>
|
||
</div>
|
||
<div className="flex flex-wrap gap-2">
|
||
{file.previewable && !isEditing && (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={() =>
|
||
setFullscreenPreview({
|
||
mode: "file",
|
||
title: file.name,
|
||
file,
|
||
})
|
||
}
|
||
disabled={!file.content}
|
||
title="全屏查看文件"
|
||
>
|
||
<Maximize2 className="size-4" />
|
||
全屏
|
||
</Button>
|
||
)}
|
||
{isMarkdown && (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={() => handleDownloadFileAsWord(file)}
|
||
disabled={!file.content && !editState?.draft}
|
||
title="将 Markdown 导出为 Word"
|
||
>
|
||
<FileText className="size-4" />
|
||
下载 Word
|
||
</Button>
|
||
)}
|
||
<Button size="sm" variant="outline" onClick={() => handleDownloadFile(file.index)}>
|
||
<Download className="size-4" />
|
||
下载
|
||
</Button>
|
||
{editable && !isEditing && (
|
||
<Button size="sm" variant="outline" onClick={() => handleEnterEdit(file)}>
|
||
<Edit3 className="size-4" />
|
||
编辑
|
||
</Button>
|
||
)}
|
||
{isEditing && (
|
||
<>
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={() => handleCancelEdit(file.index)}
|
||
disabled={editState?.saving}
|
||
>
|
||
<X className="size-4" />
|
||
取消
|
||
</Button>
|
||
<Button
|
||
size="sm"
|
||
onClick={() => handleSaveEdit(file)}
|
||
disabled={editState?.saving}
|
||
>
|
||
{editState?.saving ? (
|
||
<Loader2 className="size-4 animate-spin" />
|
||
) : (
|
||
<Save className="size-4" />
|
||
)}
|
||
保存
|
||
</Button>
|
||
</>
|
||
)}
|
||
</div>
|
||
</div>
|
||
<div className="p-3">
|
||
{isEditing ? (
|
||
<Textarea
|
||
className="min-h-80 font-mono text-xs"
|
||
value={editState?.draft ?? ""}
|
||
disabled={editState?.saving}
|
||
onChange={(event) =>
|
||
setEdits((prev) => ({
|
||
...prev,
|
||
[file.index]: {
|
||
draft: event.target.value,
|
||
saving: prev[file.index]?.saving ?? false,
|
||
},
|
||
}))
|
||
}
|
||
/>
|
||
) : (
|
||
<RenderPreview file={file} />
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
</TabsContent>
|
||
<TabsContent value="meta" className="m-0 p-3">
|
||
<pre className="bg-muted overflow-auto whitespace-pre-wrap break-words rounded-md p-3 text-xs">
|
||
{resultMetadata}
|
||
</pre>
|
||
</TabsContent>
|
||
</>
|
||
)}
|
||
{hasExecution && (
|
||
<TabsContent value="execution" className="m-0 p-3">
|
||
{runLive && (
|
||
<div className="text-primary border-primary/30 bg-primary/5 mb-3 flex items-center gap-2 rounded-md border p-2 text-xs">
|
||
<Loader2 className="size-3 animate-spin" />
|
||
任务执行中,下方消息每 4 秒自动刷新…
|
||
</div>
|
||
)}
|
||
{messagesLoading && runMessages.length === 0 && (
|
||
<div className="text-muted-foreground text-sm">正在加载执行消息...</div>
|
||
)}
|
||
{!messagesLoading && runMessages.length === 0 && (
|
||
<div className="text-muted-foreground rounded-md border p-3 text-sm">
|
||
暂无执行消息,任务可能还未开始执行。
|
||
</div>
|
||
)}
|
||
<div className="flex flex-col gap-3">
|
||
{runMessages.map((message) => (
|
||
<ExecutionMessage key={message.seq} message={message} />
|
||
))}
|
||
</div>
|
||
</TabsContent>
|
||
)}
|
||
</ScrollArea>
|
||
</Tabs>
|
||
)}
|
||
</Card>
|
||
</div>
|
||
</WorkspaceBody>
|
||
</WorkspaceContainer>
|
||
</>
|
||
);
|
||
}
|