# Conflicts: # frontend-web/src/open-canvas/components/ai-writing/AIWritingForm.tsx # frontend-web/src/open-canvas/components/ai-writing/AIWritingPanel.tsx # offline-backend-20260512/backend/CLAUDE.md # offline-backend-20260512/backend/app/gateway/services.py # offline-backend-20260512/backend/tests/test_ai_writing_knowledge_base.py
1131 lines
40 KiB
TypeScript
1131 lines
40 KiB
TypeScript
"use client";
|
||
|
||
import {
|
||
ArrowDownIcon,
|
||
Code2Icon,
|
||
CopyIcon,
|
||
DownloadIcon,
|
||
ExternalLinkIcon,
|
||
EyeIcon,
|
||
FileType2Icon,
|
||
LoaderIcon,
|
||
PackageIcon,
|
||
SaveIcon,
|
||
SparklesIcon,
|
||
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 { MarkdownAiEditor } from "@/open-canvas/components/artifact/MarkdownAiEditor";
|
||
import { publishArtifactToKnowledge } from "@/core/agents/api";
|
||
import { useAgent } from "@/core/agents/hooks";
|
||
import { apiFetch } from "@/core/api";
|
||
import { copyTextToClipboard } from "@/core/clipboard";
|
||
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 { 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";
|
||
import { SkillInstallDialog } from "./skill-install-dialog";
|
||
|
||
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<HTMLElement>(".cm-scroller"),
|
||
root.querySelector<HTMLTextAreaElement>("textarea"),
|
||
root.querySelector<HTMLElement>("[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;
|
||
// 「AI 写作」md 展示开关:只要是可编辑的 markdown 就提供「AI 写作」视图(在 源码/预览 旁多一个
|
||
// 切换项),用户可随时切过去体验划词「AI 改写」。默认仍是「预览」,避免编辑器在内容加载期间
|
||
// 挂载导致白屏 + 避免复杂 md(表格/公式/HTML)误入有损编辑。
|
||
const canUseAiEditor = canEditArtifact;
|
||
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" | "edit">("code");
|
||
const [allowAutoViewSwitch, setAllowAutoViewSwitch] = useState(true);
|
||
const [installDialogOpen, setInstallDialogOpen] = useState(false);
|
||
const [showPreviewSwitchPulse, setShowPreviewSwitchPulse] = useState(false);
|
||
const [autoScrollEnabled, setAutoScrollEnabled] = useState(true);
|
||
const [showResumeAutoScroll, setShowResumeAutoScroll] = useState(false);
|
||
const [binaryPreviewUrl, setBinaryPreviewUrl] = useState<string | null>(
|
||
null,
|
||
);
|
||
const [spreadsheetData, setSpreadsheetData] = useState<ArrayBuffer | null>(
|
||
null,
|
||
);
|
||
const artifactContentRef = useRef<HTMLDivElement | null>(null);
|
||
const resumeButtonTimeoutRef = useRef<number | null>(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;
|
||
}
|
||
|
||
// md/mermaid 默认预览(AI 写作视图作为可选切换项,由用户手动进入)。
|
||
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 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 (
|
||
<Artifact className={cn(className)}>
|
||
<ArtifactHeader className="flex flex-wrap items-center gap-3 px-4 py-3">
|
||
<div className="flex min-w-0 items-center gap-2">
|
||
<div className="bg-muted/65 inline-flex min-w-0 items-center rounded-full border border-black/6 p-1 shadow-sm dark:border-white/8">
|
||
<span className="bg-background text-muted-foreground inline-flex h-7 shrink-0 items-center rounded-full border border-black/6 px-2.5 text-[10px] font-semibold tracking-[0.16em] dark:border-white/8">
|
||
{fileTypeLabel}
|
||
</span>
|
||
<ArtifactTitle className="min-w-0">
|
||
{/* markdown:隐藏文件名(仅留 MD 徽标),把横向空间让给工具栏,避免窄面板下
|
||
工具栏换行错位;多文件仍保留切换下拉(靠它切文件)。文件名仍可在下载/另存为时取到。 */}
|
||
{language === "markdown" && !hasMultipleArtifacts ? null : useWriteFileStreaming ? (
|
||
<div className="truncate px-3">{getFileName(filepath)}</div>
|
||
) : hasMultipleArtifacts ? (
|
||
<Select value={filepath} onValueChange={select}>
|
||
<SelectTrigger className="text-foreground h-8 min-w-0 max-w-[16rem] border-none bg-transparent! px-3 shadow-none select-none focus-visible:ring-0 focus:outline-0 active:outline-0">
|
||
<SelectValue placeholder="Select a file" />
|
||
</SelectTrigger>
|
||
<SelectContent className="select-none">
|
||
<SelectGroup>
|
||
{(artifacts ?? []).map((artifactPath) => (
|
||
<SelectItem key={artifactPath} value={artifactPath}>
|
||
{getFileName(artifactPath)}
|
||
</SelectItem>
|
||
))}
|
||
</SelectGroup>
|
||
</SelectContent>
|
||
</Select>
|
||
) : (
|
||
<div className="truncate px-3">{getFileName(filepath)}</div>
|
||
)}
|
||
</ArtifactTitle>
|
||
</div>
|
||
</div>
|
||
<div className="flex w-full items-center justify-center md:w-auto md:flex-1">
|
||
{isSupportPreview && (
|
||
<div className="flex items-center gap-2">
|
||
<ToggleGroup
|
||
className={cn(
|
||
"bg-muted/65 rounded-full border border-black/6 p-1 shadow-sm dark:border-white/8",
|
||
showPreviewSwitchPulse &&
|
||
"animate-[sandbox-preview-glow_1.1s_ease-out_2]",
|
||
)}
|
||
type="single"
|
||
variant="default"
|
||
size="sm"
|
||
spacing={1}
|
||
value={viewMode}
|
||
onValueChange={(value) => {
|
||
if (value) {
|
||
setAllowAutoViewSwitch(false);
|
||
setViewMode(value as "code" | "preview" | "edit");
|
||
}
|
||
}}
|
||
>
|
||
{canUseAiEditor && (
|
||
<ToggleGroupItem
|
||
className="text-muted-foreground h-8 min-w-10 rounded-full border-0 bg-transparent px-3 shadow-none data-[state=on]:bg-background data-[state=on]:text-foreground data-[state=on]:shadow-[0_6px_14px_-10px_rgba(15,23,42,0.35)]"
|
||
value="edit"
|
||
aria-label="AI 写作编辑"
|
||
>
|
||
<SparklesIcon />
|
||
</ToggleGroupItem>
|
||
)}
|
||
<ToggleGroupItem
|
||
className="text-muted-foreground h-8 min-w-10 rounded-full border-0 bg-transparent px-3 shadow-none data-[state=on]:bg-background data-[state=on]:text-foreground data-[state=on]:shadow-[0_6px_14px_-10px_rgba(15,23,42,0.35)]"
|
||
value="code"
|
||
>
|
||
<Code2Icon />
|
||
</ToggleGroupItem>
|
||
<ToggleGroupItem
|
||
className="text-muted-foreground h-8 min-w-10 rounded-full border-0 bg-transparent px-3 shadow-none data-[state=on]:bg-background data-[state=on]:text-foreground data-[state=on]:shadow-[0_6px_14px_-10px_rgba(15,23,42,0.35)]"
|
||
value="preview"
|
||
>
|
||
<EyeIcon />
|
||
</ToggleGroupItem>
|
||
</ToggleGroup>
|
||
{isHtmlStreaming && (
|
||
<div className="animate-[sandbox-preview-badge_1.4s_ease-in-out_infinite] text-muted-foreground bg-muted/80 inline-flex items-center rounded-full border px-2.5 py-1 text-[11px]">
|
||
<span className="bg-primary mr-2 size-1.5 animate-pulse rounded-full" />
|
||
正在生成,完成后自动预览
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
<div className="flex w-full items-center justify-end gap-2 md:ml-auto md:w-auto">
|
||
<ArtifactActions className="bg-muted/45 max-w-full flex-wrap justify-end rounded-3xl border border-black/6 p-1 dark:border-white/8">
|
||
{canPublishToKnowledge && (
|
||
<ArtifactAction
|
||
icon={isPublishingToKnowledge ? LoaderIcon : UploadCloudIcon}
|
||
label="发布入库"
|
||
tooltip={`发布到知识库(模板:${ingestTemplateName})`}
|
||
disabled={isPublishingToKnowledge || !displayContent}
|
||
onClick={() => void handlePublishToKnowledge()}
|
||
/>
|
||
)}
|
||
{canEditArtifact && (
|
||
<ArtifactAction
|
||
icon={updateArtifact.isPending ? LoaderIcon : SaveIcon}
|
||
label="保存 Markdown"
|
||
tooltip={hasLocalEdits ? "保存 Markdown 修改" : "Markdown 已保存"}
|
||
disabled={!hasLocalEdits || updateArtifact.isPending}
|
||
onClick={handleSaveArtifact}
|
||
/>
|
||
)}
|
||
{!useWriteFileStreaming && filepath.endsWith(".skill") && (
|
||
<Tooltip content={t.toolCalls.skillInstallTooltip}>
|
||
<ArtifactAction
|
||
icon={PackageIcon}
|
||
label={t.common.install}
|
||
tooltip={t.common.install}
|
||
disabled={
|
||
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"
|
||
}
|
||
onClick={() => setInstallDialogOpen(true)}
|
||
/>
|
||
</Tooltip>
|
||
)}
|
||
{isCodeFile && (
|
||
<ArtifactAction
|
||
icon={CopyIcon}
|
||
label={t.clipboard.copyToClipboard}
|
||
disabled={!content}
|
||
onClick={async () => {
|
||
try {
|
||
await copyTextToClipboard(displayContent ?? "");
|
||
toast.success(t.clipboard.copiedToClipboard);
|
||
} catch (error) {
|
||
toast.error("Failed to copy to clipboard");
|
||
console.error(error);
|
||
}
|
||
}}
|
||
tooltip={t.clipboard.copyToClipboard}
|
||
/>
|
||
)}
|
||
{language === "markdown" && (
|
||
<ArtifactAction
|
||
icon={isExportingWord ? LoaderIcon : FileType2Icon}
|
||
label="另存为 Word"
|
||
tooltip="另存为 Word (.docx)"
|
||
disabled={isExportingWord || !displayContent}
|
||
onClick={handleDownloadAsWord}
|
||
/>
|
||
)}
|
||
{language === "html" && (
|
||
<ArtifactAction
|
||
icon={ExternalLinkIcon}
|
||
label="新窗口打开"
|
||
tooltip="在新窗口全屏打开 HTML"
|
||
disabled={!displayContent?.trim()}
|
||
onClick={handleOpenInNewWindow}
|
||
/>
|
||
)}
|
||
<ArtifactAction
|
||
icon={DownloadIcon}
|
||
label={t.common.download}
|
||
tooltip={t.common.download}
|
||
onClick={async () => {
|
||
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",
|
||
);
|
||
}
|
||
}}
|
||
/>
|
||
<ArtifactAction
|
||
className="hover:bg-background"
|
||
icon={XIcon}
|
||
label={t.common.close}
|
||
onClick={() => (onClose ? onClose() : setOpen(false))}
|
||
tooltip={t.common.close}
|
||
/>
|
||
</ArtifactActions>
|
||
</div>
|
||
</ArtifactHeader>
|
||
<ArtifactContent
|
||
ref={artifactContentRef}
|
||
className="relative p-0"
|
||
onWheelCapture={handlePauseAutoScroll}
|
||
>
|
||
{isApplyingEdit && (
|
||
<div className="absolute right-4 bottom-4 z-20 inline-flex items-center gap-2 rounded-full border border-[#d8b878] bg-[#fff3cf]/95 px-3 py-1.5 text-xs text-[#6d5625] shadow-sm">
|
||
<span className="h-3.5 w-0.5 animate-pulse rounded-full bg-[#9b7a2f]" />
|
||
正在改写 Markdown
|
||
</div>
|
||
)}
|
||
{showResumeAutoScroll && (
|
||
<button
|
||
type="button"
|
||
onClick={handleResumeAutoScroll}
|
||
className="animate-[sandbox-scroll-button-in_220ms_ease-out] absolute inset-x-0 top-1/2 z-20 mx-auto flex w-fit -translate-y-1/2 items-center gap-2 rounded-full border border-white/35 bg-black/28 px-4 py-2 text-sm font-medium text-white shadow-[0_20px_40px_-24px_rgba(15,23,42,0.7)] backdrop-blur-md transition hover:bg-black/40"
|
||
>
|
||
<ArrowDownIcon className="size-4" />
|
||
滑动到底部并继续自动下滑
|
||
</button>
|
||
)}
|
||
{viewMode === "edit" && canUseAiEditor && (
|
||
<MarkdownAiEditor
|
||
// 编辑用原始内容(与源码模式一致,不脱敏);保存仍走头部「保存 Markdown」按钮。
|
||
markdown={displayContent ?? ""}
|
||
onChange={(value) => {
|
||
setDraftContent(value);
|
||
setHasLocalEdits(true);
|
||
}}
|
||
threadId={threadId}
|
||
/>
|
||
)}
|
||
{isSupportPreview &&
|
||
viewMode === "preview" &&
|
||
(language === "markdown" ||
|
||
language === "html" ||
|
||
language === "mermaid") && (
|
||
<ArtifactFilePreview
|
||
content={disableDesensitize ? (displayContent ?? "") : desensitize(displayContent ?? "")}
|
||
language={language ?? "text"}
|
||
threadId={threadId}
|
||
publicShareCode={publicShareCode}
|
||
animated={showPreviewSwitchPulse}
|
||
activeCursor={isApplyingEdit}
|
||
/>
|
||
)}
|
||
{isCodeFile && viewMode === "code" && (
|
||
<div className="size-full">
|
||
<CodeEditor
|
||
className="size-full resize-none rounded-none border-none bg-transparent"
|
||
value={
|
||
canEditArtifact || disableDesensitize
|
||
? (displayContent ?? "")
|
||
: desensitize(displayContent ?? "")
|
||
}
|
||
readonly={!canEditArtifact}
|
||
onChange={
|
||
canEditArtifact
|
||
? (value) => {
|
||
setDraftContent(value);
|
||
setHasLocalEdits(true);
|
||
}
|
||
: undefined
|
||
}
|
||
streamingReadonlyFallback={!canEditArtifact}
|
||
/>
|
||
</div>
|
||
)}
|
||
{!isCodeFile && isSpreadsheetFile && (
|
||
spreadsheetData ? (
|
||
<SpreadsheetPreview data={spreadsheetData} />
|
||
) : (
|
||
<div className="text-muted-foreground flex size-full items-center justify-center gap-2 text-sm">
|
||
<LoaderIcon className="size-5 animate-spin" />
|
||
{t.common.loading}
|
||
</div>
|
||
)
|
||
)}
|
||
{!isCodeFile &&
|
||
!isSpreadsheetFile &&
|
||
(binaryPreviewUrl ? (
|
||
<iframe className="size-full bg-white" src={binaryPreviewUrl} />
|
||
) : (
|
||
<div className="text-muted-foreground flex size-full items-center justify-center gap-2 text-sm">
|
||
<LoaderIcon className="size-5 animate-spin" />
|
||
{t.common.loading}
|
||
</div>
|
||
))}
|
||
</ArtifactContent>
|
||
<SkillInstallDialog
|
||
open={installDialogOpen}
|
||
onOpenChange={setInstallDialogOpen}
|
||
threadId={threadId}
|
||
filepath={filepath}
|
||
/>
|
||
</Artifact>
|
||
);
|
||
}
|
||
|
||
function SandboxPreviewImage({
|
||
src,
|
||
alt,
|
||
threadId,
|
||
publicShareCode,
|
||
...props
|
||
}: React.ImgHTMLAttributes<HTMLImageElement> & {
|
||
threadId: string;
|
||
publicShareCode?: string;
|
||
}) {
|
||
if (!src || typeof src !== "string") {
|
||
return null;
|
||
}
|
||
|
||
let url = src;
|
||
if (src.startsWith("/mnt/")) {
|
||
if (publicShareCode) {
|
||
const normalized = src.startsWith("/") ? src : `/${src}`;
|
||
url = `${getBackendBaseURL()}/api/public/shares/${encodeURIComponent(
|
||
publicShareCode,
|
||
)}/files${normalized}`;
|
||
} else {
|
||
url = resolveArtifactURL(src, threadId);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<img
|
||
{...props}
|
||
className={cn(
|
||
"my-3 max-w-full overflow-hidden rounded-lg",
|
||
props.className,
|
||
)}
|
||
src={url}
|
||
alt={alt}
|
||
/>
|
||
);
|
||
}
|
||
|
||
export function ArtifactFilePreview({
|
||
content,
|
||
language,
|
||
threadId,
|
||
publicShareCode,
|
||
animated = false,
|
||
activeCursor = false,
|
||
}: {
|
||
content: string;
|
||
language: string;
|
||
threadId: string;
|
||
publicShareCode?: string;
|
||
animated?: boolean;
|
||
activeCursor?: boolean;
|
||
}) {
|
||
const [htmlPreviewUrl, setHtmlPreviewUrl] = useState<string>();
|
||
const [mermaidSvg, setMermaidSvg] = useState<string | null>(null);
|
||
const [mermaidError, setMermaidError] = useState<string | null>(null);
|
||
const markdownComponents = useMemo(() => {
|
||
const anchorResolver = createMarkdownAnchorResolver(content ?? "");
|
||
const heading = (level: 1 | 2 | 3 | 4 | 5 | 6) => {
|
||
const Tag = `h${level}` as const;
|
||
return ({ children, id, ...props }: HTMLAttributes<HTMLHeadingElement>) => (
|
||
<Tag id={id ?? anchorResolver.getHeadingId(level, extractTextFromChildren(children))} {...props}>
|
||
{children}
|
||
</Tag>
|
||
);
|
||
};
|
||
|
||
return {
|
||
h1: heading(1),
|
||
h2: heading(2),
|
||
h3: heading(3),
|
||
h4: heading(4),
|
||
h5: heading(5),
|
||
h6: heading(6),
|
||
a: (props: AnchorHTMLAttributes<HTMLAnchorElement>) => {
|
||
if (typeof props.children === "string" && /^citation:(.+)$/.test(props.children)) {
|
||
return <ArtifactLink {...props} />;
|
||
}
|
||
const { className, ...rest } = props;
|
||
const resolvedHref = anchorResolver.resolveHref(
|
||
props.href,
|
||
extractTextFromChildren(props.children),
|
||
);
|
||
if (resolvedHref === null) {
|
||
return (
|
||
<span
|
||
className={cn(
|
||
"text-primary/80 decoration-dotted underline underline-offset-2 cursor-not-allowed",
|
||
className,
|
||
)}
|
||
title="未在当前 Markdown 中找到对应章节"
|
||
>
|
||
{props.children}
|
||
</span>
|
||
);
|
||
}
|
||
const finalHref = resolvedHref ?? props.href;
|
||
return (
|
||
<ArtifactLink
|
||
{...rest}
|
||
className={className}
|
||
href={finalHref}
|
||
onClick={(event) => {
|
||
if (isInPageAnchor(finalHref)) {
|
||
event.preventDefault();
|
||
scrollToInPageAnchor(event.currentTarget, finalHref);
|
||
}
|
||
rest.onClick?.(event);
|
||
}}
|
||
/>
|
||
);
|
||
},
|
||
};
|
||
}, [content]);
|
||
|
||
useEffect(() => {
|
||
if (language !== "html") {
|
||
setHtmlPreviewUrl(undefined);
|
||
return;
|
||
}
|
||
|
||
// 必须带 charset=utf-8:blob: URL 的 Content-Type 不含 charset 时,iframe 会按
|
||
// 系统默认编码(中文 Windows 常为 GBK/Latin-1)解码,模型生成的 HTML 若没写
|
||
// <meta charset> 就会中文乱码。与下方下载/新窗口打开的 blobType 保持一致。
|
||
// Intercept in-page anchor clicks so they scroll within the iframe instead
|
||
// of navigating the sandboxed blob: document (which blanks the frame).
|
||
const blob = new Blob([injectInPageAnchorHandler(content ?? "")], {
|
||
type: "text/html;charset=utf-8",
|
||
});
|
||
const url = URL.createObjectURL(blob);
|
||
setHtmlPreviewUrl(url);
|
||
|
||
return () => {
|
||
URL.revokeObjectURL(url);
|
||
};
|
||
}, [content, language]);
|
||
|
||
useEffect(() => {
|
||
if (language !== "mermaid") {
|
||
setMermaidSvg(null);
|
||
setMermaidError(null);
|
||
return;
|
||
}
|
||
|
||
let cancelled = false;
|
||
setMermaidSvg(null);
|
||
setMermaidError(null);
|
||
|
||
void renderMermaidToSvg(content ?? "")
|
||
.then((svg) => {
|
||
if (!cancelled) {
|
||
setMermaidSvg(svg);
|
||
}
|
||
})
|
||
.catch((error) => {
|
||
console.error("Failed to render mermaid preview:", error);
|
||
if (!cancelled) {
|
||
setMermaidError(
|
||
error instanceof Error ? error.message : "Mermaid 渲染失败",
|
||
);
|
||
}
|
||
});
|
||
|
||
return () => {
|
||
cancelled = true;
|
||
};
|
||
}, [content, language]);
|
||
|
||
if (language === "markdown") {
|
||
return (
|
||
<div
|
||
data-artifact-preview-scroll
|
||
data-markdown-anchor-root
|
||
className={cn(
|
||
"size-full overflow-auto px-5 py-4",
|
||
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
||
)}
|
||
>
|
||
<Streamdown
|
||
className="size-full"
|
||
{...streamdownPlugins}
|
||
components={{
|
||
...markdownComponents,
|
||
img: (props) => (
|
||
<SandboxPreviewImage
|
||
{...props}
|
||
threadId={threadId}
|
||
publicShareCode={publicShareCode}
|
||
/>
|
||
),
|
||
}}
|
||
>
|
||
{content ?? ""}
|
||
</Streamdown>
|
||
{activeCursor && (
|
||
<span className="mt-2 inline-block h-5 w-0.5 animate-pulse rounded-full bg-[#9b7a2f]" />
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
if (language === "html") {
|
||
return (
|
||
<iframe
|
||
className={cn(
|
||
"size-full bg-white",
|
||
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
||
)}
|
||
title="Artifact preview"
|
||
sandbox="allow-scripts allow-forms"
|
||
src={htmlPreviewUrl}
|
||
/>
|
||
);
|
||
}
|
||
|
||
if (language === "mermaid") {
|
||
return (
|
||
<div
|
||
data-artifact-preview-scroll
|
||
className={cn(
|
||
"size-full overflow-auto bg-[#fcfdfc] px-5 py-4",
|
||
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
|
||
)}
|
||
>
|
||
{mermaidSvg ? (
|
||
<div
|
||
className="mx-auto flex min-h-full items-start justify-center rounded-2xl border border-slate-200 bg-white p-4 shadow-sm"
|
||
dangerouslySetInnerHTML={{ __html: mermaidSvg }}
|
||
/>
|
||
) : mermaidError ? (
|
||
<div className="space-y-3">
|
||
<div className="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
|
||
{mermaidError}
|
||
</div>
|
||
<pre className="whitespace-pre-wrap break-words rounded-xl bg-slate-100 p-4 text-xs text-slate-700">
|
||
{content ?? ""}
|
||
</pre>
|
||
</div>
|
||
) : (
|
||
<div className="text-muted-foreground flex size-full items-center justify-center gap-2 text-sm">
|
||
<LoaderIcon className="size-5 animate-spin" />
|
||
正在生成图表预览
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return null;
|
||
}
|