Initial commit: deerflow-server (frontend-web + offline-backend-20260512)

This commit is contained in:
吉鑫升 committed 2026-05-13 09:36:15 +08:00
commit e7a455f22e
560 files changed
+101331

No files matched your search

@@ -0,0 +1,605 @@
"use client";
import {
ArrowDownIcon,
Code2Icon,
CopyIcon,
DownloadIcon,
EyeIcon,
LoaderIcon,
PackageIcon,
SquareArrowOutUpRightIcon,
XIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } 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 { apiFetch } from "@/core/api";
import {
downloadArtifactFile,
openArtifactInNewTab,
} from "@/core/artifacts/download";
import { useArtifactContent } from "@/core/artifacts/hooks";
import { urlOfArtifact } from "@/core/artifacts/utils";
import { useI18n } from "@/core/i18n/hooks";
import { installSkill } from "@/core/skills/api";
import { streamdownPlugins } from "@/core/streamdown";
import { checkCodeFile, getFileName } from "@/core/utils/files";
import { env } from "@/env";
import { cn } from "@/lib/utils";
import { ArtifactLink } from "../citations/artifact-link";
import { useThread } from "../messages/context";
import { Tooltip } from "../tooltip";
import { useArtifacts } from "./context";
const SANDBOX_RESUME_EVENT = "workspace:sandbox-resume-autoscroll";
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,
}: {
className?: string;
filepath: string;
threadId: string;
}) {
const { t } = useI18n();
const { artifacts, setOpen, select } = useArtifacts();
const { isMock, thread } = useThread();
const isWriteFile = useMemo(() => {
return filepathFromProps.startsWith("write-file:");
}, [filepathFromProps]);
const filepath = useMemo(() => {
if (isWriteFile) {
const url = new URL(filepathFromProps);
return decodeURIComponent(url.pathname);
}
return filepathFromProps;
}, [filepathFromProps, isWriteFile]);
const isSkillFile = useMemo(() => {
return filepath.endsWith(".skill");
}, [filepath]);
const { isCodeFile, language } = useMemo(() => {
if (isWriteFile) {
let nextLanguage = checkCodeFile(filepath).language;
nextLanguage ??= "text";
return { isCodeFile: true, language: nextLanguage };
}
if (isSkillFile) {
return { isCodeFile: true, language: "markdown" };
}
return checkCodeFile(filepath);
}, [filepath, isWriteFile, isSkillFile]);
const isSupportPreview = useMemo(() => {
return language === "html" || language === "markdown";
}, [language]);
const { content } = useArtifactContent({
threadId,
filepath: filepathFromProps,
enabled: isCodeFile && !isWriteFile,
});
const displayContent = content ?? "";
const isHtmlStreaming = language === "html" && thread.isLoading;
const hasMultipleArtifacts = (artifacts?.length ?? 0) > 1;
const fileTypeLabel = useMemo(() => {
if (language === "html") return "HTML";
if (language === "markdown") return "MD";
if (isSkillFile) return "SKILL";
if (language) return language.toUpperCase();
return "FILE";
}, [isSkillFile, 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<string | null>(
null,
);
const artifactContentRef = useRef<HTMLDivElement | null>(null);
const resumeButtonTimeoutRef = useRef<number | null>(null);
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) {
setBinaryPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
return;
}
let cancelled = false;
(async () => {
try {
const res = await apiFetch(
urlOfArtifact({ filepath, threadId, isMock }),
);
if (cancelled || !res.ok) 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;
setBinaryPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
};
}, [filepath, threadId, isMock, isCodeFile]);
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]);
return (
<Artifact className={cn(className)}>
<ArtifactHeader className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] 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">
{isWriteFile ? (
<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 items-center justify-center">
{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");
}
}}
>
<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 items-center justify-end gap-2">
<ArtifactActions className="bg-muted/45 rounded-full border border-black/6 p-1 dark:border-white/8">
{!isWriteFile && filepath.endsWith(".skill") && (
<Tooltip content={t.toolCalls.skillInstallTooltip}>
<ArtifactAction
icon={isInstalling ? LoaderIcon : PackageIcon}
label={t.common.install}
tooltip={t.common.install}
disabled={
isInstalling ||
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"
}
onClick={handleInstallSkill}
/>
</Tooltip>
)}
{!isWriteFile && (
<ArtifactAction
icon={SquareArrowOutUpRightIcon}
label={t.common.openInNewWindow}
tooltip={t.common.openInNewWindow}
onClick={async () => {
try {
await openArtifactInNewTab({
filepath,
threadId,
isMock,
});
} catch (error) {
console.error(error);
toast.error(
error instanceof Error
? error.message
: "Failed to open artifact",
);
}
}}
/>
)}
{isCodeFile && (
<ArtifactAction
icon={CopyIcon}
label={t.clipboard.copyToClipboard}
disabled={!content}
onClick={async () => {
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}
/>
)}
{!isWriteFile && (
<ArtifactAction
icon={DownloadIcon}
label={t.common.download}
tooltip={t.common.download}
onClick={async () => {
try {
await downloadArtifactFile({
filepath,
threadId,
isMock,
});
} 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={() => setOpen(false)}
tooltip={t.common.close}
/>
</ArtifactActions>
</div>
</ArtifactHeader>
<ArtifactContent
ref={artifactContentRef}
className="relative p-0"
onWheelCapture={handlePauseAutoScroll}
>
{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>
)}
{isSupportPreview &&
viewMode === "preview" &&
(language === "markdown" || language === "html") && (
<ArtifactFilePreview
content={displayContent}
language={language ?? "text"}
animated={showPreviewSwitchPulse}
/>
)}
{isCodeFile && viewMode === "code" && (
<div className="size-full">
<CodeEditor
className="size-full resize-none rounded-none border-none bg-transparent"
value={displayContent ?? ""}
readonly
/>
</div>
)}
{!isCodeFile &&
(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>
</Artifact>
);
}
export function ArtifactFilePreview({
content,
language,
animated = false,
}: {
content: string;
language: string;
animated?: boolean;
}) {
const [htmlPreviewUrl, setHtmlPreviewUrl] = useState<string>();
useEffect(() => {
if (language !== "html") {
setHtmlPreviewUrl(undefined);
return;
}
const blob = new Blob([content ?? ""], { type: "text/html" });
const url = URL.createObjectURL(blob);
setHtmlPreviewUrl(url);
return () => {
URL.revokeObjectURL(url);
};
}, [content, language]);
if (language === "markdown") {
return (
<div
data-artifact-preview-scroll
className={cn(
"size-full overflow-auto px-5 py-4",
animated && "animate-[sandbox-preview-enter_320ms_ease-out]",
)}
>
<Streamdown
className="size-full"
{...streamdownPlugins}
components={{ a: ArtifactLink }}
>
{content ?? ""}
</Streamdown>
</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}
/>
);
}
return null;
}