"use client"; import { ArrowDownIcon, Code2Icon, CopyIcon, DownloadIcon, ExternalLinkIcon, EyeIcon, FileType2Icon, LoaderIcon, PackageIcon, SaveIcon, UploadCloudIcon, XIcon, } from "lucide-react"; import { useParams } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react"; import { toast } from "sonner"; import { Streamdown } from "streamdown"; import { Artifact, ArtifactAction, ArtifactActions, ArtifactContent, ArtifactHeader, ArtifactTitle, } from "@/components/ai-elements/artifact"; import { Select, SelectItem } from "@/components/ui/select"; import { SelectContent, SelectGroup, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; import { CodeEditor } from "@/components/workspace/code-editor"; import { publishArtifactToKnowledge } from "@/core/agents/api"; import { useAgent } from "@/core/agents/hooks"; import { apiFetch } from "@/core/api"; import { downloadArtifactFile, } from "@/core/artifacts/download"; import { useArtifactContent, useUpdateArtifactContent, } from "@/core/artifacts/hooks"; import { resolveArtifactURL, urlOfArtifact } from "@/core/artifacts/utils"; import { useI18n } from "@/core/i18n/hooks"; import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx"; import { installSkill } from "@/core/skills/api"; import { streamdownPlugins } from "@/core/streamdown"; import { checkCodeFile, getFileName, isImageFile, } from "@/core/utils/files"; import { downloadMermaidSvgFile, isMermaidFile, openMermaidSvgInNewTab, renderMermaidToSvg, } from "@/core/utils/mermaid"; import { createMarkdownAnchorResolver, injectInPageAnchorHandler, isInPageAnchor, scrollToInPageAnchor, } from "@/core/utils/markdown"; import { getBackendBaseURL } from "@/core/config"; import { env } from "@/env"; import { desensitize } from "@/lib/desensitize"; import { cn } from "@/lib/utils"; import { ArtifactLink } from "../citations/artifact-link"; import { useThread } from "../messages/context"; import { Tooltip } from "../tooltip"; import { useArtifacts } from "./context"; import { SpreadsheetPreview } from "./spreadsheet-preview"; const SANDBOX_RESUME_EVENT = "workspace:sandbox-resume-autoscroll"; function extractTextFromChildren(children: ReactNode): string { if (typeof children === "string" || typeof children === "number") return String(children); if (Array.isArray(children)) return children.map(extractTextFromChildren).join(""); return ""; } /** 取 md 标题用于入库:优先文中第一个标题行,否则退回文件名(去扩展名)。 */ function extractMarkdownTitle(content: string, filepath: string): string { const heading = /^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/m.exec(content); if (heading?.[1]) return heading[1].trim(); return getFileName(filepath).replace(/\.(md|markdown)$/i, ""); } function findScrollableArtifactElement(root: HTMLElement | null) { if (!root) { return null; } const candidates = [ root.querySelector(".cm-scroller"), root.querySelector("textarea"), root.querySelector("[data-artifact-preview-scroll]"), root, ]; return ( candidates.find( (element) => !!element && element.scrollHeight - element.clientHeight > 1, ) ?? root ); } export function ArtifactFileDetail({ className, filepath: filepathFromProps, threadId, onClose, allowVirtualMarkdownEdit = false, disableDesensitize = false, }: { className?: string; filepath: string; threadId: string; /** 覆盖默认关闭行为(仅 setOpen(false));圆桌 Step3 文件预览用于退出沙箱模式。 */ onClose?: () => void; /** * 圆桌沙箱(Step2/Step3)用:流式结束后,把 `write-file:` 虚拟 md 预览切回真实 * artifacts API(可加载 + PATCH 保存),从而支持用户编辑(对齐主聊天页 md 可编辑)。 * 默认 false —— 主聊天页等其它调用方行为不变。 */ allowVirtualMarkdownEdit?: boolean; /** * 关闭对预览内容的脱敏。多智能体会商页的「消息列表沙箱」按需求**不脱敏**沙箱内的 * 产物内容(用户要拿原始文件),故 Step2SandboxLayout 传 true;主聊天等其它调用方 * 默认 false,沿用全局脱敏。 */ disableDesensitize?: boolean; }) { const { t } = useI18n(); const { artifacts, setOpen, select } = useArtifacts(); const { isMock, thread, publicShareCode } = useThread(); const isWriteFileVirtual = useMemo(() => { return filepathFromProps.startsWith("write-file:"); }, [filepathFromProps]); const filepath = useMemo(() => { if (isWriteFileVirtual) { const url = new URL(filepathFromProps); return decodeURIComponent(url.pathname); } return filepathFromProps; }, [filepathFromProps, isWriteFileVirtual]); const isSkillFile = useMemo(() => { return filepath.endsWith(".skill"); }, [filepath]); // .xlsx is a ZIP archive — the generic binary iframe preview renders its // raw bytes as mojibake, so it gets a dedicated table preview instead. const isSpreadsheetFile = useMemo(() => { return /\.xlsx$/i.test(filepath); }, [filepath]); // 圆桌沙箱:write_file 虚拟预览的 md 在流式结束(thread 非 loading)后,切回真实 // artifacts API 加载并允许编辑/保存。流式进行中仍走内存 stub 只读预览;仅 // allowVirtualMarkdownEdit 开启的调用方(Step2/Step3 沙箱)生效,主聊天页不受影响。 const editVirtualMarkdown = useMemo(() => { return ( allowVirtualMarkdownEdit && isWriteFileVirtual && !isImageFile(filepath) && !isMock && !thread.isLoading && checkCodeFile(filepath).language === "markdown" ); }, [allowVirtualMarkdownEdit, isWriteFileVirtual, filepath, isMock, thread.isLoading]); /** write_file 流式预览走 tool args 文本;图片等二进制产物始终走 artifacts API; * 圆桌结束后可编辑的 md(editVirtualMarkdown)亦回到真实 API(可加载 + PATCH 保存)。 */ const useWriteFileStreaming = useMemo(() => { return isWriteFileVirtual && !isImageFile(filepath) && !editVirtualMarkdown; }, [filepath, isWriteFileVirtual, editVirtualMarkdown]); const { isCodeFile, language } = useMemo(() => { if (useWriteFileStreaming) { let nextLanguage = checkCodeFile(filepath).language; nextLanguage ??= "text"; return { isCodeFile: true, language: nextLanguage }; } if (isSkillFile) { return { isCodeFile: true, language: "markdown" }; } return checkCodeFile(filepath); }, [filepath, useWriteFileStreaming, isSkillFile]); const isSupportPreview = useMemo(() => { return ( language === "html" || language === "markdown" || language === "mermaid" ); }, [language]); const { content, isApplyingEdit } = useArtifactContent({ threadId, // editVirtualMarkdown:用解码后的真实路径走 artifacts API(而非 write-file 虚拟 // URL),这样保存后 useUpdateArtifactContent 写入的查询缓存才能命中,编辑内容 // 不会被旧的内存 stub 值覆盖回退。 filepath: editVirtualMarkdown ? filepath : filepathFromProps, enabled: isCodeFile && !useWriteFileStreaming, }); const canEditArtifact = language === "markdown" && !useWriteFileStreaming && !isSkillFile && !isMock; const [draftContent, setDraftContent] = useState(""); const [hasLocalEdits, setHasLocalEdits] = useState(false); const updateArtifact = useUpdateArtifactContent(); const displayContent = canEditArtifact ? draftContent : (content ?? ""); const isHtmlStreaming = language === "html" && thread.isLoading; const hasMultipleArtifacts = (artifacts?.length ?? 0) > 1; const fileTypeLabel = useMemo(() => { if (isImageFile(filepath)) return "IMG"; if (isSpreadsheetFile) return "XLSX"; if (isMermaidFile(filepath) || language === "mermaid") return "MMD"; if (language === "html") return "HTML"; if (language === "markdown") return "MD"; if (isSkillFile) return "SKILL"; if (language) return language.toUpperCase(); return "FILE"; }, [filepath, isSkillFile, isSpreadsheetFile, language]); const [viewMode, setViewMode] = useState<"code" | "preview">("code"); const [allowAutoViewSwitch, setAllowAutoViewSwitch] = useState(true); const [isInstalling, setIsInstalling] = useState(false); const [showPreviewSwitchPulse, setShowPreviewSwitchPulse] = useState(false); const [autoScrollEnabled, setAutoScrollEnabled] = useState(true); const [showResumeAutoScroll, setShowResumeAutoScroll] = useState(false); const [binaryPreviewUrl, setBinaryPreviewUrl] = useState( null, ); const [spreadsheetData, setSpreadsheetData] = useState( null, ); const artifactContentRef = useRef(null); const resumeButtonTimeoutRef = useRef(null); useEffect(() => { setDraftContent(content ?? ""); setHasLocalEdits(false); }, [filepathFromProps]); useEffect(() => { if (!canEditArtifact || hasLocalEdits) { return; } setDraftContent(content ?? ""); }, [canEditArtifact, content, hasLocalEdits]); useEffect(() => { setAllowAutoViewSwitch(true); setAutoScrollEnabled(true); setShowResumeAutoScroll(false); if (language === "html") { setViewMode(thread.isLoading ? "code" : "preview"); return; } if (isSupportPreview) { setViewMode("preview"); return; } setViewMode("code"); }, [filepathFromProps, isSupportPreview, language, thread.isLoading]); useEffect(() => { if (!allowAutoViewSwitch || language !== "html") { return; } if (thread.isLoading) { setViewMode("code"); return; } setViewMode("preview"); setShowPreviewSwitchPulse(true); const timeoutId = window.setTimeout(() => { setShowPreviewSwitchPulse(false); }, 1400); return () => window.clearTimeout(timeoutId); }, [allowAutoViewSwitch, language, thread.isLoading]); const scrollArtifactToBottom = useCallback( (behavior: ScrollBehavior = "auto") => { const target = findScrollableArtifactElement(artifactContentRef.current); if (!target) { return false; } target.scrollTo({ top: target.scrollHeight, behavior, }); return true; }, [], ); useEffect(() => { if (!thread.isLoading || !autoScrollEnabled) { return; } const tick = () => { scrollArtifactToBottom("auto"); }; tick(); const intervalId = window.setInterval(tick, 180); return () => window.clearInterval(intervalId); }, [autoScrollEnabled, scrollArtifactToBottom, thread.isLoading]); useEffect(() => { if (!thread.isLoading || !autoScrollEnabled) { return; } scrollArtifactToBottom("auto"); }, [ autoScrollEnabled, content, scrollArtifactToBottom, thread.isLoading, viewMode, ]); useEffect(() => { const handleResumeEvent = () => { setAutoScrollEnabled(true); setShowResumeAutoScroll(false); scrollArtifactToBottom("smooth"); }; window.addEventListener(SANDBOX_RESUME_EVENT, handleResumeEvent); return () => { window.removeEventListener(SANDBOX_RESUME_EVENT, handleResumeEvent); }; }, [scrollArtifactToBottom]); useEffect(() => { return () => { if (resumeButtonTimeoutRef.current) { window.clearTimeout(resumeButtonTimeoutRef.current); } }; }, []); useEffect(() => { if (isCodeFile) { setSpreadsheetData(null); setBinaryPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); return null; }); return; } let cancelled = false; (async () => { try { const res = await apiFetch( urlOfArtifact({ filepath, threadId, isMock, publicShareCode }), ); if (cancelled || !res.ok) return; if (isSpreadsheetFile) { const buffer = await res.arrayBuffer(); if (!cancelled) { setSpreadsheetData(buffer); } return; } const blob = await res.blob(); if (cancelled) return; const u = URL.createObjectURL(blob); setBinaryPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); return u; }); } catch (error) { console.error("Artifact preview load failed:", error); if (!cancelled) { toast.error("Failed to load preview"); } } })(); return () => { cancelled = true; setSpreadsheetData(null); setBinaryPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); return null; }); }; }, [filepath, threadId, isMock, isCodeFile, isSpreadsheetFile, publicShareCode]); const handlePauseAutoScroll = useCallback(() => { if (!thread.isLoading || !autoScrollEnabled) { return; } setAutoScrollEnabled(false); setShowResumeAutoScroll(true); }, [autoScrollEnabled, thread.isLoading]); const handleResumeAutoScroll = useCallback(() => { setAutoScrollEnabled(true); scrollArtifactToBottom("smooth"); setShowResumeAutoScroll(true); if (resumeButtonTimeoutRef.current) { window.clearTimeout(resumeButtonTimeoutRef.current); } resumeButtonTimeoutRef.current = window.setTimeout(() => { setShowResumeAutoScroll(false); }, 1600); }, [scrollArtifactToBottom]); const handleInstallSkill = useCallback(async () => { if (isInstalling) return; setIsInstalling(true); try { const result = await installSkill({ thread_id: threadId, path: filepath, }); if (result.success) { toast.success(result.message); } else { toast.error(result.message ?? "Failed to install skill"); } } catch (error) { console.error("Failed to install skill:", error); toast.error("Failed to install skill"); } finally { setIsInstalling(false); } }, [threadId, filepath, isInstalling]); const handleSaveArtifact = useCallback(async () => { if (!canEditArtifact || updateArtifact.isPending) { return; } try { await updateArtifact.mutateAsync({ filepath, threadId, isMock, content: draftContent, }); setHasLocalEdits(false); toast.success("Markdown 已保存"); } catch (error) { console.error("Failed to save artifact:", error); toast.error(error instanceof Error ? error.message : "Markdown 保存失败"); } }, [ canEditArtifact, draftContent, filepath, isMock, threadId, updateArtifact, ]); // 发布入库:仅当当前路由是智能体会话(agents/:agent_id/chats/…)且该智能体 // 配置了入库模板名(template_name)时,md 产物右上角才出现发布按钮。 const { agent_id: routeAgentId } = useParams<{ agent_id?: string }>(); const { agent: routeAgent } = useAgent(routeAgentId ?? null); const ingestTemplateName = routeAgent?.template_name?.trim() ?? ""; const canPublishToKnowledge = !!routeAgentId && !!ingestTemplateName && language === "markdown" && !isSkillFile && !isMock; const [isPublishingToKnowledge, setIsPublishingToKnowledge] = useState(false); const handlePublishToKnowledge = useCallback(async () => { if (!routeAgentId || isPublishingToKnowledge) { return; } const source = (displayContent ?? "").trim(); if (!source) { toast.error("Markdown 内容为空,无法发布入库"); return; } setIsPublishingToKnowledge(true); try { const result = await publishArtifactToKnowledge({ agent_id: routeAgentId, title: extractMarkdownTitle(source, filepath), content: source, }); if (result.success) { toast.success(`已发布入库:${result.node_name}`); } else { const last = result.attempts[result.attempts.length - 1]; toast.error( `发布入库失败:${last?.error ?? last?.response_text ?? "接口返回失败"}`, ); } } catch (error) { console.error("Failed to publish artifact to knowledge base:", error); toast.error(error instanceof Error ? error.message : "发布入库失败"); } finally { setIsPublishingToKnowledge(false); } }, [displayContent, filepath, isPublishingToKnowledge, routeAgentId]); const [isExportingWord, setIsExportingWord] = useState(false); const handleDownloadAsWord = useCallback(async () => { const source = (displayContent ?? "").trim(); if (!source) { toast.error("Markdown 内容为空,无法另存为 Word"); return; } setIsExportingWord(true); try { const baseName = getFileName(filepath).replace(/\.(md|markdown)$/i, ""); await downloadMarkdownAsDocx(source, baseName || "document", baseName); toast.success("已另存为 Word"); } catch (error) { console.error("Failed to export markdown as docx:", error); toast.error(error instanceof Error ? error.message : "另存为 Word 失败"); } finally { setIsExportingWord(false); } }, [displayContent, filepath]); /** HTML 产物在新窗口打开(结果绘制汇总/大屏多页都需要全屏看)。 * blob: URL 带 charset=utf-8(与预览/下载一致,防中文乱码);URL 延迟回收, * 给新窗口足够的加载时间。 */ const handleOpenInNewWindow = useCallback(() => { const source = displayContent ?? ""; if (!source.trim()) { toast.error("文件内容为空,暂时无法在新窗口打开"); return; } const blob = new Blob([source], { type: "text/html;charset=utf-8" }); const url = URL.createObjectURL(blob); window.open(url, "_blank", "noopener,noreferrer"); window.setTimeout(() => URL.revokeObjectURL(url), 60_000); }, [displayContent]); const handleDownloadWriteFile = useCallback(() => { const source = displayContent ?? ""; if (!source.trim()) { toast.error("文件内容为空,暂时无法下载"); return; } if (language === "mermaid") { void downloadMermaidSvgFile(source, filepath).catch((error) => { console.error("Failed to download mermaid artifact:", error); toast.error(error instanceof Error ? error.message : "Download failed"); }); return; } const blobType = language === "html" ? "text/html;charset=utf-8" : language === "markdown" ? "text/markdown;charset=utf-8" : "text/plain;charset=utf-8"; const blob = new Blob([source], { type: blobType }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = getFileName(filepath); document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }, [displayContent, filepath, language]); return (
{fileTypeLabel} {useWriteFileStreaming ? (
{getFileName(filepath)}
) : hasMultipleArtifacts ? ( ) : (
{getFileName(filepath)}
)}
{isSupportPreview && (
{ if (value) { setAllowAutoViewSwitch(false); setViewMode(value as "code" | "preview"); } }} > {isHtmlStreaming && (
正在生成,完成后自动预览
)}
)}
{canPublishToKnowledge && ( void handlePublishToKnowledge()} /> )} {canEditArtifact && ( )} {!useWriteFileStreaming && filepath.endsWith(".skill") && ( )} {isCodeFile && ( { try { await navigator.clipboard.writeText(displayContent ?? ""); toast.success(t.clipboard.copiedToClipboard); } catch (error) { toast.error("Failed to copy to clipboard"); console.error(error); } }} tooltip={t.clipboard.copyToClipboard} /> )} {!useWriteFileStreaming && language === "markdown" && ( )} {language === "html" && ( )} { if (useWriteFileStreaming) { handleDownloadWriteFile(); return; } if (language === "mermaid") { try { await downloadMermaidSvgFile(displayContent ?? "", filepath); } catch (error) { console.error(error); toast.error( error instanceof Error ? error.message : "Download failed", ); } return; } try { await downloadArtifactFile({ filepath, threadId, isMock, publicShareCode, }); } catch (error) { console.error(error); toast.error( error instanceof Error ? error.message : "Download failed", ); } }} /> (onClose ? onClose() : setOpen(false))} tooltip={t.common.close} />
{isApplyingEdit && (
正在改写 Markdown
)} {showResumeAutoScroll && ( )} {isSupportPreview && viewMode === "preview" && (language === "markdown" || language === "html" || language === "mermaid") && ( )} {isCodeFile && viewMode === "code" && (
{ setDraftContent(value); setHasLocalEdits(true); } : undefined } streamingReadonlyFallback={!canEditArtifact} />
)} {!isCodeFile && isSpreadsheetFile && ( spreadsheetData ? ( ) : (
{t.common.loading}
) )} {!isCodeFile && !isSpreadsheetFile && (binaryPreviewUrl ? (