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,36 @@
"use client";
import { BotIcon } from "lucide-react";
import { type Agent } from "@/core/agents";
import { cn } from "@/lib/utils";
export function AgentWelcome({
className,
agent,
agentName,
}: {
className?: string;
agent: Agent | null | undefined;
agentName: string;
}) {
const displayName = agent?.name ?? agentName;
const description = agent?.description;
return (
<div
className={cn(
"mx-auto flex w-full flex-col items-center justify-center gap-2 px-8 py-4 text-center",
className,
)}
>
<div className="bg-primary/10 flex h-12 w-12 items-center justify-center rounded-full">
<BotIcon className="text-primary h-6 w-6" />
</div>
<div className="text-2xl font-bold">{displayName}</div>
{description && (
<p className="text-muted-foreground max-w-sm text-sm">{description}</p>
)}
</div>
);
}
@@ -0,0 +1,296 @@
"use client";
import { BotIcon, MessageSquareIcon, SquarePenIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useDeleteAgent, useUpdateAgent } from "@/core/agents";
import type { Agent } from "@/core/agents";
import { useI18n } from "@/core/i18n/hooks";
import { useSkills } from "@/core/skills/hooks";
interface AgentCardProps {
agent: Agent;
}
export function AgentCard({ agent }: AgentCardProps) {
const { t } = useI18n();
const router = useRouter();
const deleteAgent = useDeleteAgent();
const updateAgent = useUpdateAgent();
const { skills, isLoading: isSkillsLoading } = useSkills();
const [deleteOpen, setDeleteOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [editDescription, setEditDescription] = useState(agent.description ?? "");
const [editSoul, setEditSoul] = useState(agent.soul ?? "");
const [selectedSkills, setSelectedSkills] = useState<string[]>(
agent.skills ?? [],
);
useEffect(() => {
if (!editOpen) {
return;
}
setEditDescription(agent.description ?? "");
setEditSoul(agent.soul ?? "");
setSelectedSkills(agent.skills ?? []);
}, [agent.description, agent.skills, agent.soul, editOpen]);
function handleChat() {
router.push(`/workspace/agents/${agent.name}/chats/new`);
}
async function handleDelete() {
try {
await deleteAgent.mutateAsync(agent.name);
toast.success(t.agents.deleteSuccess);
setDeleteOpen(false);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
async function handleSaveEdit() {
try {
await updateAgent.mutateAsync({
name: agent.name,
request: {
description: editDescription,
soul: editSoul,
skills: selectedSkills,
},
});
toast.success("智能体已更新");
setEditOpen(false);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
function toggleSkill(skillName: string) {
setSelectedSkills((prev) => {
if (prev.includes(skillName)) {
return prev.filter((name) => name !== skillName);
}
return [...prev, skillName];
});
}
const enabledSkills = skills.filter((skill) => skill.enabled);
return (
<>
<Card className="group flex flex-col transition-shadow hover:shadow-md">
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-2">
<div className="flex items-center gap-2">
<div className="bg-primary/10 text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-lg">
<BotIcon className="h-5 w-5" />
</div>
<div className="min-w-0">
<CardTitle className="truncate text-base">
{agent.name}
</CardTitle>
{agent.model && (
<Badge variant="secondary" className="mt-0.5 text-xs">
{agent.model}
</Badge>
)}
</div>
</div>
</div>
{agent.description && (
<CardDescription className="mt-2 line-clamp-2 text-sm">
{agent.description}
</CardDescription>
)}
</CardHeader>
{(agent.tool_groups?.length ?? agent.skills?.length ?? 0) > 0 && (
<CardContent className="pt-0 pb-3">
<div className="flex flex-wrap gap-1">
{agent.tool_groups?.map((group) => (
<Badge
key={`tg:${group}`}
variant="outline"
className="text-xs"
>
{group}
</Badge>
))}
{agent.skills?.map((skill) => (
<Badge
key={`sk:${skill}`}
variant="secondary"
className="text-xs"
>
{skill}
</Badge>
))}
</div>
</CardContent>
)}
<CardFooter className="mt-auto flex items-center justify-between gap-2 pt-3">
<Button size="sm" className="flex-1" onClick={handleChat}>
<MessageSquareIcon className="mr-1.5 h-3.5 w-3.5" />
{t.agents.chat}
</Button>
<div className="flex gap-1">
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
onClick={() => setEditOpen(true)}
title="编辑智能体"
>
<SquarePenIcon className="h-3.5 w-3.5" />
</Button>
<Button
size="icon"
variant="ghost"
className="text-destructive hover:text-destructive h-8 w-8 shrink-0"
onClick={() => setDeleteOpen(true)}
title={t.agents.delete}
>
<Trash2Icon className="h-3.5 w-3.5" />
</Button>
</div>
</CardFooter>
</Card>
<Dialog open={editOpen} onOpenChange={setEditOpen}>
<DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>编辑智能体:{agent.name}</DialogTitle>
<DialogDescription>
可以修改描述、技能白名单和 SOUL 内容。
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<label className="text-sm font-medium">名称</label>
<Input value={agent.name} disabled />
</div>
<div className="space-y-2">
<label className="text-sm font-medium">描述</label>
<Textarea
value={editDescription}
onChange={(e) => setEditDescription(e.target.value)}
placeholder="输入智能体描述"
className="min-h-20"
/>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium">技能白名单</label>
<span className="text-muted-foreground text-xs">
已选 {selectedSkills.length} 个
</span>
</div>
<div className="rounded-md border p-2">
{isSkillsLoading ? (
<p className="text-muted-foreground text-sm">技能加载中...</p>
) : enabledSkills.length === 0 ? (
<p className="text-muted-foreground text-sm">
当前没有可用技能
</p>
) : (
<div className="flex flex-wrap gap-2">
{enabledSkills.map((skill) => {
const checked = selectedSkills.includes(skill.name);
return (
<Button
key={skill.name}
type="button"
size="sm"
variant={checked ? "default" : "outline"}
onClick={() => toggleSkill(skill.name)}
title={skill.description}
className="h-8"
>
{skill.name}
</Button>
);
})}
</div>
)}
</div>
<p className="text-muted-foreground text-xs">
不选任何技能会保存为无技能(skills = [])。
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">SOUL</label>
<Textarea
value={editSoul ?? ""}
onChange={(e) => setEditSoul(e.target.value)}
placeholder="输入 SOUL.md 内容"
className="min-h-40 font-mono text-xs"
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setEditOpen(false)}
disabled={updateAgent.isPending}
>
{t.common.cancel}
</Button>
<Button onClick={handleSaveEdit} disabled={updateAgent.isPending}>
{updateAgent.isPending ? t.common.loading : "保存修改"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete Confirm */}
<Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t.agents.delete}</DialogTitle>
<DialogDescription>{t.agents.deleteConfirm}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setDeleteOpen(false)}
disabled={deleteAgent.isPending}
>
{t.common.cancel}
</Button>
<Button
variant="destructive"
onClick={handleDelete}
disabled={deleteAgent.isPending}
>
{deleteAgent.isPending ? t.common.loading : t.common.delete}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,69 @@
"use client";
import { BotIcon, PlusIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { useAgents } from "@/core/agents";
import { useI18n } from "@/core/i18n/hooks";
import { AgentCard } from "./agent-card";
export function AgentGallery() {
const { t } = useI18n();
const { agents, isLoading } = useAgents();
const router = useRouter();
const handleNewAgent = () => {
router.push("/workspace/agents/new");
};
return (
<div className="flex size-full flex-col">
{/* Page header */}
<div className="flex items-center justify-between border-b px-6 py-4">
<div>
<h1 className="text-xl font-semibold">{t.agents.title}</h1>
<p className="text-muted-foreground mt-0.5 text-sm">
{t.agents.description}
</p>
</div>
<Button onClick={handleNewAgent}>
<PlusIcon className="mr-1.5 h-4 w-4" />
{t.agents.newAgent}
</Button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-6">
{isLoading ? (
<div className="text-muted-foreground flex h-40 items-center justify-center text-sm">
{t.common.loading}
</div>
) : agents.length === 0 ? (
<div className="flex h-64 flex-col items-center justify-center gap-3 text-center">
<div className="bg-muted flex h-14 w-14 items-center justify-center rounded-full">
<BotIcon className="text-muted-foreground h-7 w-7" />
</div>
<div>
<p className="font-medium">{t.agents.emptyTitle}</p>
<p className="text-muted-foreground mt-1 text-sm">
{t.agents.emptyDescription}
</p>
</div>
<Button variant="outline" className="mt-2" onClick={handleNewAgent}>
<PlusIcon className="mr-1.5 h-4 w-4" />
{t.agents.newAgent}
</Button>
</div>
) : (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{agents.map((agent) => (
<AgentCard key={agent.name} agent={agent} />
))}
</div>
)}
</div>
</div>
);
}
@@ -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;
}
@@ -0,0 +1,148 @@
import { DownloadIcon, LoaderIcon, PackageIcon } from "lucide-react";
import { useCallback, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Card,
CardAction,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { downloadArtifactFile } from "@/core/artifacts/download";
import { useI18n } from "@/core/i18n/hooks";
import { installSkill } from "@/core/skills/api";
import {
getFileExtensionDisplayName,
getFileIcon,
getFileName,
} from "@/core/utils/files";
import { cn } from "@/lib/utils";
import { useThread } from "../messages/context";
import { useArtifacts } from "./context";
export function ArtifactFileList({
className,
files,
threadId,
}: {
className?: string;
files: string[];
threadId: string;
}) {
const { t } = useI18n();
const { isMock } = useThread();
const { select: selectArtifact, setOpen } = useArtifacts();
const [installingFile, setInstallingFile] = useState<string | null>(null);
const [downloadingFile, setDownloadingFile] = useState<string | null>(null);
const handleClick = useCallback(
(filepath: string) => {
selectArtifact(filepath);
setOpen(true);
},
[selectArtifact, setOpen],
);
const handleInstallSkill = useCallback(
async (e: React.MouseEvent, filepath: string) => {
e.stopPropagation();
e.preventDefault();
if (installingFile) return;
setInstallingFile(filepath);
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 {
setInstallingFile(null);
}
},
[threadId, installingFile],
);
const handleDownload = useCallback(
async (e: React.MouseEvent, filepath: string) => {
e.stopPropagation();
e.preventDefault();
if (downloadingFile) return;
setDownloadingFile(filepath);
try {
await downloadArtifactFile({ filepath, threadId, isMock });
} catch (error) {
console.error(error);
toast.error(
error instanceof Error ? error.message : "Download failed",
);
} finally {
setDownloadingFile(null);
}
},
[threadId, isMock, downloadingFile],
);
return (
<ul className={cn("flex w-full flex-col gap-4", className)}>
{files.map((file) => (
<Card
key={file}
className="relative cursor-pointer p-3"
onClick={() => handleClick(file)}
>
<CardHeader className="grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1 pr-2 pl-1">
<CardTitle className="relative min-w-0 pl-8 leading-tight [overflow-wrap:anywhere] break-words">
<div className="min-w-0">{getFileName(file)}</div>
<div className="absolute top-2 -left-0.5">
{getFileIcon(file, "size-6")}
</div>
</CardTitle>
<CardDescription className="min-w-0 pl-8 text-xs">
{getFileExtensionDisplayName(file)} file
</CardDescription>
<CardAction className="row-span-1 self-center">
{file.endsWith(".skill") && (
<Button
variant="ghost"
disabled={installingFile === file}
onClick={(e) => handleInstallSkill(e, file)}
>
{installingFile === file ? (
<LoaderIcon className="size-4 animate-spin" />
) : (
<PackageIcon className="size-4" />
)}
{t.common.install}
</Button>
)}
<Button
variant="ghost"
disabled={downloadingFile === file}
onClick={(e) => handleDownload(e, file)}
>
{downloadingFile === file ? (
<LoaderIcon className="size-4 animate-spin" />
) : (
<DownloadIcon className="size-4" />
)}
{t.common.download}
</Button>
</CardAction>
</CardHeader>
</Card>
))}
</ul>
);
}
@@ -0,0 +1,30 @@
import { FilesIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/workspace/tooltip";
import { useI18n } from "@/core/i18n/hooks";
import { useArtifacts } from "./context";
export const ArtifactTrigger = () => {
const { t } = useI18n();
const { artifacts, setOpen: setArtifactsOpen } = useArtifacts();
if (!artifacts || artifacts.length === 0) {
return null;
}
return (
<Tooltip content="Show artifacts of this conversation">
<Button
className="text-muted-foreground hover:text-foreground"
variant="ghost"
onClick={() => {
setArtifactsOpen(true);
}}
>
<FilesIcon />
{t.common.artifacts}
</Button>
</Tooltip>
);
};
@@ -0,0 +1,96 @@
import {
createContext,
useCallback,
useContext,
useState,
type ReactNode,
} from "react";
import { useSidebar } from "@/components/ui/sidebar";
import { env } from "@/env";
export interface ArtifactsContextType {
artifacts: string[];
setArtifacts: (artifacts: string[]) => void;
selectedArtifact: string | null;
autoSelect: boolean;
select: (artifact: string, autoSelect?: boolean) => void;
deselect: () => void;
open: boolean;
autoOpen: boolean;
setOpen: (open: boolean) => void;
}
const ArtifactsContext = createContext<ArtifactsContextType | undefined>(
undefined,
);
interface ArtifactsProviderProps {
children: ReactNode;
}
export function ArtifactsProvider({ children }: ArtifactsProviderProps) {
const [artifacts, setArtifacts] = useState<string[]>([]);
const [selectedArtifact, setSelectedArtifact] = useState<string | null>(null);
const [autoSelect, setAutoSelect] = useState(true);
const [open, setOpen] = useState(
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true",
);
const [autoOpen, setAutoOpen] = useState(true);
const { setOpen: setSidebarOpen } = useSidebar();
const select = useCallback(
(artifact: string, autoSelect = false) => {
setSelectedArtifact(artifact);
if (env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true") {
setSidebarOpen(false);
}
if (!autoSelect) {
setAutoSelect(false);
}
},
[setSidebarOpen, setSelectedArtifact, setAutoSelect],
);
const deselect = useCallback(() => {
setSelectedArtifact(null);
setAutoSelect(true);
setOpen(false);
}, []);
const value: ArtifactsContextType = {
artifacts,
setArtifacts,
open,
autoOpen,
autoSelect,
setOpen: (isOpen: boolean) => {
if (!isOpen && autoOpen) {
setAutoOpen(false);
setAutoSelect(false);
}
setOpen(isOpen);
},
selectedArtifact,
select,
deselect,
};
return (
<ArtifactsContext.Provider value={value}>
{children}
</ArtifactsContext.Provider>
);
}
export function useArtifacts() {
const context = useContext(ArtifactsContext);
if (context === undefined) {
throw new Error("useArtifacts must be used within an ArtifactsProvider");
}
return context;
}
@@ -0,0 +1,4 @@
export * from "./artifact-file-detail";
export * from "./artifact-file-list";
export * from "./artifact-trigger";
export * from "./context";
@@ -0,0 +1,183 @@
import { FilesIcon, XIcon } from "lucide-react";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import type { GroupImperativeHandle } from "react-resizable-panels";
import { ConversationEmptyState } from "@/components/ai-elements/conversation";
import { Button } from "@/components/ui/button";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
} from "@/components/ui/resizable";
import { env } from "@/env";
import { cn } from "@/lib/utils";
import {
ArtifactFileDetail,
ArtifactFileList,
useArtifacts,
} from "../artifacts";
import { useThread } from "../messages/context";
const CLOSE_MODE = { chat: 100, artifacts: 0 };
const OPEN_MODE = { chat: 60, artifacts: 40 };
const ChatBox: React.FC<{ children: React.ReactNode; threadId: string }> = ({
children,
threadId,
}) => {
const { thread } = useThread();
const pathname = usePathname();
const threadIdRef = useRef(threadId);
const layoutRef = useRef<GroupImperativeHandle>(null);
const {
artifacts,
open: artifactsOpen,
setOpen: setArtifactsOpen,
setArtifacts,
select: selectArtifact,
deselect,
selectedArtifact,
} = useArtifacts();
const [autoSelectFirstArtifact, setAutoSelectFirstArtifact] = useState(true);
useEffect(() => {
if (threadIdRef.current !== threadId) {
threadIdRef.current = threadId;
deselect();
}
// Update artifacts from the current thread
setArtifacts(thread.values.artifacts);
// DO NOT automatically deselect the artifact when switching threads, because the artifacts auto discovering is not work now.
// if (
// selectedArtifact &&
// !thread.values.artifacts?.includes(selectedArtifact)
// ) {
// deselect();
// }
if (
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" &&
autoSelectFirstArtifact
) {
if (thread?.values?.artifacts?.length > 0) {
setAutoSelectFirstArtifact(false);
selectArtifact(thread.values.artifacts[0]!);
}
}
}, [
threadId,
autoSelectFirstArtifact,
deselect,
selectArtifact,
selectedArtifact,
setArtifacts,
thread.values.artifacts,
]);
const artifactPanelOpen = useMemo(() => {
if (env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true") {
return artifactsOpen && artifacts?.length > 0;
}
return artifactsOpen;
}, [artifactsOpen, artifacts]);
const resizableIdBase = useMemo(() => {
const raw = pathname
.replace(/[^a-zA-Z0-9_-]+/g, "-")
.replace(/^-+|-+$/g, "");
return raw.length > 0 ? raw : `thread-${threadId}`;
}, [pathname, threadId]);
useEffect(() => {
if (layoutRef.current) {
if (artifactPanelOpen) {
layoutRef.current.setLayout(OPEN_MODE);
} else {
layoutRef.current.setLayout(CLOSE_MODE);
}
}
}, [artifactPanelOpen]);
return (
<ResizablePanelGroup
id={`${resizableIdBase}-panels`}
orientation="horizontal"
defaultLayout={{ chat: 100, artifacts: 0 }}
groupRef={layoutRef}
>
<ResizablePanel className="relative" defaultSize={100} id="chat">
{children}
</ResizablePanel>
<ResizableHandle
id={`${resizableIdBase}-separator`}
className={cn(
"opacity-33 hover:opacity-100",
!artifactPanelOpen && "pointer-events-none opacity-0",
)}
/>
<ResizablePanel
className={cn(
"bg-[#fffdfa] transition-all duration-300 ease-in-out",
!artifactsOpen && "opacity-0",
)}
id="artifacts"
>
<div
className={cn(
"h-full bg-[#fffdfa] p-4 transition-transform duration-300 ease-in-out",
artifactPanelOpen ? "translate-x-0" : "translate-x-full",
)}
>
{selectedArtifact ? (
<ArtifactFileDetail
className="size-full"
filepath={selectedArtifact}
threadId={threadId}
/>
) : (
<div className="relative flex size-full justify-center">
<div className="absolute top-1 right-1 z-30">
<Button
size="icon-sm"
variant="ghost"
onClick={() => {
setArtifactsOpen(false);
}}
>
<XIcon />
</Button>
</div>
{thread.values.artifacts?.length === 0 ? (
<ConversationEmptyState
icon={<FilesIcon />}
title="No artifact selected"
description="Select an artifact to view its details"
/>
) : (
<div className="flex size-full max-w-(--container-width-sm) flex-col justify-center p-4 pt-8">
<header className="shrink-0">
<h2 className="text-lg font-medium">Artifacts</h2>
</header>
<main className="min-h-0 grow">
<ArtifactFileList
className="max-w-(--container-width-sm) p-4 pt-12"
files={thread.values.artifacts ?? []}
threadId={threadId}
/>
</main>
</div>
)}
</div>
)}
</div>
</ResizablePanel>
</ResizablePanelGroup>
);
};
export { ChatBox };
@@ -0,0 +1,3 @@
export * from "./chat-box";
export * from "./use-chat-mode";
export * from "./use-thread-chat";
@@ -0,0 +1,41 @@
import { useParams, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useRef } from "react";
import { usePromptInputController } from "@/components/ai-elements/prompt-input";
import { useI18n } from "@/core/i18n/hooks";
/**
* Hook to determine if the chat is in a specific mode based on URL parameters, and to set an initial prompt input value accordingly.
*/
export function useSpecificChatMode() {
const { t } = useI18n();
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
const searchParams = useSearchParams();
const promptInputController = usePromptInputController();
const inputInitialValue = useMemo(() => {
if (threadIdFromPath !== "new" || searchParams.get("mode") !== "skill") {
return undefined;
}
return t.inputBox.createSkillPrompt;
}, [threadIdFromPath, searchParams, t.inputBox.createSkillPrompt]);
const lastInitialValueRef = useRef<string | undefined>(undefined);
const setInputRef = useRef(promptInputController.textInput.setInput);
setInputRef.current = promptInputController.textInput.setInput;
useEffect(() => {
if (
inputInitialValue &&
inputInitialValue !== lastInitialValueRef.current
) {
lastInitialValueRef.current = inputInitialValue;
setTimeout(() => {
setInputRef.current(inputInitialValue);
const textarea = document.querySelector("textarea");
if (textarea) {
textarea.focus();
textarea.selectionStart = textarea.value.length;
textarea.selectionEnd = textarea.value.length;
}
}, 100);
}
}, [inputInitialValue]);
}
@@ -0,0 +1,43 @@
"use client";
import { useParams, usePathname, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { uuid } from "@/core/utils/uuid";
export function useThreadChat() {
const { thread_id: threadIdFromPath } = useParams<{ thread_id: string }>();
const pathname = usePathname();
const searchParams = useSearchParams();
const [threadId, setThreadId] = useState(() => {
return threadIdFromPath === "new" ? uuid() : threadIdFromPath;
});
const [isNewThread, setIsNewThread] = useState(
() => threadIdFromPath === "new",
);
useEffect(() => {
const onNewChatPath =
pathname.endsWith("/new") ||
(pathname === "/" && threadIdFromPath === "new");
if (onNewChatPath) {
setIsNewThread(true);
setThreadId(uuid());
return;
}
// Guard: after history.replaceState updates the URL from /chats/new to
// /chats/{UUID}, Next.js useParams may still return the stale "new" value
// because replaceState does not trigger router updates. Avoid propagating
// this invalid thread ID to downstream hooks (e.g. useStream), which would
// cause a 422 from LangGraph Server.
if (threadIdFromPath === "new") {
return;
}
setIsNewThread(false);
setThreadId(threadIdFromPath);
}, [pathname, threadIdFromPath]);
const isMock = searchParams.get("mock") === "true";
return { threadId, setThreadId, isNewThread, setIsNewThread, isMock };
}
@@ -0,0 +1,33 @@
import type { AnchorHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
import { CitationLink } from "./citation-link";
function isExternalUrl(href: string | undefined): boolean {
return !!href && /^https?:\/\//.test(href);
}
/** Link renderer for artifact markdown: citation: prefix → CitationLink, otherwise underlined text. */
export function ArtifactLink(props: AnchorHTMLAttributes<HTMLAnchorElement>) {
if (typeof props.children === "string") {
const match = /^citation:(.+)$/.exec(props.children);
if (match) {
const [, text] = match;
return <CitationLink {...props}>{text}</CitationLink>;
}
}
const { className, target, rel, ...rest } = props;
const external = isExternalUrl(props.href);
return (
<a
{...rest}
className={cn(
"text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors",
className,
)}
target={target ?? (external ? "_blank" : undefined)}
rel={rel ?? (external ? "noopener noreferrer" : undefined)}
/>
);
}
@@ -0,0 +1,82 @@
import { ExternalLinkIcon } from "lucide-react";
import type { ComponentProps } from "react";
import { Badge } from "@/components/ui/badge";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card";
import { cn } from "@/lib/utils";
export function CitationLink({
href,
children,
...props
}: ComponentProps<"a">) {
const domain = extractDomain(href ?? "");
// Priority: children > domain
const childrenText =
typeof children === "string"
? children.replace(/^citation:\s*/i, "")
: null;
const isGenericText = childrenText === "Source" || childrenText === "来源";
const displayText = (!isGenericText && childrenText) ?? domain;
return (
<HoverCard closeDelay={0} openDelay={0}>
<HoverCardTrigger asChild>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center"
onClick={(e) => e.stopPropagation()}
{...props}
>
<Badge
variant="secondary"
className="hover:bg-secondary/80 mx-0.5 cursor-pointer gap-1 rounded-full px-2 py-0.5 text-xs font-normal"
>
{displayText}
<ExternalLinkIcon className="size-3" />
</Badge>
</a>
</HoverCardTrigger>
<HoverCardContent className={cn("relative w-80 p-0", props.className)}>
<div className="p-3">
<div className="space-y-1">
{displayText && (
<h4 className="truncate text-sm leading-tight font-medium">
{displayText}
</h4>
)}
{href && (
<p className="text-muted-foreground truncate text-xs break-all">
{href}
</p>
)}
</div>
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary mt-2 inline-flex items-center gap-1 text-xs hover:underline"
>
Visit source
<ExternalLinkIcon className="size-3" />
</a>
</div>
</HoverCardContent>
</HoverCard>
);
}
function extractDomain(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./i, "");
} catch {
return url;
}
}
@@ -0,0 +1,114 @@
"use client";
import { css } from "@codemirror/lang-css";
import { html } from "@codemirror/lang-html";
import { javascript } from "@codemirror/lang-javascript";
import { json } from "@codemirror/lang-json";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { python } from "@codemirror/lang-python";
import { languages } from "@codemirror/language-data";
import { basicLightInit } from "@uiw/codemirror-theme-basic";
import { monokaiInit } from "@uiw/codemirror-theme-monokai";
import CodeMirror from "@uiw/react-codemirror";
import { useTheme } from "next-themes";
import { useMemo } from "react";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { useThread } from "./messages/context";
const customDarkTheme = monokaiInit({
settings: {
background: "transparent",
gutterBackground: "transparent",
gutterForeground: "#555",
gutterActiveForeground: "#fff",
fontSize: "var(--text-sm)",
},
});
const customLightTheme = basicLightInit({
settings: {
background: "transparent",
fontSize: "var(--text-sm)",
},
});
export function CodeEditor({
className,
placeholder,
value,
readonly,
disabled,
autoFocus,
settings,
}: {
className?: string;
placeholder?: string;
value: string;
readonly?: boolean;
disabled?: boolean;
autoFocus?: boolean;
settings?: unknown;
}) {
const {
thread: { isLoading },
} = useThread();
const { resolvedTheme } = useTheme();
const extensions = useMemo(() => {
return [
css(),
html(),
javascript({}),
json(),
markdown({
base: markdownLanguage,
codeLanguages: languages,
}),
python(),
];
}, []);
return (
<div
className={cn(
"flex cursor-text flex-col overflow-hidden rounded-md",
className,
)}
>
{isLoading ? (
<Textarea
className={cn(
"h-full overflow-auto font-mono [&_.cm-editor]:h-full [&_.cm-focused]:outline-none!",
"resize-none p-4! [&_.cm-line]:px-2! [&_.cm-line]:py-0!",
"border-none",
)}
readOnly
value={value}
/>
) : (
<CodeMirror
readOnly={readonly ?? disabled}
placeholder={placeholder}
className={cn(
"h-full overflow-auto font-mono [&_.cm-editor]:h-full [&_.cm-focused]:outline-none!",
"px-2 py-0! [&_.cm-line]:px-2! [&_.cm-line]:py-0!",
)}
theme={resolvedTheme === "dark" ? customDarkTheme : customLightTheme}
extensions={extensions}
basicSetup={{
foldGutter:
(settings as { foldGutter?: boolean })?.foldGutter ?? false,
highlightActiveLine: false,
highlightActiveLineGutter: false,
lineNumbers:
(settings as { lineNumbers?: boolean })?.lineNumbers ?? false,
}}
autoFocus={autoFocus}
value={value}
/>
)}
</div>
);
}
@@ -0,0 +1,134 @@
"use client";
import {
KeyboardIcon,
MessageSquarePlusIcon,
SettingsIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandShortcut,
} from "@/components/ui/command";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useI18n } from "@/core/i18n/hooks";
import { useGlobalShortcuts } from "@/hooks/use-global-shortcuts";
import { SettingsDialog } from "./settings";
export function CommandPalette() {
const { t } = useI18n();
const router = useRouter();
const [open, setOpen] = useState(false);
const [shortcutsOpen, setShortcutsOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [isMac, setIsMac] = useState(false);
const handleNewChat = useCallback(() => {
router.push("/workspace/chats/new");
setOpen(false);
}, [router]);
const handleOpenSettings = useCallback(() => {
setOpen(false);
setSettingsOpen(true);
}, []);
const handleShowShortcuts = useCallback(() => {
setOpen(false);
setShortcutsOpen(true);
}, []);
const shortcuts = useMemo(
() => [
{ key: "k", meta: true, action: () => setOpen((o) => !o) },
{ key: "n", meta: true, shift: true, action: handleNewChat },
{ key: ",", meta: true, action: handleOpenSettings },
{ key: "/", meta: true, action: handleShowShortcuts },
],
[handleNewChat, handleOpenSettings, handleShowShortcuts],
);
useGlobalShortcuts(shortcuts);
useEffect(() => {
setIsMac(navigator.userAgent.includes("Mac"));
}, []);
const metaKey = isMac ? "⌘" : "Ctrl+";
const shiftKey = isMac ? "⇧" : "Shift+";
return (
<>
<SettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} />
<CommandDialog open={open} onOpenChange={setOpen}>
<CommandInput placeholder={t.shortcuts.searchActions} />
<CommandList>
<CommandEmpty>{t.shortcuts.noResults}</CommandEmpty>
<CommandGroup heading={t.shortcuts.actions}>
<CommandItem onSelect={handleNewChat}>
<MessageSquarePlusIcon className="mr-2 h-4 w-4" />
{t.sidebar.newChat}
<CommandShortcut>
{metaKey}
{shiftKey}N
</CommandShortcut>
</CommandItem>
<CommandItem onSelect={handleOpenSettings}>
<SettingsIcon className="mr-2 h-4 w-4" />
{t.common.settings}
<CommandShortcut>{metaKey},</CommandShortcut>
</CommandItem>
<CommandItem onSelect={handleShowShortcuts}>
<KeyboardIcon className="mr-2 h-4 w-4" />
{t.shortcuts.keyboardShortcuts}
<CommandShortcut>{metaKey}/</CommandShortcut>
</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
<Dialog open={shortcutsOpen} onOpenChange={setShortcutsOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t.shortcuts.keyboardShortcuts}</DialogTitle>
<DialogDescription>
{t.shortcuts.keyboardShortcutsDescription}
</DialogDescription>
</DialogHeader>
<div className="space-y-3 text-sm">
{[
{ keys: `${metaKey}K`, label: t.shortcuts.openCommandPalette },
{ keys: `${metaKey}${shiftKey}N`, label: t.sidebar.newChat },
{ keys: `${metaKey}B`, label: t.shortcuts.toggleSidebar },
{ keys: `${metaKey},`, label: t.common.settings },
{
keys: `${metaKey}/`,
label: t.shortcuts.keyboardShortcuts,
},
].map(({ keys, label }) => (
<div key={keys} className="flex items-center justify-between">
<span className="text-muted-foreground">{label}</span>
<kbd className="bg-muted text-muted-foreground rounded px-2 py-0.5 font-mono text-xs">
{keys}
</kbd>
</div>
))}
</div>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,39 @@
import { CheckIcon, CopyIcon } from "lucide-react";
import { useCallback, useState, type ComponentProps } from "react";
import { Button } from "@/components/ui/button";
import { useI18n } from "@/core/i18n/hooks";
import { Tooltip } from "./tooltip";
export function CopyButton({
clipboardData,
...props
}: ComponentProps<typeof Button> & {
clipboardData: string;
}) {
const { t } = useI18n();
const [copied, setCopied] = useState(false);
const handleCopy = useCallback(() => {
void navigator.clipboard.writeText(clipboardData);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [clipboardData]);
return (
<Tooltip content={t.clipboard.copyToClipboard}>
<Button
size="icon-sm"
type="button"
variant="ghost"
onClick={handleCopy}
{...props}
>
{copied ? (
<CheckIcon className="text-green-500" size={12} />
) : (
<CopyIcon size={12} />
)}
</Button>
</Tooltip>
);
}
@@ -0,0 +1,81 @@
"use client";
import { Download, FileJson, FileText } from "lucide-react";
import { useCallback } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useI18n } from "@/core/i18n/hooks";
import {
exportThreadAsJSON,
exportThreadAsMarkdown,
} from "@/core/threads/export";
import type { AgentThread } from "@/core/threads/types";
import { useThread } from "./messages/context";
import { Tooltip } from "./tooltip";
export function ExportTrigger({ threadId }: { threadId: string }) {
const { t } = useI18n();
const { thread } = useThread();
const messages = thread.messages;
const handleExport = useCallback(
(format: "markdown" | "json") => {
if (messages.length === 0) {
toast.error(t.conversation.noMessages);
return;
}
const agentThread = {
thread_id: threadId,
updated_at: new Date().toISOString(),
values: thread.values,
} as AgentThread;
if (format === "markdown") {
exportThreadAsMarkdown(agentThread, messages);
} else {
exportThreadAsJSON(agentThread, messages);
}
toast.success(t.common.exportSuccess);
},
[messages, thread.values, threadId, t],
);
if (messages.length === 0) {
return null;
}
return (
<DropdownMenu>
<Tooltip content={t.common.export}>
<DropdownMenuTrigger asChild>
<Button
className="text-muted-foreground hover:text-foreground"
variant="ghost"
>
<Download />
{t.common.export}
</Button>
</DropdownMenuTrigger>
</Tooltip>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => handleExport("markdown")}>
<FileText className="text-muted-foreground" />
<span>{t.common.exportAsMarkdown}</span>
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => handleExport("json")}>
<FileJson className="text-muted-foreground" />
<span>{t.common.exportAsJSON}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -0,0 +1,29 @@
import { AnimatePresence, motion } from "motion/react";
import { cn } from "@/lib/utils";
export function FlipDisplay({
uniqueKey,
children,
className,
}: {
uniqueKey: string;
children: React.ReactNode;
className?: string;
}) {
return (
<div className={cn("relative overflow-hidden", className)}>
<AnimatePresence mode="wait">
<motion.div
key={uniqueKey}
initial={{ y: 8, opacity: 0 }}
animate={{ y: 2, opacity: 1 }}
exit={{ y: -8, opacity: 0 }}
transition={{ duration: 0.25, ease: [0.4, 0, 0.2, 1] }}
>
{children}
</motion.div>
</AnimatePresence>
</div>
);
}
@@ -0,0 +1,14 @@
export function GithubIcon(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
height={32}
aria-hidden="true"
viewBox="0 0 24 24"
width={32}
fill="currentColor"
{...props}
>
<path d="M12 1C5.923 1 1 5.923 1 12c0 4.867 3.149 8.979 7.521 10.436.55.096.756-.233.756-.522 0-.262-.013-1.128-.013-2.049-2.764.509-3.479-.674-3.699-1.292-.124-.317-.66-1.293-1.127-1.554-.385-.207-.936-.715-.014-.729.866-.014 1.485.797 1.691 1.128.99 1.663 2.571 1.196 3.204.907.096-.715.385-1.196.701-1.471-2.448-.275-5.005-1.224-5.005-5.432 0-1.196.426-2.186 1.128-2.956-.111-.275-.496-1.402.11-2.915 0 0 .921-.288 3.024 1.128a10.193 10.193 0 0 1 2.75-.371c.936 0 1.871.123 2.75.371 2.104-1.43 3.025-1.128 3.025-1.128.605 1.513.221 2.64.111 2.915.701.77 1.127 1.747 1.127 2.956 0 4.222-2.571 5.157-5.019 5.432.399.344.743 1.004.743 2.035 0 1.471-.014 2.654-.014 3.025 0 .289.206.632.756.522C19.851 20.979 23 16.854 23 12c0-6.077-4.922-11-11-11Z"></path>
</svg>
);
}
@@ -0,0 +1,962 @@
"use client";
import type { ChatStatus } from "ai";
import {
CheckIcon,
GraduationCapIcon,
LightbulbIcon,
PaperclipIcon,
PlusIcon,
SparklesIcon,
RocketIcon,
XIcon,
ZapIcon,
} from "lucide-react";
import { useSearchParams } from "next/navigation";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ComponentProps,
} from "react";
import {
PromptInput,
PromptInputActionMenu,
PromptInputActionMenuContent,
PromptInputActionMenuItem,
PromptInputActionMenuTrigger,
PromptInputAttachment,
PromptInputAttachments,
PromptInputBody,
PromptInputButton,
PromptInputFooter,
PromptInputSubmit,
PromptInputTextarea,
PromptInputTools,
usePromptInputAttachments,
usePromptInputController,
type PromptInputMessage,
} from "@/components/ai-elements/prompt-input";
import { Button } from "@/components/ui/button";
import { ConfettiButton } from "@/components/ui/confetti-button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import { useI18n } from "@/core/i18n/hooks";
import { useModels } from "@/core/models/hooks";
import type { AgentThreadContext } from "@/core/threads";
import { textOfMessage } from "@/core/threads/utils";
import { cn } from "@/lib/utils";
import {
ModelSelector,
ModelSelectorContent,
ModelSelectorInput,
ModelSelectorItem,
ModelSelectorList,
ModelSelectorName,
ModelSelectorTrigger,
} from "../ai-elements/model-selector";
import { Suggestion, Suggestions } from "../ai-elements/suggestion";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { useThread } from "./messages/context";
import { ModeHoverGuide } from "./mode-hover-guide";
import { Tooltip } from "./tooltip";
type InputMode = "flash" | "thinking" | "pro" | "ultra";
function getResolvedMode(
mode: InputMode | undefined,
supportsThinking: boolean,
): InputMode {
if (!supportsThinking && mode !== "flash") {
return "flash";
}
if (mode) {
return mode;
}
return supportsThinking ? "pro" : "flash";
}
export function InputBox({
className,
disabled,
autoFocus,
status = "ready",
context,
extraHeader,
isNewThread,
threadId,
initialValue,
onContextChange,
onFollowupsVisibilityChange,
onSubmit,
onStop,
...props
}: Omit<ComponentProps<typeof PromptInput>, "onSubmit"> & {
assistantId?: string | null;
status?: ChatStatus;
disabled?: boolean;
context: Omit<
AgentThreadContext,
"thread_id" | "is_plan_mode" | "thinking_enabled" | "subagent_enabled"
> & {
mode: "flash" | "thinking" | "pro" | "ultra" | undefined;
reasoning_effort?: "minimal" | "low" | "medium" | "high";
};
extraHeader?: React.ReactNode;
isNewThread?: boolean;
threadId: string;
initialValue?: string;
onContextChange?: (
context: Omit<
AgentThreadContext,
"thread_id" | "is_plan_mode" | "thinking_enabled" | "subagent_enabled"
> & {
mode: "flash" | "thinking" | "pro" | "ultra" | undefined;
reasoning_effort?: "minimal" | "low" | "medium" | "high";
},
) => void;
onFollowupsVisibilityChange?: (visible: boolean) => void;
onSubmit?: (message: PromptInputMessage) => void;
onStop?: () => void;
}) {
const { t } = useI18n();
const searchParams = useSearchParams();
const [modelDialogOpen, setModelDialogOpen] = useState(false);
const { models } = useModels();
const { thread, isMock } = useThread();
const { textInput } = usePromptInputController();
const promptRootRef = useRef<HTMLDivElement | null>(null);
const [followups, setFollowups] = useState<string[]>([]);
const [followupsHidden, setFollowupsHidden] = useState(false);
const [followupsLoading, setFollowupsLoading] = useState(false);
const lastGeneratedForAiIdRef = useRef<string | null>(null);
const wasStreamingRef = useRef(false);
const [confirmOpen, setConfirmOpen] = useState(false);
const [pendingSuggestion, setPendingSuggestion] = useState<string | null>(
null,
);
useEffect(() => {
if (models.length === 0) {
return;
}
const currentModel = models.find((m) => m.name === context.model_name);
const fallbackModel = currentModel ?? models[0]!;
const supportsThinking = fallbackModel.supports_thinking ?? false;
const nextModelName = fallbackModel.name;
const nextMode = getResolvedMode(context.mode, supportsThinking);
if (context.model_name === nextModelName && context.mode === nextMode) {
return;
}
onContextChange?.({
...context,
model_name: nextModelName,
mode: nextMode,
});
}, [context, models, onContextChange]);
const selectedModel = useMemo(() => {
if (models.length === 0) {
return undefined;
}
return models.find((m) => m.name === context.model_name) ?? models[0];
}, [context.model_name, models]);
const resolvedModelName = selectedModel?.name;
const supportThinking = useMemo(
() => selectedModel?.supports_thinking ?? false,
[selectedModel],
);
const supportReasoningEffort = useMemo(
() => selectedModel?.supports_reasoning_effort ?? false,
[selectedModel],
);
const handleModelSelect = useCallback(
(model_name: string) => {
const model = models.find((m) => m.name === model_name);
if (!model) {
return;
}
onContextChange?.({
...context,
model_name,
mode: getResolvedMode(context.mode, model.supports_thinking ?? false),
reasoning_effort: context.reasoning_effort,
});
setModelDialogOpen(false);
},
[onContextChange, context, models],
);
const handleModeSelect = useCallback(
(mode: InputMode) => {
onContextChange?.({
...context,
mode: getResolvedMode(mode, supportThinking),
reasoning_effort:
mode === "ultra"
? "high"
: mode === "pro"
? "medium"
: mode === "thinking"
? "low"
: "minimal",
});
},
[onContextChange, context, supportThinking],
);
const handleReasoningEffortSelect = useCallback(
(effort: "minimal" | "low" | "medium" | "high") => {
onContextChange?.({
...context,
reasoning_effort: effort,
});
},
[onContextChange, context],
);
const handleSubmit = useCallback(
async (message: PromptInputMessage) => {
if (status === "streaming") {
onStop?.();
return;
}
if (!message.text) {
return;
}
setFollowups([]);
setFollowupsHidden(false);
setFollowupsLoading(false);
// Guard against submitting before the initial model auto-selection
// effect has flushed thread settings to storage/state.
if (resolvedModelName && context.model_name !== resolvedModelName) {
onContextChange?.({
...context,
model_name: resolvedModelName,
mode: getResolvedMode(
context.mode,
selectedModel?.supports_thinking ?? false,
),
});
setTimeout(() => onSubmit?.(message), 0);
return;
}
onSubmit?.(message);
},
[
context,
onContextChange,
onSubmit,
onStop,
resolvedModelName,
selectedModel?.supports_thinking,
status,
],
);
const requestFormSubmit = useCallback(() => {
const form = promptRootRef.current?.querySelector("form");
form?.requestSubmit();
}, []);
const handleFollowupClick = useCallback(
(suggestion: string) => {
if (status === "streaming") {
return;
}
const current = (textInput.value ?? "").trim();
if (current) {
setPendingSuggestion(suggestion);
setConfirmOpen(true);
return;
}
textInput.setInput(suggestion);
setFollowupsHidden(true);
setTimeout(() => requestFormSubmit(), 0);
},
[requestFormSubmit, status, textInput],
);
const confirmReplaceAndSend = useCallback(() => {
if (!pendingSuggestion) {
setConfirmOpen(false);
return;
}
textInput.setInput(pendingSuggestion);
setFollowupsHidden(true);
setConfirmOpen(false);
setPendingSuggestion(null);
setTimeout(() => requestFormSubmit(), 0);
}, [pendingSuggestion, requestFormSubmit, textInput]);
const confirmAppendAndSend = useCallback(() => {
if (!pendingSuggestion) {
setConfirmOpen(false);
return;
}
const current = (textInput.value ?? "").trim();
const next = current
? `${current}\n${pendingSuggestion}`
: pendingSuggestion;
textInput.setInput(next);
setFollowupsHidden(true);
setConfirmOpen(false);
setPendingSuggestion(null);
setTimeout(() => requestFormSubmit(), 0);
}, [pendingSuggestion, requestFormSubmit, textInput]);
const showFollowups =
!disabled &&
!isNewThread &&
!followupsHidden &&
(followupsLoading || followups.length > 0);
const followupsVisibilityChangeRef = useRef(onFollowupsVisibilityChange);
useEffect(() => {
followupsVisibilityChangeRef.current = onFollowupsVisibilityChange;
}, [onFollowupsVisibilityChange]);
useEffect(() => {
followupsVisibilityChangeRef.current?.(showFollowups);
}, [showFollowups]);
useEffect(() => {
return () => followupsVisibilityChangeRef.current?.(false);
}, []);
useEffect(() => {
const streaming = status === "streaming";
const wasStreaming = wasStreamingRef.current;
wasStreamingRef.current = streaming;
if (!wasStreaming || streaming) {
return;
}
if (disabled || isMock) {
return;
}
const lastAi = [...thread.messages].reverse().find((m) => m.type === "ai");
const lastAiId = lastAi?.id ?? null;
if (!lastAiId || lastAiId === lastGeneratedForAiIdRef.current) {
return;
}
lastGeneratedForAiIdRef.current = lastAiId;
const recent = thread.messages
.filter((m) => m.type === "human" || m.type === "ai")
.map((m) => {
const role = m.type === "human" ? "user" : "assistant";
const content = textOfMessage(m) ?? "";
return { role, content };
})
.filter((m) => m.content.trim().length > 0)
.slice(-6);
if (recent.length === 0) {
return;
}
const controller = new AbortController();
setFollowupsHidden(false);
setFollowupsLoading(true);
setFollowups([]);
apiFetch(`${getBackendBaseURL()}/api/threads/${threadId}/suggestions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: recent,
n: 3,
model_name: context.model_name ?? undefined,
}),
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok) {
return { suggestions: [] as string[] };
}
return (await res.json()) as { suggestions?: string[] };
})
.then((data) => {
const suggestions = (data.suggestions ?? [])
.map((s) => (typeof s === "string" ? s.trim() : ""))
.filter((s) => s.length > 0)
.slice(0, 5);
setFollowups(suggestions);
})
.catch(() => {
setFollowups([]);
})
.finally(() => {
setFollowupsLoading(false);
});
return () => controller.abort();
}, [context.model_name, disabled, isMock, status, thread.messages, threadId]);
return (
<div ref={promptRootRef} className="relative flex flex-col gap-4">
{showFollowups && (
<div className="flex items-center justify-center pb-2">
<div className="flex items-center gap-2">
{followupsLoading ? (
<div className="text-muted-foreground bg-background/80 rounded-full border px-4 py-2 text-xs backdrop-blur-sm">
{t.inputBox.followupLoading}
</div>
) : (
<Suggestions className="min-h-16 w-fit items-start">
{followups.map((s) => (
<Suggestion
key={s}
suggestion={s}
onClick={() => handleFollowupClick(s)}
/>
))}
<Button
aria-label={t.common.close}
className="text-muted-foreground cursor-pointer rounded-full px-3 text-xs font-normal"
variant="outline"
size="sm"
type="button"
onClick={() => setFollowupsHidden(true)}
>
<XIcon className="size-4" />
</Button>
</Suggestions>
)}
</div>
</div>
)}
<PromptInput
className={cn(
"rounded-[1.85rem] border border-[#eadfce] bg-white shadow-[0_24px_70px_-34px_rgba(120,83,42,0.32)] ring-1 ring-[#f6efe5] transition-all duration-300 ease-out *:data-[slot='input-group']:rounded-[1.85rem]",
className,
)}
disabled={disabled}
globalDrop
multiple
onSubmit={handleSubmit}
{...props}
>
{extraHeader && (
<div className="absolute top-0 right-0 left-0 z-10">
<div className="absolute right-0 bottom-0 left-0 flex items-center justify-center">
{extraHeader}
</div>
</div>
)}
<PromptInputAttachments>
{(attachment) => <PromptInputAttachment data={attachment} />}
</PromptInputAttachments>
<PromptInputBody className="absolute top-0 right-0 left-0 z-3">
<PromptInputTextarea
className={cn(
"size-full px-2 py-1 text-[15px] leading-7 placeholder:text-[#b7ab9a]",
)}
disabled={disabled}
placeholder={t.inputBox.placeholder}
autoFocus={autoFocus}
defaultValue={initialValue}
/>
</PromptInputBody>
<PromptInputFooter className="flex items-center border-t border-[#f4ede4] px-2 pt-2.5 pb-1.5">
<PromptInputTools className="gap-1.5">
{/* TODO: Add more connectors here
<PromptInputActionMenu>
<PromptInputActionMenuTrigger className="px-2!" />
<PromptInputActionMenuContent>
<PromptInputActionAddAttachments
label={t.inputBox.addAttachments}
/>
</PromptInputActionMenuContent>
</PromptInputActionMenu> */}
<AddAttachmentsButton className="rounded-full border border-[#eee3d5] bg-[#fffaf5] px-2.5! shadow-none hover:bg-white" />
<PromptInputActionMenu>
<ModeHoverGuide
mode={
context.mode === "flash" ||
context.mode === "thinking" ||
context.mode === "pro" ||
context.mode === "ultra"
? context.mode
: "flash"
}
>
<PromptInputActionMenuTrigger className="gap-1.5! rounded-full border border-[#eee3d5] bg-[#fffaf5] px-3! text-[#7e6a57] shadow-none hover:bg-white">
<div>
{context.mode === "flash" && <ZapIcon className="size-3" />}
{context.mode === "thinking" && (
<LightbulbIcon className="size-3" />
)}
{context.mode === "pro" && (
<GraduationCapIcon className="size-3" />
)}
{context.mode === "ultra" && (
<RocketIcon className="size-3 text-[#dabb5e]" />
)}
</div>
<div
className={cn(
"text-xs font-normal",
context.mode === "ultra" ? "golden-text" : "",
)}
>
{(context.mode === "flash" && t.inputBox.flashMode) ||
(context.mode === "thinking" &&
t.inputBox.reasoningMode) ||
(context.mode === "pro" && t.inputBox.proMode) ||
(context.mode === "ultra" && t.inputBox.ultraMode)}
</div>
</PromptInputActionMenuTrigger>
</ModeHoverGuide>
<PromptInputActionMenuContent className="w-80">
<DropdownMenuGroup>
<DropdownMenuLabel className="text-muted-foreground text-xs">
{t.inputBox.mode}
</DropdownMenuLabel>
<PromptInputActionMenu>
<PromptInputActionMenuItem
className={cn(
context.mode === "flash"
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleModeSelect("flash")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
<ZapIcon
className={cn(
"mr-2 size-4",
context.mode === "flash" &&
"text-accent-foreground",
)}
/>
{t.inputBox.flashMode}
</div>
<div className="pl-7 text-xs">
{t.inputBox.flashModeDescription}
</div>
</div>
{context.mode === "flash" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
{supportThinking && (
<PromptInputActionMenuItem
className={cn(
context.mode === "thinking"
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleModeSelect("thinking")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
<LightbulbIcon
className={cn(
"mr-2 size-4",
context.mode === "thinking" &&
"text-accent-foreground",
)}
/>
{t.inputBox.reasoningMode}
</div>
<div className="pl-7 text-xs">
{t.inputBox.reasoningModeDescription}
</div>
</div>
{context.mode === "thinking" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
)}
<PromptInputActionMenuItem
className={cn(
context.mode === "pro"
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleModeSelect("pro")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
<GraduationCapIcon
className={cn(
"mr-2 size-4",
context.mode === "pro" &&
"text-accent-foreground",
)}
/>
{t.inputBox.proMode}
</div>
<div className="pl-7 text-xs">
{t.inputBox.proModeDescription}
</div>
</div>
{context.mode === "pro" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
<PromptInputActionMenuItem
className={cn(
context.mode === "ultra"
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleModeSelect("ultra")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
<RocketIcon
className={cn(
"mr-2 size-4",
context.mode === "ultra" && "text-[#dabb5e]",
)}
/>
<div
className={cn(
context.mode === "ultra" && "golden-text",
)}
>
{t.inputBox.ultraMode}
</div>
</div>
<div className="pl-7 text-xs">
{t.inputBox.ultraModeDescription}
</div>
</div>
{context.mode === "ultra" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
</PromptInputActionMenu>
</DropdownMenuGroup>
</PromptInputActionMenuContent>
</PromptInputActionMenu>
{supportReasoningEffort && context.mode !== "flash" && (
<PromptInputActionMenu>
<PromptInputActionMenuTrigger className="gap-1.5! rounded-full border border-[#eee3d5] bg-[#fffaf5] px-3! text-[#7e6a57] shadow-none hover:bg-white">
<div className="text-xs font-normal">
{t.inputBox.reasoningEffort}:
{context.reasoning_effort === "minimal" &&
" " + t.inputBox.reasoningEffortMinimal}
{context.reasoning_effort === "low" &&
" " + t.inputBox.reasoningEffortLow}
{context.reasoning_effort === "medium" &&
" " + t.inputBox.reasoningEffortMedium}
{context.reasoning_effort === "high" &&
" " + t.inputBox.reasoningEffortHigh}
</div>
</PromptInputActionMenuTrigger>
<PromptInputActionMenuContent className="w-70">
<DropdownMenuGroup>
<DropdownMenuLabel className="text-muted-foreground text-xs">
{t.inputBox.reasoningEffort}
</DropdownMenuLabel>
<PromptInputActionMenu>
<PromptInputActionMenuItem
className={cn(
context.reasoning_effort === "minimal"
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleReasoningEffortSelect("minimal")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
{t.inputBox.reasoningEffortMinimal}
</div>
<div className="pl-2 text-xs">
{t.inputBox.reasoningEffortMinimalDescription}
</div>
</div>
{context.reasoning_effort === "minimal" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
<PromptInputActionMenuItem
className={cn(
context.reasoning_effort === "low"
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleReasoningEffortSelect("low")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
{t.inputBox.reasoningEffortLow}
</div>
<div className="pl-2 text-xs">
{t.inputBox.reasoningEffortLowDescription}
</div>
</div>
{context.reasoning_effort === "low" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
<PromptInputActionMenuItem
className={cn(
context.reasoning_effort === "medium" ||
!context.reasoning_effort
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleReasoningEffortSelect("medium")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
{t.inputBox.reasoningEffortMedium}
</div>
<div className="pl-2 text-xs">
{t.inputBox.reasoningEffortMediumDescription}
</div>
</div>
{context.reasoning_effort === "medium" ||
!context.reasoning_effort ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
<PromptInputActionMenuItem
className={cn(
context.reasoning_effort === "high"
? "text-accent-foreground"
: "text-muted-foreground/65",
)}
onSelect={() => handleReasoningEffortSelect("high")}
>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1 font-bold">
{t.inputBox.reasoningEffortHigh}
</div>
<div className="pl-2 text-xs">
{t.inputBox.reasoningEffortHighDescription}
</div>
</div>
{context.reasoning_effort === "high" ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</PromptInputActionMenuItem>
</PromptInputActionMenu>
</DropdownMenuGroup>
</PromptInputActionMenuContent>
</PromptInputActionMenu>
)}
</PromptInputTools>
<PromptInputTools className="gap-1.5">
<ModelSelector
open={modelDialogOpen}
onOpenChange={setModelDialogOpen}
>
<ModelSelectorTrigger asChild>
<PromptInputButton className="rounded-full border border-[#eee3d5] bg-[#fffaf5] px-3 shadow-none hover:bg-white">
<div className="flex min-w-0 flex-col items-start text-left">
<ModelSelectorName className="text-xs font-normal">
{selectedModel?.display_name}
</ModelSelectorName>
</div>
</PromptInputButton>
</ModelSelectorTrigger>
<ModelSelectorContent>
<ModelSelectorInput placeholder={t.inputBox.searchModels} />
<ModelSelectorList>
{models.map((m) => (
<ModelSelectorItem
key={m.name}
value={m.name}
onSelect={() => handleModelSelect(m.name)}
>
<div className="flex min-w-0 flex-1 flex-col">
<ModelSelectorName>{m.display_name}</ModelSelectorName>
<span className="text-muted-foreground truncate text-[10px]">
{m.model}
</span>
</div>
{m.name === context.model_name ? (
<CheckIcon className="ml-auto size-4" />
) : (
<div className="ml-auto size-4" />
)}
</ModelSelectorItem>
))}
</ModelSelectorList>
</ModelSelectorContent>
</ModelSelector>
<PromptInputSubmit
className="rounded-full border-[#e7d9c7] bg-white shadow-[0_10px_24px_-18px_rgba(120,83,42,0.34)]"
disabled={disabled}
variant="outline"
status={status}
/>
</PromptInputTools>
</PromptInputFooter>
{!isNewThread && (
<div className="absolute right-0 -bottom-[17px] left-0 z-0 h-4 bg-[#fffdfa]"></div>
)}
</PromptInput>
{isNewThread && searchParams.get("mode") !== "skill" && (
<div className="flex items-center justify-center pt-2">
<SuggestionList />
</div>
)}
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t.inputBox.followupConfirmTitle}</DialogTitle>
<DialogDescription>
{t.inputBox.followupConfirmDescription}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setConfirmOpen(false)}>
{t.common.cancel}
</Button>
<Button variant="secondary" onClick={confirmAppendAndSend}>
{t.inputBox.followupConfirmAppend}
</Button>
<Button onClick={confirmReplaceAndSend}>
{t.inputBox.followupConfirmReplace}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
function SuggestionList() {
const { t } = useI18n();
const { textInput } = usePromptInputController();
const handleSuggestionClick = useCallback(
(prompt: string | undefined) => {
if (!prompt) return;
textInput.setInput(prompt);
setTimeout(() => {
const textarea = document.querySelector<HTMLTextAreaElement>(
"textarea[name='message']",
);
if (textarea) {
const selStart = prompt.indexOf("[");
const selEnd = prompt.indexOf("]");
if (selStart !== -1 && selEnd !== -1) {
textarea.setSelectionRange(selStart, selEnd + 1);
textarea.focus();
}
}
}, 500);
},
[textInput],
);
return (
<Suggestions className="min-h-16 w-fit items-start">
<ConfettiButton
className="text-muted-foreground cursor-pointer rounded-full px-4 text-xs font-normal"
variant="outline"
size="sm"
onClick={() => handleSuggestionClick(t.inputBox.surpriseMePrompt)}
>
<SparklesIcon className="size-4" /> {t.inputBox.surpriseMe}
</ConfettiButton>
{t.inputBox.suggestions.map((suggestion) => (
<Suggestion
key={suggestion.suggestion}
icon={suggestion.icon}
suggestion={suggestion.suggestion}
onClick={() => handleSuggestionClick(suggestion.prompt)}
/>
))}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Suggestion icon={PlusIcon} suggestion={t.common.create} />
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuGroup>
{t.inputBox.suggestionsCreate.map((suggestion, index) =>
"type" in suggestion && suggestion.type === "separator" ? (
<DropdownMenuSeparator key={index} />
) : (
!("type" in suggestion) && (
<DropdownMenuItem
key={suggestion.suggestion}
onClick={() => handleSuggestionClick(suggestion.prompt)}
>
{suggestion.icon && <suggestion.icon className="size-4" />}
{suggestion.suggestion}
</DropdownMenuItem>
)
),
)}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</Suggestions>
);
}
function AddAttachmentsButton({ className }: { className?: string }) {
const { t } = useI18n();
const attachments = usePromptInputAttachments();
return (
<Tooltip content={t.inputBox.addAttachments}>
<PromptInputButton
className={cn("px-2!", className)}
onClick={() => attachments.openFileDialog()}
>
<PaperclipIcon className="size-3" />
</PromptInputButton>
</Tooltip>
);
}
@@ -0,0 +1,21 @@
import type { BaseStream } from "@langchain/langgraph-sdk/react";
import { createContext, useContext } from "react";
import type { AgentThreadState } from "@/core/threads";
export interface ThreadContextType {
thread: BaseStream<AgentThreadState>;
isMock?: boolean;
}
export const ThreadContext = createContext<ThreadContextType | undefined>(
undefined,
);
export function useThread() {
const context = useContext(ThreadContext);
if (context === undefined) {
throw new Error("useThread must be used within a ThreadContext");
}
return context;
}
@@ -0,0 +1 @@
export * from "./message-list";
@@ -0,0 +1,76 @@
"use client";
import { useMemo } from "react";
import type { AnchorHTMLAttributes } from "react";
import {
MessageResponse,
type MessageResponseProps,
} from "@/components/ai-elements/message";
import { streamdownPlugins } from "@/core/streamdown";
import { cn } from "@/lib/utils";
import { CitationLink } from "../citations/citation-link";
function isExternalUrl(href: string | undefined): boolean {
return !!href && /^https?:\/\//.test(href);
}
export type MarkdownContentProps = {
content: string;
isLoading: boolean;
rehypePlugins: MessageResponseProps["rehypePlugins"];
className?: string;
remarkPlugins?: MessageResponseProps["remarkPlugins"];
components?: MessageResponseProps["components"];
};
/** Renders markdown content. */
export function MarkdownContent({
content,
rehypePlugins,
className,
remarkPlugins = streamdownPlugins.remarkPlugins,
components: componentsFromProps,
}: MarkdownContentProps) {
const components = useMemo(() => {
return {
a: (props: AnchorHTMLAttributes<HTMLAnchorElement>) => {
if (typeof props.children === "string") {
const match = /^citation:(.+)$/.exec(props.children);
if (match) {
const [, text] = match;
return <CitationLink {...props}>{text}</CitationLink>;
}
}
const { className, target, rel, ...rest } = props;
const external = isExternalUrl(props.href);
return (
<a
{...rest}
className={cn(
"text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors",
className,
)}
target={target ?? (external ? "_blank" : undefined)}
rel={rel ?? (external ? "noopener noreferrer" : undefined)}
/>
);
},
...componentsFromProps,
};
}, [componentsFromProps]);
if (!content) return null;
return (
<MessageResponse
className={className}
remarkPlugins={remarkPlugins}
rehypePlugins={rehypePlugins}
components={components}
>
{content}
</MessageResponse>
);
}
@@ -0,0 +1,486 @@
import type { Message } from "@langchain/langgraph-sdk";
import {
BookOpenTextIcon,
ChevronUp,
FolderOpenIcon,
GlobeIcon,
LightbulbIcon,
ListTodoIcon,
MessageCircleQuestionMarkIcon,
NotebookPenIcon,
SearchIcon,
SquareTerminalIcon,
WrenchIcon,
} from "lucide-react";
import { useMemo, useState } from "react";
import {
ChainOfThought,
ChainOfThoughtContent,
ChainOfThoughtSearchResult,
ChainOfThoughtSearchResults,
ChainOfThoughtStep,
} from "@/components/ai-elements/chain-of-thought";
import { CodeBlock } from "@/components/ai-elements/code-block";
import { Button } from "@/components/ui/button";
import { useI18n } from "@/core/i18n/hooks";
import {
extractReasoningContentFromMessage,
findToolCallResult,
} from "@/core/messages/utils";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { extractTitleFromMarkdown } from "@/core/utils/markdown";
import { env } from "@/env";
import { cn } from "@/lib/utils";
import { useArtifacts } from "../artifacts";
import { FlipDisplay } from "../flip-display";
import { Tooltip } from "../tooltip";
import { MarkdownContent } from "./markdown-content";
export function MessageGroup({
className,
messages,
isLoading = false,
}: {
className?: string;
messages: Message[];
isLoading?: boolean;
}) {
const { t } = useI18n();
const [showAbove, setShowAbove] = useState(
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true",
);
const [showLastThinking, setShowLastThinking] = useState(
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true",
);
const steps = useMemo(() => convertToSteps(messages), [messages]);
const lastToolCallStep = useMemo(() => {
const filteredSteps = steps.filter((step) => step.type === "toolCall");
return filteredSteps[filteredSteps.length - 1];
}, [steps]);
const aboveLastToolCallSteps = useMemo(() => {
if (lastToolCallStep) {
const index = steps.indexOf(lastToolCallStep);
return steps.slice(0, index);
}
return [];
}, [lastToolCallStep, steps]);
const lastReasoningStep = useMemo(() => {
if (lastToolCallStep) {
const index = steps.indexOf(lastToolCallStep);
return steps.slice(index + 1).find((step) => step.type === "reasoning");
} else {
const filteredSteps = steps.filter((step) => step.type === "reasoning");
return filteredSteps[filteredSteps.length - 1];
}
}, [lastToolCallStep, steps]);
const rehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
return (
<ChainOfThought
className={cn("w-full gap-2 rounded-lg border p-0.5", className)}
open={true}
>
{aboveLastToolCallSteps.length > 0 && (
<Button
key="above"
className="w-full items-start justify-start text-left"
variant="ghost"
onClick={() => setShowAbove(!showAbove)}
>
<ChainOfThoughtStep
label={
<span className="opacity-60">
{showAbove
? t.toolCalls.lessSteps
: t.toolCalls.moreSteps(aboveLastToolCallSteps.length)}
</span>
}
icon={
<ChevronUp
className={cn(
"size-4 opacity-60 transition-transform duration-200",
showAbove ? "rotate-180" : "",
)}
/>
}
></ChainOfThoughtStep>
</Button>
)}
{lastToolCallStep && (
<ChainOfThoughtContent className="px-4 pb-2">
{showAbove &&
aboveLastToolCallSteps.map((step) =>
step.type === "reasoning" ? (
<ChainOfThoughtStep
key={step.id}
label={
<MarkdownContent
content={step.reasoning ?? ""}
isLoading={isLoading}
rehypePlugins={rehypePlugins}
/>
}
></ChainOfThoughtStep>
) : (
<ToolCall key={step.id} {...step} isLoading={isLoading} />
),
)}
{lastToolCallStep && (
<FlipDisplay uniqueKey={lastToolCallStep.id ?? ""}>
<ToolCall
key={lastToolCallStep.id}
{...lastToolCallStep}
isLast={true}
isLoading={isLoading}
/>
</FlipDisplay>
)}
</ChainOfThoughtContent>
)}
{lastReasoningStep && (
<>
<Button
key={lastReasoningStep.id}
className="w-full items-start justify-start text-left"
variant="ghost"
onClick={() => setShowLastThinking(!showLastThinking)}
>
<div className="flex w-full items-center justify-between">
<ChainOfThoughtStep
className="font-normal"
label={t.common.thinking}
icon={LightbulbIcon}
></ChainOfThoughtStep>
<div>
<ChevronUp
className={cn(
"text-muted-foreground size-4",
showLastThinking ? "" : "rotate-180",
)}
/>
</div>
</div>
</Button>
{showLastThinking && (
<ChainOfThoughtContent className="px-4 pb-2">
<ChainOfThoughtStep
key={lastReasoningStep.id}
label={
<MarkdownContent
content={lastReasoningStep.reasoning ?? ""}
isLoading={isLoading}
rehypePlugins={rehypePlugins}
/>
}
></ChainOfThoughtStep>
</ChainOfThoughtContent>
)}
</>
)}
</ChainOfThought>
);
}
function ToolCall({
id,
messageId,
name,
args,
result,
isLast = false,
isLoading = false,
}: {
id?: string;
messageId?: string;
name: string;
args: Record<string, unknown>;
result?: string | Record<string, unknown>;
isLast?: boolean;
isLoading?: boolean;
}) {
const { t } = useI18n();
const { setOpen, autoOpen, autoSelect, selectedArtifact, select } =
useArtifacts();
if (name === "web_search") {
let label: React.ReactNode = t.toolCalls.searchForRelatedInfo;
if (typeof args.query === "string") {
label = t.toolCalls.searchOnWebFor(args.query);
}
return (
<ChainOfThoughtStep key={id} label={label} icon={SearchIcon}>
{Array.isArray(result) && (
<ChainOfThoughtSearchResults>
{result.map((item) => (
<ChainOfThoughtSearchResult key={item.url}>
<a href={item.url} target="_blank" rel="noopener noreferrer">
{item.title}
</a>
</ChainOfThoughtSearchResult>
))}
</ChainOfThoughtSearchResults>
)}
</ChainOfThoughtStep>
);
} else if (name === "image_search") {
let label: React.ReactNode = t.toolCalls.searchForRelatedImages;
if (typeof args.query === "string") {
label = t.toolCalls.searchForRelatedImagesFor(args.query);
}
const results = (
result as {
results: {
source_url: string;
thumbnail_url: string;
image_url: string;
title: string;
}[];
}
)?.results;
return (
<ChainOfThoughtStep key={id} label={label} icon={SearchIcon}>
{Array.isArray(results) && (
<ChainOfThoughtSearchResults>
{Array.isArray(results) &&
results.map((item) => (
<Tooltip key={item.image_url} content={item.title}>
<a
className="size-24 overflow-hidden rounded-lg object-cover"
href={item.source_url}
target="_blank"
rel="noopener noreferrer"
>
<div className="bg-accent size-24">
<img
className="size-full object-cover"
src={item.thumbnail_url}
alt={item.title}
width={100}
height={100}
/>
</div>
</a>
</Tooltip>
))}
</ChainOfThoughtSearchResults>
)}
</ChainOfThoughtStep>
);
} else if (name === "web_fetch") {
const url = (args as { url: string })?.url;
let title = url;
if (typeof result === "string") {
const potentialTitle = extractTitleFromMarkdown(result);
if (potentialTitle && potentialTitle.toLowerCase() !== "untitled") {
title = potentialTitle;
}
}
return (
<ChainOfThoughtStep
key={id}
label={t.toolCalls.viewWebPage}
icon={GlobeIcon}
>
<ChainOfThoughtSearchResult>
{url && (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="cursor-pointer"
>
{title}
</a>
)}
</ChainOfThoughtSearchResult>
</ChainOfThoughtStep>
);
} else if (name === "ls") {
let description: string | undefined = (args as { description: string })
?.description;
if (!description) {
description = t.toolCalls.listFolder;
}
const path: string | undefined = (args as { path: string })?.path;
return (
<ChainOfThoughtStep key={id} label={description} icon={FolderOpenIcon}>
{path && (
<ChainOfThoughtSearchResult className="cursor-pointer">
{path}
</ChainOfThoughtSearchResult>
)}
</ChainOfThoughtStep>
);
} else if (name === "read_file") {
let description: string | undefined = (args as { description: string })
?.description;
if (!description) {
description = t.toolCalls.readFile;
}
const { path } = args as { path: string; content: string };
return (
<ChainOfThoughtStep key={id} label={description} icon={BookOpenTextIcon}>
{path && (
<ChainOfThoughtSearchResult className="cursor-pointer">
{path}
</ChainOfThoughtSearchResult>
)}
</ChainOfThoughtStep>
);
} else if (name === "write_file" || name === "str_replace") {
let description: string | undefined = (args as { description: string })
?.description;
if (!description) {
description = t.toolCalls.writeFile;
}
const path: string | undefined = (args as { path: string })?.path;
if (isLoading && isLast && autoOpen && autoSelect && path && !result) {
setTimeout(() => {
const url = new URL(
`write-file:${path}?message_id=${messageId}&tool_call_id=${id}`,
).toString();
if (selectedArtifact === url) {
return;
}
select(url, true);
setOpen(true);
}, 100);
}
return (
<ChainOfThoughtStep
key={id}
className="cursor-pointer"
label={description}
icon={NotebookPenIcon}
onClick={() => {
select(
new URL(
`write-file:${path}?message_id=${messageId}&tool_call_id=${id}`,
).toString(),
);
setOpen(true);
}}
>
{path && (
<ChainOfThoughtSearchResult className="cursor-pointer">
{path}
</ChainOfThoughtSearchResult>
)}
</ChainOfThoughtStep>
);
} else if (name === "bash") {
const description: string | undefined = (args as { description: string })
?.description;
if (!description) {
return t.toolCalls.executeCommand;
}
const command: string | undefined = (args as { command: string })?.command;
return (
<ChainOfThoughtStep
key={id}
label={description}
icon={SquareTerminalIcon}
>
{command && (
<CodeBlock
className="mx-0 cursor-pointer border-none px-0"
showLineNumbers={false}
language="bash"
code={command}
/>
)}
</ChainOfThoughtStep>
);
} else if (name === "ask_clarification") {
return (
<ChainOfThoughtStep
key={id}
label={t.toolCalls.needYourHelp}
icon={MessageCircleQuestionMarkIcon}
></ChainOfThoughtStep>
);
} else if (name === "write_todos") {
return (
<ChainOfThoughtStep
key={id}
label={t.toolCalls.writeTodos}
icon={ListTodoIcon}
></ChainOfThoughtStep>
);
} else {
const description: string | undefined = (args as { description: string })
?.description;
return (
<ChainOfThoughtStep
key={id}
label={description ?? t.toolCalls.useTool(name)}
icon={WrenchIcon}
></ChainOfThoughtStep>
);
}
}
interface GenericCoTStep<T extends string = string> {
id?: string;
messageId?: string;
type: T;
}
interface CoTReasoningStep extends GenericCoTStep<"reasoning"> {
reasoning: string | null;
}
interface CoTToolCallStep extends GenericCoTStep<"toolCall"> {
name: string;
args: Record<string, unknown>;
result?: string;
}
type CoTStep = CoTReasoningStep | CoTToolCallStep;
function convertToSteps(messages: Message[]): CoTStep[] {
const steps: CoTStep[] = [];
for (const message of messages) {
if (message.type === "ai") {
const reasoning = extractReasoningContentFromMessage(message);
if (reasoning) {
const step: CoTReasoningStep = {
id: message.id,
messageId: message.id,
type: "reasoning",
reasoning: extractReasoningContentFromMessage(message),
};
steps.push(step);
}
for (const tool_call of message.tool_calls ?? []) {
if (tool_call.name === "task") {
continue;
}
const step: CoTToolCallStep = {
id: tool_call.id,
messageId: message.id,
type: "toolCall",
name: tool_call.name,
args: tool_call.args,
};
const toolCallId = tool_call.id;
if (toolCallId) {
const toolCallResult = findToolCallResult(toolCallId, messages);
if (toolCallResult) {
try {
const json = JSON.parse(toolCallResult);
step.result = json;
} catch {
step.result = toolCallResult;
}
}
}
steps.push(step);
}
}
}
return steps;
}
@@ -0,0 +1,426 @@
import type { Message } from "@langchain/langgraph-sdk";
import { FileIcon, Loader2Icon } from "lucide-react";
import {
memo,
useMemo,
type AnchorHTMLAttributes,
type ImgHTMLAttributes,
} from "react";
import rehypeKatex from "rehype-katex";
import { Loader } from "@/components/ai-elements/loader";
import {
Message as AIElementMessage,
MessageContent as AIElementMessageContent,
MessageResponse as AIElementMessageResponse,
MessageToolbar,
} from "@/components/ai-elements/message";
import {
Reasoning,
ReasoningContent,
ReasoningTrigger,
} from "@/components/ai-elements/reasoning";
import { Task, TaskTrigger } from "@/components/ai-elements/task";
import { Badge } from "@/components/ui/badge";
import { resolveArtifactURL } from "@/core/artifacts/utils";
import { useI18n } from "@/core/i18n/hooks";
import {
extractContentFromMessage,
extractReasoningContentFromMessage,
parseUploadedFiles,
stripUploadedFilesTag,
type FileInMessage,
} from "@/core/messages/utils";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { humanMessagePlugins } from "@/core/streamdown";
import { cn } from "@/lib/utils";
import { CopyButton } from "../copy-button";
import { MarkdownContent } from "./markdown-content";
import { MessageTokenUsage } from "./message-token-usage";
export function MessageListItem({
className,
message,
isLoading,
threadId,
tokenUsageEnabled = false,
}: {
className?: string;
message: Message;
isLoading?: boolean;
threadId: string;
tokenUsageEnabled?: boolean;
}) {
const isHuman = message.type === "human";
return (
<AIElementMessage
className={cn("group/conversation-message relative w-full", className)}
from={isHuman ? "user" : "assistant"}
>
<MessageContent
className={isHuman ? "w-fit" : "w-full"}
message={message}
isLoading={isLoading}
threadId={threadId}
tokenUsageEnabled={tokenUsageEnabled}
/>
{!isLoading && (
<MessageToolbar
className={cn(
isHuman ? "-bottom-9 justify-end" : "-bottom-8",
"absolute right-0 left-0 z-20 opacity-0 transition-opacity delay-200 duration-300 group-hover/conversation-message:opacity-100",
)}
>
<div className="flex gap-1">
<CopyButton
clipboardData={
extractContentFromMessage(message) ??
extractReasoningContentFromMessage(message) ??
""
}
/>
</div>
</MessageToolbar>
)}
</AIElementMessage>
);
}
/**
* Custom image component that handles artifact URLs
*/
function MessageImage({
src,
alt,
threadId,
maxWidth = "90%",
...props
}: React.ImgHTMLAttributes<HTMLImageElement> & {
threadId: string;
maxWidth?: string;
}) {
if (!src) return null;
const imgClassName = cn("overflow-hidden rounded-lg", `max-w-[${maxWidth}]`);
if (typeof src !== "string") {
return <img className={imgClassName} src={src} alt={alt} {...props} />;
}
const url = src.startsWith("/mnt/") ? resolveArtifactURL(src, threadId) : src;
return (
<a href={url} target="_blank" rel="noopener noreferrer">
<img className={imgClassName} src={url} alt={alt} {...props} />
</a>
);
}
function MessageContent_({
className,
message,
isLoading = false,
threadId,
tokenUsageEnabled = false,
}: {
className?: string;
message: Message;
isLoading?: boolean;
threadId: string;
tokenUsageEnabled?: boolean;
}) {
const rehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
const isHuman = message.type === "human";
const components = useMemo(
() => ({
img: (props: ImgHTMLAttributes<HTMLImageElement>) => (
<MessageImage {...props} threadId={threadId} maxWidth="90%" />
),
a: ({ href, ...props }: AnchorHTMLAttributes<HTMLAnchorElement>) => {
if (href?.startsWith("/mnt/")) {
const url = resolveArtifactURL(href, threadId);
return (
<a
{...props}
href={url}
target="_blank"
rel="noopener noreferrer"
/>
);
}
return <a {...props} href={href} />;
},
}),
[threadId],
);
const rawContent = extractContentFromMessage(message);
const reasoningContent = extractReasoningContentFromMessage(message);
const files = useMemo(() => {
const files = message.additional_kwargs?.files;
if (!Array.isArray(files) || files.length === 0) {
if (rawContent.includes("<uploaded_files>")) {
// If the content contains the <uploaded_files> tag, we return the parsed files from the content for backward compatibility.
return parseUploadedFiles(rawContent);
}
return null;
}
return files as FileInMessage[];
}, [message.additional_kwargs?.files, rawContent]);
const contentToDisplay = useMemo(() => {
if (isHuman) {
return rawContent ? stripUploadedFilesTag(rawContent) : "";
}
return rawContent ?? "";
}, [rawContent, isHuman]);
const filesList =
files && files.length > 0 ? (
<RichFilesList files={files} threadId={threadId} />
) : null;
// Uploading state: mock AI message shown while files upload
if (message.additional_kwargs?.element === "task") {
return (
<AIElementMessageContent className={className}>
<Task defaultOpen={false}>
<TaskTrigger title="">
<div className="text-muted-foreground flex w-full cursor-default items-center gap-2 text-sm select-none">
<Loader className="size-4" />
<span>{contentToDisplay}</span>
</div>
</TaskTrigger>
</Task>
</AIElementMessageContent>
);
}
// Reasoning-only AI message (no main response content yet)
if (!isHuman && reasoningContent && !rawContent) {
return (
<AIElementMessageContent className={className}>
<Reasoning isStreaming={isLoading}>
<ReasoningTrigger />
<ReasoningContent>{reasoningContent}</ReasoningContent>
</Reasoning>
<MessageTokenUsage
enabled={tokenUsageEnabled}
isLoading={isLoading}
message={message}
/>
</AIElementMessageContent>
);
}
if (isHuman) {
const messageResponse = contentToDisplay ? (
<AIElementMessageResponse
remarkPlugins={humanMessagePlugins.remarkPlugins}
rehypePlugins={humanMessagePlugins.rehypePlugins}
components={components}
parseIncompleteMarkdown={false}
>
{contentToDisplay}
</AIElementMessageResponse>
) : null;
return (
<div className={cn("ml-auto flex flex-col gap-2", className)}>
{filesList}
{messageResponse && (
<AIElementMessageContent className="w-fit">
{messageResponse}
</AIElementMessageContent>
)}
</div>
);
}
return (
<AIElementMessageContent className={className}>
{filesList}
<MarkdownContent
content={contentToDisplay}
isLoading={isLoading}
rehypePlugins={[...rehypePlugins, [rehypeKatex, { output: "html" }]]}
className="my-3"
components={components}
/>
<MessageTokenUsage
enabled={tokenUsageEnabled}
isLoading={isLoading}
message={message}
/>
</AIElementMessageContent>
);
}
/**
* Get file extension and check helpers
*/
const getFileExt = (filename: string) =>
filename.split(".").pop()?.toLowerCase() ?? "";
const FILE_TYPE_MAP: Record<string, string> = {
json: "JSON",
csv: "CSV",
txt: "TXT",
md: "Markdown",
py: "Python",
js: "JavaScript",
ts: "TypeScript",
tsx: "TSX",
jsx: "JSX",
html: "HTML",
css: "CSS",
xml: "XML",
yaml: "YAML",
yml: "YAML",
pdf: "PDF",
png: "PNG",
jpg: "JPG",
jpeg: "JPEG",
gif: "GIF",
svg: "SVG",
zip: "ZIP",
tar: "TAR",
gz: "GZ",
};
const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp"];
function getFileTypeLabel(filename: string): string {
const ext = getFileExt(filename);
return FILE_TYPE_MAP[ext] ?? (ext.toUpperCase() || "FILE");
}
function isImageFile(filename: string): boolean {
return IMAGE_EXTENSIONS.includes(getFileExt(filename));
}
/**
* Format bytes to human-readable size string
*/
function formatBytes(bytes: number): string {
if (bytes === 0) return "—";
const kb = bytes / 1024;
if (kb < 1024) return `${kb.toFixed(1)} KB`;
return `${(kb / 1024).toFixed(1)} MB`;
}
/**
* List of files from additional_kwargs.files (with optional upload status)
*/
function RichFilesList({
files,
threadId,
}: {
files: FileInMessage[];
threadId: string;
}) {
if (files.length === 0) return null;
return (
<div className="mb-2 flex flex-wrap justify-end gap-2">
{files.map((file, index) => (
<RichFileCard
key={`${file.filename}-${index}`}
file={file}
threadId={threadId}
/>
))}
</div>
);
}
/**
* Single file card that handles FileInMessage (supports uploading state)
*/
function RichFileCard({
file,
threadId,
}: {
file: FileInMessage;
threadId: string;
}) {
const { t } = useI18n();
const isUploading = file.status === "uploading";
const isImage = isImageFile(file.filename);
if (isUploading) {
return (
<div className="bg-background border-border/40 flex max-w-50 min-w-30 flex-col gap-1 rounded-lg border p-3 opacity-60 shadow-sm">
<div className="flex items-start gap-2">
<Loader2Icon className="text-muted-foreground mt-0.5 size-4 shrink-0 animate-spin" />
<span
className="text-foreground truncate text-sm font-medium"
title={file.filename}
>
{file.filename}
</span>
</div>
<div className="flex items-center justify-between gap-2">
<Badge
variant="secondary"
className="rounded px-1.5 py-0.5 text-[10px] font-normal"
>
{getFileTypeLabel(file.filename)}
</Badge>
<span className="text-muted-foreground text-[10px]">
{t.uploads.uploading}
</span>
</div>
</div>
);
}
if (!file.path) return null;
const fileUrl = resolveArtifactURL(file.path, threadId);
if (isImage) {
return (
<a
href={fileUrl}
target="_blank"
rel="noopener noreferrer"
className="group border-border/40 relative block overflow-hidden rounded-lg border"
>
<img
src={fileUrl}
alt={file.filename}
className="h-32 w-auto max-w-60 object-cover transition-transform group-hover:scale-105"
/>
</a>
);
}
return (
<div className="bg-background border-border/40 flex max-w-50 min-w-30 flex-col gap-1 rounded-lg border p-3 shadow-sm">
<div className="flex items-start gap-2">
<FileIcon className="text-muted-foreground mt-0.5 size-4 shrink-0" />
<span
className="text-foreground truncate text-sm font-medium"
title={file.filename}
>
{file.filename}
</span>
</div>
<div className="flex items-center justify-between gap-2">
<Badge
variant="secondary"
className="rounded px-1.5 py-0.5 text-[10px] font-normal"
>
{getFileTypeLabel(file.filename)}
</Badge>
<span className="text-muted-foreground text-[10px]">
{formatBytes(file.size)}
</span>
</div>
</div>
);
}
const MessageContent = memo(MessageContent_);
@@ -0,0 +1,242 @@
import type { BaseStream } from "@langchain/langgraph-sdk/react";
import {
Conversation,
ConversationContent,
} from "@/components/ai-elements/conversation";
import { useI18n } from "@/core/i18n/hooks";
import {
extractContentFromMessage,
extractPresentFilesFromMessage,
extractTextFromMessage,
groupMessages,
hasContent,
hasPresentFiles,
hasReasoning,
hasToolCalls,
} from "@/core/messages/utils";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import type { Subtask } from "@/core/tasks";
import { useUpdateSubtask } from "@/core/tasks/context";
import type { AgentThreadState } from "@/core/threads";
import { cn } from "@/lib/utils";
import { ArtifactFileList } from "../artifacts/artifact-file-list";
import { StreamingIndicator } from "../streaming-indicator";
import { MarkdownContent } from "./markdown-content";
import { MessageGroup } from "./message-group";
import { MessageListItem } from "./message-list-item";
import { MessageTokenUsageList } from "./message-token-usage";
import { MessageListSkeleton } from "./skeleton";
import { SubtaskCard } from "./subtask-card";
export const MESSAGE_LIST_DEFAULT_PADDING_BOTTOM = 160;
export const MESSAGE_LIST_FOLLOWUPS_EXTRA_PADDING_BOTTOM = 80;
export function MessageList({
className,
threadId,
thread,
paddingBottom = MESSAGE_LIST_DEFAULT_PADDING_BOTTOM,
tokenUsageEnabled = false,
}: {
className?: string;
threadId: string;
thread: BaseStream<AgentThreadState>;
paddingBottom?: number;
tokenUsageEnabled?: boolean;
}) {
const { t } = useI18n();
const rehypePlugins = useRehypeSplitWordsIntoSpans(thread.isLoading);
const updateSubtask = useUpdateSubtask();
const messages = thread.messages;
if (thread.isThreadLoading && messages.length === 0) {
return <MessageListSkeleton />;
}
return (
<Conversation
className={cn("flex size-full flex-col justify-center", className)}
>
<ConversationContent className="mx-auto w-full max-w-(--container-width-md) gap-8 pt-12">
{groupMessages(messages, (group) => {
if (group.type === "human" || group.type === "assistant") {
return group.messages.map((msg) => {
return (
<MessageListItem
key={`${group.id}/${msg.id}`}
message={msg}
isLoading={thread.isLoading}
threadId={threadId}
tokenUsageEnabled={tokenUsageEnabled}
/>
);
});
} else if (group.type === "assistant:clarification") {
const message = group.messages[0];
if (message && hasContent(message)) {
return (
<div key={group.id} className="w-full">
<MarkdownContent
content={extractContentFromMessage(message)}
isLoading={thread.isLoading}
rehypePlugins={rehypePlugins}
/>
<MessageTokenUsageList
enabled={tokenUsageEnabled}
isLoading={thread.isLoading}
messages={group.messages}
/>
</div>
);
}
return null;
} else if (group.type === "assistant:present-files") {
const files: string[] = [];
for (const message of group.messages) {
if (hasPresentFiles(message)) {
const presentFiles = extractPresentFilesFromMessage(message);
files.push(...presentFiles);
}
}
return (
<div className="w-full" key={group.id}>
{group.messages[0] && hasContent(group.messages[0]) && (
<MarkdownContent
content={extractContentFromMessage(group.messages[0])}
isLoading={thread.isLoading}
rehypePlugins={rehypePlugins}
className="mb-4"
/>
)}
<ArtifactFileList files={files} threadId={threadId} />
<MessageTokenUsageList
enabled={tokenUsageEnabled}
isLoading={thread.isLoading}
messages={group.messages}
/>
</div>
);
} else if (group.type === "assistant:subagent") {
const tasks = new Set<Subtask>();
for (const message of group.messages) {
if (message.type === "ai") {
for (const toolCall of message.tool_calls ?? []) {
if (toolCall.name === "task") {
const task: Subtask = {
id: toolCall.id!,
subagent_type: toolCall.args.subagent_type,
description: toolCall.args.description,
prompt: toolCall.args.prompt,
status: "in_progress",
};
updateSubtask(task);
tasks.add(task);
}
}
} else if (message.type === "tool") {
const taskId = message.tool_call_id;
if (taskId) {
const result = extractTextFromMessage(message);
if (result.startsWith("Task Succeeded. Result:")) {
updateSubtask({
id: taskId,
status: "completed",
result: result
.split("Task Succeeded. Result:")[1]
?.trim(),
});
} else if (result.startsWith("Task failed.")) {
updateSubtask({
id: taskId,
status: "failed",
error: result.split("Task failed.")[1]?.trim(),
});
} else if (result.startsWith("Task timed out")) {
updateSubtask({
id: taskId,
status: "failed",
error: result,
});
} else {
updateSubtask({
id: taskId,
status: "in_progress",
});
}
}
}
}
const results: React.ReactNode[] = [];
for (const message of group.messages.filter(
(message) => message.type === "ai",
)) {
if (hasReasoning(message)) {
results.push(
<MessageGroup
key={"thinking-group-" + message.id}
messages={[message]}
isLoading={thread.isLoading}
/>,
);
}
results.push(
<div
key="subtask-count"
className="text-muted-foreground pt-2 text-sm font-normal"
>
{t.subtasks.executing(tasks.size)}
</div>,
);
const taskIds = message.tool_calls
?.filter((toolCall) => toolCall.name === "task")
.map((toolCall) => toolCall.id);
for (const taskId of taskIds ?? []) {
results.push(
<SubtaskCard
key={"task-group-" + taskId}
taskId={taskId!}
isLoading={thread.isLoading}
/>,
);
}
}
return (
<div
key={"subtask-group-" + group.id}
className="relative z-1 flex flex-col gap-2"
>
{results}
<MessageTokenUsageList
enabled={tokenUsageEnabled}
isLoading={thread.isLoading}
messages={group.messages}
/>
</div>
);
}
const tokenUsageMessages = group.messages.filter(
(message) =>
message.type === "ai" &&
(hasToolCalls(message) ? true : !hasContent(message)),
);
return (
<div key={"group-" + group.id} className="w-full">
<MessageGroup
messages={group.messages}
isLoading={thread.isLoading}
/>
<MessageTokenUsageList
enabled={tokenUsageEnabled}
isLoading={thread.isLoading}
messages={tokenUsageMessages}
/>
</div>
);
})}
{thread.isLoading && <StreamingIndicator className="my-4" />}
<div style={{ height: `${paddingBottom}px` }} />
</ConversationContent>
</Conversation>
);
}
@@ -0,0 +1,91 @@
import type { Message } from "@langchain/langgraph-sdk";
import { CoinsIcon } from "lucide-react";
import { useI18n } from "@/core/i18n/hooks";
import { formatTokenCount, getUsageMetadata } from "@/core/messages/usage";
import { cn } from "@/lib/utils";
export function MessageTokenUsage({
className,
enabled = false,
isLoading = false,
message,
}: {
className?: string;
enabled?: boolean;
isLoading?: boolean;
message: Message;
}) {
const { t } = useI18n();
if (!enabled || isLoading || message.type !== "ai") {
return null;
}
const usage = getUsageMetadata(message);
return (
<div
className={cn(
"text-muted-foreground border-border/60 mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 border-t pt-2 text-[11px]",
className,
)}
>
<span className="inline-flex items-center gap-1 font-medium">
<CoinsIcon className="size-3" />
{t.tokenUsage.label}
</span>
{usage ? (
<>
<span>
{t.tokenUsage.input}: {formatTokenCount(usage.inputTokens)}
</span>
<span>
{t.tokenUsage.output}: {formatTokenCount(usage.outputTokens)}
</span>
<span className="font-medium">
{t.tokenUsage.total}: {formatTokenCount(usage.totalTokens)}
</span>
</>
) : (
<span>{t.tokenUsage.unavailableShort}</span>
)}
</div>
);
}
export function MessageTokenUsageList({
className,
enabled = false,
isLoading = false,
messages,
}: {
className?: string;
enabled?: boolean;
isLoading?: boolean;
messages: Message[];
}) {
if (!enabled || isLoading) {
return null;
}
const aiMessages = messages.filter((message) => message.type === "ai");
if (aiMessages.length === 0) {
return null;
}
return (
<>
{aiMessages.map((message, index) => (
<MessageTokenUsage
className={className}
enabled={enabled}
isLoading={isLoading}
key={message.id ?? index}
message={message}
/>
))}
</>
);
}
@@ -0,0 +1,79 @@
import { Skeleton } from "@/components/ui/skeleton";
const STAGGER_MS = 60;
function SkeletonBar({
className,
style,
originRight,
}: {
className?: string;
style?: React.CSSProperties;
originRight?: boolean;
}) {
return (
<div
className={`animate-skeleton-entrance fill-mode-[forwards] overflow-hidden rounded-md ${originRight ? "origin-[right]" : "origin-[left]"} ${className ?? ""}`}
style={{ opacity: 0, ...style }}
>
<Skeleton className="h-full w-full rounded-md" />
</div>
);
}
export function MessageListSkeleton() {
let index = 0;
return (
<div className="flex w-full max-w-(--container-width-md) flex-col gap-12 p-8 pt-16">
<div
role="human-message"
className="flex w-[50%] flex-col items-end gap-2 self-end"
>
<SkeletonBar
className="h-6 w-full"
originRight
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-[80%]"
originRight
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
</div>
<div role="assistant-message" className="flex flex-col gap-2">
<SkeletonBar
className="h-6 w-full"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-full"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-[70%]"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-full"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-full"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-full"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-[60%]"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
<SkeletonBar
className="h-6 w-[40%]"
style={{ animationDelay: `${index++ * STAGGER_MS}ms` }}
/>
</div>
</div>
);
}
@@ -0,0 +1,177 @@
import {
CheckCircleIcon,
ChevronUp,
ClipboardListIcon,
Loader2Icon,
XCircleIcon,
} from "lucide-react";
import { useMemo, useState } from "react";
import { Streamdown } from "streamdown";
import {
ChainOfThought,
ChainOfThoughtContent,
ChainOfThoughtStep,
} from "@/components/ai-elements/chain-of-thought";
import { Shimmer } from "@/components/ai-elements/shimmer";
import { Button } from "@/components/ui/button";
import { ShineBorder } from "@/components/ui/shine-border";
import { useI18n } from "@/core/i18n/hooks";
import { hasToolCalls } from "@/core/messages/utils";
import { useRehypeSplitWordsIntoSpans } from "@/core/rehype";
import { streamdownPluginsWithWordAnimation } from "@/core/streamdown";
import { useSubtask } from "@/core/tasks/context";
import { explainLastToolCall } from "@/core/tools/utils";
import { cn } from "@/lib/utils";
import { CitationLink } from "../citations/citation-link";
import { FlipDisplay } from "../flip-display";
import { MarkdownContent } from "./markdown-content";
export function SubtaskCard({
className,
taskId,
isLoading,
}: {
className?: string;
taskId: string;
isLoading: boolean;
}) {
const { t } = useI18n();
const [collapsed, setCollapsed] = useState(true);
const rehypePlugins = useRehypeSplitWordsIntoSpans(isLoading);
const task = useSubtask(taskId)!;
const icon = useMemo(() => {
if (task.status === "completed") {
return <CheckCircleIcon className="size-3" />;
} else if (task.status === "failed") {
return <XCircleIcon className="size-3 text-red-500" />;
} else if (task.status === "in_progress") {
return <Loader2Icon className="size-3 animate-spin" />;
}
}, [task.status]);
return (
<ChainOfThought
className={cn("relative w-full gap-2 rounded-lg border py-0", className)}
open={!collapsed}
>
<div
className={cn(
"ambilight z-[-1]",
task.status === "in_progress" ? "enabled" : "",
)}
></div>
{task.status === "in_progress" && (
<>
<ShineBorder
borderWidth={1.5}
shineColor={["#A07CFE", "#FE8FB5", "#FFBE7B"]}
/>
</>
)}
<div className="bg-background/95 flex w-full flex-col rounded-lg">
<div className="flex w-full items-center justify-between p-0.5">
<Button
className="w-full items-start justify-start text-left"
variant="ghost"
onClick={() => setCollapsed(!collapsed)}
>
<div className="flex w-full items-center justify-between">
<ChainOfThoughtStep
className="font-normal"
label={
task.status === "in_progress" ? (
<Shimmer duration={3} spread={3}>
{task.description}
</Shimmer>
) : (
task.description
)
}
icon={<ClipboardListIcon />}
></ChainOfThoughtStep>
<div className="flex items-center gap-1">
{collapsed && (
<div
className={cn(
"text-muted-foreground flex items-center gap-1 text-xs font-normal",
task.status === "failed" ? "text-red-500 opacity-67" : "",
)}
>
{icon}
<FlipDisplay
className="max-w-[420px] truncate pb-1"
uniqueKey={task.latestMessage?.id ?? ""}
>
{task.status === "in_progress" &&
task.latestMessage &&
hasToolCalls(task.latestMessage)
? explainLastToolCall(task.latestMessage, t)
: t.subtasks[task.status]}
</FlipDisplay>
</div>
)}
<ChevronUp
className={cn(
"text-muted-foreground size-4",
!collapsed ? "" : "rotate-180",
)}
/>
</div>
</div>
</Button>
</div>
<ChainOfThoughtContent className="px-4 pb-4">
{task.prompt && (
<ChainOfThoughtStep
label={
<Streamdown
{...streamdownPluginsWithWordAnimation}
components={{ a: CitationLink }}
>
{task.prompt}
</Streamdown>
}
></ChainOfThoughtStep>
)}
{task.status === "in_progress" &&
task.latestMessage &&
hasToolCalls(task.latestMessage) && (
<ChainOfThoughtStep
label={t.subtasks.in_progress}
icon={<Loader2Icon className="size-4 animate-spin" />}
>
{explainLastToolCall(task.latestMessage, t)}
</ChainOfThoughtStep>
)}
{task.status === "completed" && (
<>
<ChainOfThoughtStep
label={t.subtasks.completed}
icon={<CheckCircleIcon className="size-4" />}
></ChainOfThoughtStep>
<ChainOfThoughtStep
label={
task.result ? (
<MarkdownContent
content={task.result}
isLoading={false}
rehypePlugins={rehypePlugins}
/>
) : null
}
></ChainOfThoughtStep>
</>
)}
{task.status === "failed" && (
<ChainOfThoughtStep
label={<div className="text-red-500">{task.error}</div>}
icon={<XCircleIcon className="size-4 text-red-500" />}
></ChainOfThoughtStep>
)}
</ChainOfThoughtContent>
</div>
</ChainOfThought>
);
}
@@ -0,0 +1,65 @@
"use client";
import { useI18n } from "@/core/i18n/hooks";
import type { Translations } from "@/core/i18n/locales/types";
import { Tooltip } from "./tooltip";
export type AgentMode = "flash" | "thinking" | "pro" | "ultra";
function getModeLabelKey(
mode: AgentMode,
): keyof Pick<
Translations["inputBox"],
"flashMode" | "reasoningMode" | "proMode" | "ultraMode"
> {
switch (mode) {
case "flash":
return "flashMode";
case "thinking":
return "reasoningMode";
case "pro":
return "proMode";
case "ultra":
return "ultraMode";
}
}
function getModeDescriptionKey(
mode: AgentMode,
): keyof Pick<
Translations["inputBox"],
| "flashModeDescription"
| "reasoningModeDescription"
| "proModeDescription"
| "ultraModeDescription"
> {
switch (mode) {
case "flash":
return "flashModeDescription";
case "thinking":
return "reasoningModeDescription";
case "pro":
return "proModeDescription";
case "ultra":
return "ultraModeDescription";
}
}
export function ModeHoverGuide({
mode,
children,
showTitle = true,
}: {
mode: AgentMode;
children: React.ReactNode;
/** When true, tooltip shows "ModeName: Description". When false, only description. */
showTitle?: boolean;
}) {
const { t } = useI18n();
const label = t.inputBox[getModeLabelKey(mode)];
const description = t.inputBox[getModeDescriptionKey(mode)];
const content = showTitle ? `${label}: ${description}` : description;
return <Tooltip content={content}>{children}</Tooltip>;
}
@@ -0,0 +1,17 @@
"use client";
import { useEffect } from "react";
export function Overscroll({
behavior,
overflow = "hidden",
}: {
behavior: "none" | "contain" | "auto";
overflow?: "hidden" | "auto" | "scroll";
}) {
useEffect(() => {
document.documentElement.style.overflow = overflow;
document.documentElement.style.overscrollBehavior = behavior;
}, [behavior, overflow]);
return null;
}
@@ -0,0 +1,305 @@
"use client";
import {
Download,
FileJson,
FileText,
MoreHorizontal,
Pencil,
Share2,
Trash2,
} from "lucide-react";
import Link from "next/link";
import { useParams, usePathname, useRouter } from "next/navigation";
import { useCallback, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuAction,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { getAPIClient } from "@/core/api";
import { useI18n } from "@/core/i18n/hooks";
import {
exportThreadAsJSON,
exportThreadAsMarkdown,
} from "@/core/threads/export";
import {
useDeleteThread,
useRenameThread,
useThreads,
} from "@/core/threads/hooks";
import type { AgentThread, AgentThreadState } from "@/core/threads/types";
import { pathOfThread, titleOfThread } from "@/core/threads/utils";
import { env } from "@/env";
import { isIMEComposing } from "@/lib/ime";
export function RecentChatList() {
const { t } = useI18n();
const router = useRouter();
const pathname = usePathname();
const { thread_id: threadIdFromPath, agent_name: agentNameFromPath } =
useParams<{
thread_id: string;
agent_name?: string;
}>();
const { data: threads = [] } = useThreads();
const { mutate: deleteThread } = useDeleteThread();
const { mutate: renameThread } = useRenameThread();
// Rename dialog state
const [renameDialogOpen, setRenameDialogOpen] = useState(false);
const [renameThreadId, setRenameThreadId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState("");
const handleDelete = useCallback(
(threadId: string) => {
deleteThread({ threadId });
if (threadId === threadIdFromPath) {
const threadIndex = threads.findIndex((t) => t.thread_id === threadId);
let nextThreadPath = pathOfThread("new", {
agent_name: agentNameFromPath,
});
if (threadIndex > -1) {
if (threads[threadIndex + 1]) {
nextThreadPath = pathOfThread(threads[threadIndex + 1]!);
} else if (threads[threadIndex - 1]) {
nextThreadPath = pathOfThread(threads[threadIndex - 1]!);
}
}
void router.push(nextThreadPath);
}
},
[agentNameFromPath, deleteThread, router, threadIdFromPath, threads],
);
const handleRenameClick = useCallback(
(threadId: string, currentTitle: string) => {
setRenameThreadId(threadId);
setRenameValue(currentTitle);
setRenameDialogOpen(true);
},
[],
);
const handleRenameSubmit = useCallback(() => {
if (renameThreadId && renameValue.trim()) {
renameThread({ threadId: renameThreadId, title: renameValue.trim() });
setRenameDialogOpen(false);
setRenameThreadId(null);
setRenameValue("");
}
}, [renameThread, renameThreadId, renameValue]);
const handleShare = useCallback(
async (thread: AgentThread) => {
// Always use Vercel URL for sharing so others can access
const VERCEL_URL = "https://deer-flow-v2.vercel.app";
const isLocalhost =
window.location.hostname === "localhost" ||
window.location.hostname === "127.0.0.1";
// On localhost: use Vercel URL; On production: use current origin
const baseUrl = isLocalhost ? VERCEL_URL : window.location.origin;
const shareUrl = `${baseUrl}${pathOfThread(thread)}`;
try {
await navigator.clipboard.writeText(shareUrl);
toast.success(t.clipboard.linkCopied);
} catch {
toast.error(t.clipboard.failedToCopyToClipboard);
}
},
[t],
);
const handleExport = useCallback(
async (thread: AgentThread, format: "markdown" | "json") => {
try {
const apiClient = getAPIClient();
const state = await apiClient.threads.getState<AgentThreadState>(
thread.thread_id,
);
const messages = state.values?.messages ?? [];
if (messages.length === 0) {
toast.error(t.conversation.noMessages);
return;
}
if (format === "markdown") {
exportThreadAsMarkdown(thread, messages);
} else {
exportThreadAsJSON(thread, messages);
}
toast.success(t.common.exportSuccess);
} catch {
toast.error("Failed to export conversation");
}
},
[t],
);
const visibleThreads = threads.filter(
(thread) => thread.metadata?.thread_type !== "scheduler",
);
if (visibleThreads.length === 0) {
return null;
}
return (
<>
<SidebarGroup className="px-2">
<SidebarGroupLabel className="text-muted-foreground/90 px-2 text-[11px] font-semibold tracking-wide uppercase">
{env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true"
? t.sidebar.recentChats
: t.sidebar.demoChats}
</SidebarGroupLabel>
<SidebarGroupContent className="group-data-[collapsible=icon]:pointer-events-none group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0">
<SidebarMenu>
<div className="flex w-full flex-col gap-1">
{visibleThreads.map((thread) => {
const isActive = pathOfThread(thread) === pathname;
return (
<SidebarMenuItem
key={thread.thread_id}
className="group/side-menu-item"
>
<SidebarMenuButton isActive={isActive} asChild>
<div>
<Link
className="text-muted-foreground block w-full whitespace-nowrap group-hover/side-menu-item:overflow-hidden"
href={pathOfThread(thread)}
>
{titleOfThread(thread)}
</Link>
{env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true" && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuAction
showOnHover
className="bg-background/50 hover:bg-background"
>
<MoreHorizontal />
<span className="sr-only">{t.common.more}</span>
</SidebarMenuAction>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-48 rounded-lg"
side={"right"}
align={"start"}
>
<DropdownMenuItem
onSelect={() =>
handleRenameClick(
thread.thread_id,
titleOfThread(thread),
)
}
>
<Pencil className="text-muted-foreground" />
<span>{t.common.rename}</span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => handleShare(thread)}
>
<Share2 className="text-muted-foreground" />
<span>{t.common.share}</span>
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Download className="text-muted-foreground" />
<span>{t.common.export}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem
onSelect={() =>
handleExport(thread, "markdown")
}
>
<FileText className="text-muted-foreground" />
<span>{t.common.exportAsMarkdown}</span>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() =>
handleExport(thread, "json")
}
>
<FileJson className="text-muted-foreground" />
<span>{t.common.exportAsJSON}</span>
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => handleDelete(thread.thread_id)}
>
<Trash2 className="text-muted-foreground" />
<span>{t.common.delete}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</div>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
{/* Rename Dialog */}
<Dialog open={renameDialogOpen} onOpenChange={setRenameDialogOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>{t.common.rename}</DialogTitle>
</DialogHeader>
<div className="py-4">
<Input
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
placeholder={t.common.rename}
onKeyDown={(e) => {
if (e.key === "Enter" && !isIMEComposing(e)) {
e.preventDefault();
handleRenameSubmit();
}
}}
/>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setRenameDialogOpen(false)}
>
{t.common.cancel}
</Button>
<Button onClick={handleRenameSubmit}>{t.common.save}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,67 @@
/**
* About DeerFlow markdown content. Inlined to avoid raw-loader dependency
* (Turbopack cannot resolve raw-loader for .md imports).
*/
export const aboutMarkdown = `# 🦌 [About DeerFlow 2.0](https://github.com/bytedance/deer-flow)
> **From Open Source, Back to Open Source**
DeerFlow (**D**eep **E**xploration and **E**fficient **R**esearch **Flow**) is an open-source **super agent harness** that orchestrates **sub-agents**, **memory**, and **sandboxes** to do almost anything — powered by **extensible skills**.
---
## 🚀 Core Features
* **Skills & Tools**: With built-in and extensible skills and tools, DeerFlow can do almost anything.
* **Sub-Agents**: Sub-Agents help the main agent to do the tasks that are too complex to be done by the main agent.
* **Sandbox & File System**: Safely execute code and manipulate files in the sandbox.
* **Context Engineering**: Isolated sub-agent context, summarization to keep the context window sharp.
* **Long-Term Memory**: Keep recording the user's profile, top of mind, and conversation history.
---
## 🌟 GitHub Repository
![Star History Chart](https://api.star-history.com/svg?repos=bytedance/deer-flow&type=Date)
Explore DeerFlow on GitHub: [github.com/bytedance/deer-flow](https://github.com/bytedance/deer-flow)
## 🌐 Official Website
Visit the official website of DeerFlow: [deerflow.tech](https://deerflow.tech/)
## 📧 Support
If you have any questions or need help, please contact us at [support@deerflow.tech](mailto:support@deerflow.tech).
---
## 📜 License
DeerFlow is proudly open source and distributed under the **MIT License**.
---
## 🙌 Acknowledgments
We extend our heartfelt gratitude to the open source projects and contributors who have made DeerFlow a reality. We truly stand on the shoulders of giants.
### Core Frameworks
- **[LangChain](https://github.com/langchain-ai/langchain)**: A phenomenal framework that powers our LLM interactions and chains.
- **[LangGraph](https://github.com/langchain-ai/langgraph)**: Enabling sophisticated multi-agent orchestration.
- **[Next.js](https://nextjs.org/)**: A cutting-edge framework for building web applications.
### UI Libraries
- **[Shadcn](https://ui.shadcn.com/)**: Minimalistic components that power our UI.
- **[SToneX](https://github.com/stonexer)**: For his invaluable contribution to token-by-token visual effects.
These outstanding projects form the backbone of DeerFlow and exemplify the transformative power of open source collaboration.
### Special Thanks
Finally, we want to express our heartfelt gratitude to the core authors of DeerFlow 1.0 and 2.0:
- **[Daniel Walnut](https://github.com/hetaoBackend/)**
- **[Henry Li](https://github.com/magiccube/)**
Without their vision, passion and dedication, \`DeerFlow\` would not be what it is today.
`;
@@ -0,0 +1,9 @@
"use client";
import { Streamdown } from "streamdown";
import { aboutMarkdown } from "./about-content";
export function AboutSettingsPage() {
return <Streamdown>{aboutMarkdown}</Streamdown>;
}
@@ -0,0 +1,55 @@
# 🦌 [About DeerFlow 2.0](https://github.com/bytedance/deer-flow)
> **From Open Source, Back to Open Source**
**DeerFlow** (**D**eep **E**xploration and **E**fficient **R**esearch **Flow**) is a community-driven SuperAgent harness that researches, codes, and creates.
With the help of sandboxes, memories, tools and skills, it handles
different levels of tasks that could take minutes to hours.
---
## 🌟 GitHub Repository
Explore DeerFlow on GitHub: [github.com/bytedance/deer-flow](https://github.com/bytedance/deer-flow)
## 🌐 Official Website
Visit the official website of DeerFlow: [deerflow.tech](https://deerflow.tech/)
## 📧 Support
If you have any questions or need help, please contact us at [support@deerflow.tech](mailto:support@deerflow.tech).
---
## 📜 License
DeerFlow is proudly open source and distributed under the **MIT License**.
---
## 🙌 Acknowledgments
We extend our heartfelt gratitude to the open source projects and contributors who have made DeerFlow a reality. We truly stand on the shoulders of giants.
### Core Frameworks
- **[LangChain](https://github.com/langchain-ai/langchain)**: A phenomenal framework that powers our LLM interactions and chains.
- **[LangGraph](https://github.com/langchain-ai/langgraph)**: Enabling sophisticated multi-agent orchestration.
- **[Next.js](https://nextjs.org/)**: A cutting-edge framework for building web applications.
### UI Libraries
- **[Shadcn](https://ui.shadcn.com/)**: Minimalistic components that power our UI.
- **[SToneX](https://github.com/stonexer)**: For his invaluable contribution to token-by-token visual effects.
These outstanding projects form the backbone of DeerFlow and exemplify the transformative power of open source collaboration.
### Special Thanks
Finally, we want to express our heartfelt gratitude to the core authors of DeerFlow 1.0 and 2.0:
- **[Daniel Walnut](https://github.com/hetaoBackend/)**
- **[Henry Li](https://github.com/magiccube/)**
Without their vision, passion and dedication, `DeerFlow` would not be what it is today.
@@ -0,0 +1,196 @@
"use client";
import { MonitorSmartphoneIcon, MoonIcon, SunIcon } from "lucide-react";
import { useTheme } from "next-themes";
import { useMemo, type ComponentType, type SVGProps } from "react";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { enUS, isLocale, zhCN, type Locale } from "@/core/i18n";
import { useI18n } from "@/core/i18n/hooks";
import { cn } from "@/lib/utils";
import { SettingsSection } from "./settings-section";
const languageOptions: { value: Locale; label: string }[] = [
{ value: "en-US", label: enUS.locale.localName },
{ value: "zh-CN", label: zhCN.locale.localName },
];
export function AppearanceSettingsPage() {
const { t, locale, changeLocale } = useI18n();
const { theme, setTheme, systemTheme } = useTheme();
const currentTheme = (theme ?? "system") as "system" | "light" | "dark";
const themeOptions = useMemo(
() => [
{
id: "system",
label: t.settings.appearance.system,
description: t.settings.appearance.systemDescription,
icon: MonitorSmartphoneIcon,
},
{
id: "light",
label: t.settings.appearance.light,
description: t.settings.appearance.lightDescription,
icon: SunIcon,
},
{
id: "dark",
label: t.settings.appearance.dark,
description: t.settings.appearance.darkDescription,
icon: MoonIcon,
},
],
[
t.settings.appearance.dark,
t.settings.appearance.darkDescription,
t.settings.appearance.light,
t.settings.appearance.lightDescription,
t.settings.appearance.system,
t.settings.appearance.systemDescription,
],
);
return (
<div className="space-y-8">
<SettingsSection
title={t.settings.appearance.themeTitle}
description={t.settings.appearance.themeDescription}
>
<div className="grid gap-3 lg:grid-cols-3">
{themeOptions.map((option) => (
<ThemePreviewCard
key={option.id}
icon={option.icon}
label={option.label}
description={option.description}
active={currentTheme === option.id}
mode={option.id as "system" | "light" | "dark"}
systemTheme={systemTheme}
onSelect={(value) => setTheme(value)}
/>
))}
</div>
</SettingsSection>
<Separator />
<SettingsSection
title={t.settings.appearance.languageTitle}
description={t.settings.appearance.languageDescription}
>
<Select
value={locale}
onValueChange={(value) => {
if (isLocale(value)) {
changeLocale(value);
}
}}
>
<SelectTrigger className="w-[220px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{languageOptions.map((item) => (
<SelectItem key={item.value} value={item.value}>
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
</SettingsSection>
</div>
);
}
function ThemePreviewCard({
icon: Icon,
label,
description,
active,
mode,
systemTheme,
onSelect,
}: {
icon: ComponentType<SVGProps<SVGSVGElement>>;
label: string;
description: string;
active: boolean;
mode: "system" | "light" | "dark";
systemTheme?: string;
onSelect: (mode: "system" | "light" | "dark") => void;
}) {
const previewMode =
mode === "system" ? (systemTheme === "dark" ? "dark" : "light") : mode;
return (
<button
type="button"
onClick={() => onSelect(mode)}
className={cn(
"group flex h-full flex-col gap-3 rounded-lg border p-4 text-left transition-all",
active
? "border-primary ring-primary/30 shadow-sm ring-2"
: "hover:border-border hover:shadow-sm",
)}
>
<div className="flex items-start gap-3">
<div className="bg-muted rounded-md p-2">
<Icon className="size-4" />
</div>
<div className="space-y-1">
<div className="text-sm leading-none font-semibold">{label}</div>
<p className="text-muted-foreground text-xs leading-snug">
{description}
</p>
</div>
</div>
<div
className={cn(
"relative overflow-hidden rounded-md border text-xs transition-colors",
previewMode === "dark"
? "border-neutral-800 bg-neutral-900 text-neutral-200"
: "border-slate-200 bg-white text-slate-900",
)}
>
<div className="border-border/50 flex items-center gap-2 border-b px-3 py-2">
<div
className={cn(
"h-2 w-2 rounded-full",
previewMode === "dark" ? "bg-emerald-400" : "bg-emerald-500",
)}
/>
<div className="h-2 w-10 rounded-full bg-current/20" />
<div className="h-2 w-6 rounded-full bg-current/15" />
</div>
<div className="grid grid-cols-[1fr_240px] gap-3 px-3 py-3">
<div className="space-y-2">
<div className="h-3 w-3/4 rounded-full bg-current/15" />
<div className="h-3 w-1/2 rounded-full bg-current/10" />
<div className="h-[90px] rounded-md border border-current/10 bg-current/5" />
</div>
<div className="space-y-2">
<div className="flex items-center gap-2">
<div className="h-8 w-8 rounded-md bg-current/10" />
<div className="space-y-2">
<div className="h-2 w-14 rounded-full bg-current/15" />
<div className="h-2 w-10 rounded-full bg-current/10" />
</div>
</div>
<div className="flex flex-col gap-1 rounded-md border border-dashed border-current/15 p-2">
<div className="h-2 w-3/5 rounded-full bg-current/15" />
<div className="h-2 w-2/5 rounded-full bg-current/10" />
</div>
</div>
</div>
</div>
</button>
);
}
@@ -0,0 +1 @@
export { SettingsDialog } from "./settings-dialog";
@@ -0,0 +1,982 @@
"use client";
import {
DownloadIcon,
PenLineIcon,
PlusIcon,
Trash2Icon,
UploadIcon,
} from "lucide-react";
import Link from "next/link";
import { useDeferredValue, useId, useRef, useState } from "react";
import { toast } from "sonner";
import { Streamdown } from "streamdown";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { useI18n } from "@/core/i18n/hooks";
import { exportMemory } from "@/core/memory/api";
import {
useClearMemory,
useCreateMemoryFact,
useDeleteMemoryFact,
useImportMemory,
useMemory,
useUpdateMemoryFact,
} from "@/core/memory/hooks";
import type {
MemoryFactInput,
MemoryFactPatchInput,
UserMemory,
} from "@/core/memory/types";
import { streamdownPlugins } from "@/core/streamdown/plugins";
import { pathOfThread } from "@/core/threads/utils";
import { formatTimeAgo } from "@/core/utils/datetime";
import { SettingsSection } from "./settings-section";
type MemoryViewFilter = "all" | "facts" | "summaries";
type MemoryFact = UserMemory["facts"][number];
type MemorySection = {
title: string;
summary: string;
updatedAt?: string;
};
type MemorySectionGroup = {
title: string;
sections: MemorySection[];
};
type PendingImport = {
fileName: string;
memory: UserMemory;
};
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isMemorySection(value: unknown): value is {
summary: string;
updatedAt: string;
} {
return (
isRecord(value) &&
typeof value.summary === "string" &&
typeof value.updatedAt === "string"
);
}
function isMemoryFact(value: unknown): value is UserMemory["facts"][number] {
return (
isRecord(value) &&
typeof value.id === "string" &&
typeof value.content === "string" &&
typeof value.category === "string" &&
typeof value.confidence === "number" &&
Number.isFinite(value.confidence) &&
typeof value.createdAt === "string" &&
typeof value.source === "string"
);
}
function isImportedMemory(value: unknown): value is UserMemory {
if (!isRecord(value)) {
return false;
}
if (
typeof value.version !== "string" ||
typeof value.lastUpdated !== "string" ||
!isRecord(value.user) ||
!isRecord(value.history) ||
!Array.isArray(value.facts)
) {
return false;
}
return (
isMemorySection(value.user.workContext) &&
isMemorySection(value.user.personalContext) &&
isMemorySection(value.user.topOfMind) &&
isMemorySection(value.history.recentMonths) &&
isMemorySection(value.history.earlierContext) &&
isMemorySection(value.history.longTermBackground) &&
value.facts.every(isMemoryFact)
);
}
type FactFormState = {
content: string;
category: string;
confidence: string;
};
const DEFAULT_FACT_FORM_STATE: FactFormState = {
content: "",
category: "context",
confidence: "0.8",
};
function confidenceToLevelKey(confidence: unknown): {
key: "veryHigh" | "high" | "normal" | "unknown";
value?: number;
} {
if (typeof confidence !== "number" || !Number.isFinite(confidence)) {
return { key: "unknown" };
}
const value = Math.min(1, Math.max(0, confidence));
if (value >= 0.85) return { key: "veryHigh", value };
if (value >= 0.65) return { key: "high", value };
return { key: "normal", value };
}
function formatMemorySection(
section: MemorySection,
t: ReturnType<typeof useI18n>["t"],
): string {
const content =
section.summary.trim() ||
`<span class="text-muted-foreground">${t.settings.memory.markdown.empty}</span>`;
return [
`### ${section.title}`,
content,
"",
section.updatedAt &&
`> ${t.settings.memory.markdown.updatedAt}: \`${formatTimeAgo(section.updatedAt)}\``,
]
.filter(Boolean)
.join("\n");
}
function buildMemorySectionGroups(
memory: UserMemory,
t: ReturnType<typeof useI18n>["t"],
): MemorySectionGroup[] {
return [
{
title: t.settings.memory.markdown.userContext,
sections: [
{
title: t.settings.memory.markdown.work,
summary: memory.user.workContext.summary,
updatedAt: memory.user.workContext.updatedAt,
},
{
title: t.settings.memory.markdown.personal,
summary: memory.user.personalContext.summary,
updatedAt: memory.user.personalContext.updatedAt,
},
{
title: t.settings.memory.markdown.topOfMind,
summary: memory.user.topOfMind.summary,
updatedAt: memory.user.topOfMind.updatedAt,
},
],
},
{
title: t.settings.memory.markdown.historyBackground,
sections: [
{
title: t.settings.memory.markdown.recentMonths,
summary: memory.history.recentMonths.summary,
updatedAt: memory.history.recentMonths.updatedAt,
},
{
title: t.settings.memory.markdown.earlierContext,
summary: memory.history.earlierContext.summary,
updatedAt: memory.history.earlierContext.updatedAt,
},
{
title: t.settings.memory.markdown.longTermBackground,
summary: memory.history.longTermBackground.summary,
updatedAt: memory.history.longTermBackground.updatedAt,
},
],
},
];
}
function summariesToMarkdown(
memory: UserMemory,
sectionGroups: MemorySectionGroup[],
t: ReturnType<typeof useI18n>["t"],
) {
const parts: string[] = [];
parts.push(`## ${t.settings.memory.markdown.overview}`);
parts.push(
`- **${t.common.lastUpdated}**: \`${formatTimeAgo(memory.lastUpdated)}\``,
);
for (const group of sectionGroups) {
parts.push(`\n## ${group.title}`);
for (const section of group.sections) {
parts.push(formatMemorySection(section, t));
}
}
const markdown = parts.join("\n\n");
const lines = markdown.split("\n");
const out: string[] = [];
let i = 0;
for (const line of lines) {
i++;
if (i !== 1 && line.startsWith("## ")) {
if (out.length === 0 || out[out.length - 1] !== "---") {
out.push("---");
}
}
out.push(line);
}
return out.join("\n");
}
function isMemorySummaryEmpty(memory: UserMemory) {
return (
memory.user.workContext.summary.trim() === "" &&
memory.user.personalContext.summary.trim() === "" &&
memory.user.topOfMind.summary.trim() === "" &&
memory.history.recentMonths.summary.trim() === "" &&
memory.history.earlierContext.summary.trim() === "" &&
memory.history.longTermBackground.summary.trim() === ""
);
}
function truncateFactPreview(content: string, maxLength = 140) {
const normalized = content.replace(/\s+/g, " ").trim();
if (normalized.length <= maxLength) {
return normalized;
}
const ellipsis = "...";
if (maxLength <= ellipsis.length) {
return normalized.slice(0, maxLength);
}
return `${normalized.slice(0, maxLength - ellipsis.length)}${ellipsis}`;
}
function upperFirst(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function MemorySettingsPage() {
const { t } = useI18n();
const { memory, isLoading, error } = useMemory();
const clearMemory = useClearMemory();
const createMemoryFact = useCreateMemoryFact();
const deleteMemoryFact = useDeleteMemoryFact();
const importMemoryMutation = useImportMemory();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const updateMemoryFact = useUpdateMemoryFact();
const [clearDialogOpen, setClearDialogOpen] = useState(false);
const [factToDelete, setFactToDelete] = useState<MemoryFact | null>(null);
const [factToEdit, setFactToEdit] = useState<MemoryFact | null>(null);
const [factEditorOpen, setFactEditorOpen] = useState(false);
const [factForm, setFactForm] = useState<FactFormState>(
DEFAULT_FACT_FORM_STATE,
);
const [query, setQuery] = useState("");
const [filter, setFilter] = useState<MemoryViewFilter>("all");
const [pendingImport, setPendingImport] = useState<PendingImport | null>(
null,
);
const [isExporting, setIsExporting] = useState(false);
const deferredQuery = useDeferredValue(query);
const normalizedQuery = deferredQuery.trim().toLowerCase();
const factContentInputId = useId();
const factCategoryInputId = useId();
const factConfidenceInputId = useId();
const factConfidenceHintId = useId();
const clearAllLabel = t.settings.memory.clearAll ?? "Clear all memory";
const clearAllConfirmTitle =
t.settings.memory.clearAllConfirmTitle ?? "Clear all memory?";
const clearAllConfirmDescription =
t.settings.memory.clearAllConfirmDescription ??
"This will remove all saved summaries and facts. This action cannot be undone.";
const clearAllSuccess =
t.settings.memory.clearAllSuccess ?? "All memory cleared";
const factDeleteConfirmTitle =
t.settings.memory.factDeleteConfirmTitle ?? "Delete this fact?";
const factDeleteConfirmDescription =
t.settings.memory.factDeleteConfirmDescription ??
"This fact will be removed from memory immediately. This action cannot be undone.";
const factDeleteSuccess =
t.settings.memory.factDeleteSuccess ?? "Fact deleted";
const addFactLabel = t.settings.memory.addFact;
const addFactTitle = t.settings.memory.addFactTitle;
const editFactTitle = t.settings.memory.editFactTitle;
const addFactSuccess = t.settings.memory.addFactSuccess;
const editFactSuccess = t.settings.memory.editFactSuccess;
const factContentLabel = t.settings.memory.factContentLabel;
const factCategoryLabel = t.settings.memory.factCategoryLabel;
const factConfidenceLabel = t.settings.memory.factConfidenceLabel;
const factContentPlaceholder = t.settings.memory.factContentPlaceholder;
const factCategoryPlaceholder = t.settings.memory.factCategoryPlaceholder;
const factConfidenceHint = t.settings.memory.factConfidenceHint;
const factSave = t.settings.memory.factSave;
const factValidationContent = t.settings.memory.factValidationContent;
const factValidationConfidence = t.settings.memory.factValidationConfidence;
const noFacts = t.settings.memory.noFacts ?? "No saved facts yet.";
const summaryReadOnly = t.settings.memory.summaryReadOnly;
const memoryFullyEmpty =
t.settings.memory.memoryFullyEmpty ?? "No memory saved yet.";
const factPreviewLabel =
t.settings.memory.factPreviewLabel ?? "Fact to delete";
const searchPlaceholder =
t.settings.memory.searchPlaceholder ?? "Search memory";
const filterAll = t.settings.memory.filterAll ?? "All";
const filterFacts = t.settings.memory.filterFacts ?? "Facts";
const filterSummaries = t.settings.memory.filterSummaries ?? "Summaries";
const noMatches = t.settings.memory.noMatches ?? "No matching memory found";
const exportButton = t.settings.memory.exportButton ?? t.common.export;
const exportSuccess =
t.settings.memory.exportSuccess ?? t.common.exportSuccess;
const importButton = t.settings.memory.importButton ?? t.common.import;
const importSuccess = t.settings.memory.importSuccess ?? "Memory imported";
const sectionGroups = memory ? buildMemorySectionGroups(memory, t) : [];
const filteredSectionGroups = sectionGroups
.map((group) => ({
...group,
sections: group.sections.filter((section) =>
normalizedQuery
? `${section.title} ${section.summary}`
.toLowerCase()
.includes(normalizedQuery)
: true,
),
}))
.filter((group) => group.sections.length > 0);
const filteredFacts = memory
? memory.facts.filter((fact) =>
normalizedQuery
? `${fact.content} ${fact.category}`
.toLowerCase()
.includes(normalizedQuery)
: true,
)
: [];
const showSummaries = filter !== "facts";
const showFacts = filter !== "summaries";
const shouldRenderSummariesBlock =
showSummaries && (filteredSectionGroups.length > 0 || !normalizedQuery);
const shouldRenderFactsBlock =
showFacts &&
(filteredFacts.length > 0 || !normalizedQuery || filter === "facts");
const hasMatchingVisibleContent =
!memory ||
(showSummaries && filteredSectionGroups.length > 0) ||
(showFacts && filteredFacts.length > 0);
async function handleExportMemory() {
try {
setIsExporting(true);
const exportedMemory = await exportMemory();
const fileName = `deerflow-memory-${(exportedMemory.lastUpdated || new Date().toISOString()).replace(/[:.]/g, "-")}.json`;
const blob = new Blob([JSON.stringify(exportedMemory, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
toast.success(exportSuccess);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
} finally {
setIsExporting(false);
}
}
async function handleImportFileSelection(event: {
target: HTMLInputElement;
}) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) {
return;
}
try {
const parsed: unknown = JSON.parse(await file.text());
if (!isImportedMemory(parsed)) {
toast.error(t.settings.memory.importInvalidFile);
return;
}
setPendingImport({
fileName: file.name,
memory: parsed,
});
} catch {
toast.error(t.settings.memory.importInvalidFile);
}
}
async function handleConfirmImport() {
if (!pendingImport) {
return;
}
try {
await importMemoryMutation.mutateAsync(pendingImport.memory);
toast.success(importSuccess);
setPendingImport(null);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
async function handleClearMemory() {
try {
await clearMemory.mutateAsync();
toast.success(clearAllSuccess);
setClearDialogOpen(false);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
async function handleDeleteFact() {
if (!factToDelete) return;
try {
await deleteMemoryFact.mutateAsync(factToDelete.id);
toast.success(factDeleteSuccess);
setFactToDelete(null);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
function openCreateFactDialog() {
setFactToEdit(null);
setFactForm(DEFAULT_FACT_FORM_STATE);
setFactEditorOpen(true);
}
function openEditFactDialog(fact: MemoryFact) {
setFactToEdit(fact);
setFactForm({
content: fact.content,
category: fact.category,
confidence: String(fact.confidence),
});
setFactEditorOpen(true);
}
async function handleSaveFact() {
const trimmedContent = factForm.content.trim();
if (!trimmedContent) {
toast.error(factValidationContent);
return;
}
const confidence = Number(factForm.confidence);
if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) {
toast.error(factValidationConfidence);
return;
}
const input: MemoryFactInput = {
content: trimmedContent,
category: factForm.category.trim() || "context",
confidence,
};
try {
if (factToEdit) {
const patchInput: MemoryFactPatchInput = {
content: input.content,
category: input.category,
confidence: input.confidence,
};
await updateMemoryFact.mutateAsync({
factId: factToEdit.id,
input: patchInput,
});
toast.success(editFactSuccess);
} else {
await createMemoryFact.mutateAsync(input);
toast.success(addFactSuccess);
}
setFactEditorOpen(false);
setFactToEdit(null);
setFactForm(DEFAULT_FACT_FORM_STATE);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
}
}
const isFactFormPending =
createMemoryFact.isPending || updateMemoryFact.isPending;
return (
<>
<SettingsSection
title={t.settings.memory.title}
description={t.settings.memory.description}
>
{isLoading ? (
<div className="text-muted-foreground text-sm">
{t.common.loading}
</div>
) : error ? (
<div>Error: {error.message}</div>
) : !memory ? (
<div className="text-muted-foreground text-sm">
{t.settings.memory.empty}
</div>
) : (
<div className="space-y-4">
{isMemorySummaryEmpty(memory) && memory.facts.length === 0 ? (
<div className="text-muted-foreground rounded-lg border border-dashed p-4 text-sm">
{memoryFullyEmpty}
</div>
) : null}
<div className="flex min-w-0 flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
<div className="flex min-w-0 flex-1 flex-col gap-3 sm:flex-row sm:items-center">
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={searchPlaceholder}
className="sm:max-w-xs"
/>
<ToggleGroup
type="single"
value={filter}
onValueChange={(value) => {
if (value) setFilter(value as MemoryViewFilter);
}}
variant="outline"
>
<ToggleGroupItem value="all">{filterAll}</ToggleGroupItem>
<ToggleGroupItem value="facts">{filterFacts}</ToggleGroupItem>
<ToggleGroupItem value="summaries">
{filterSummaries}
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="flex min-w-0 flex-wrap gap-2 xl:justify-end">
<input
ref={fileInputRef}
type="file"
accept=".json,application/json"
className="hidden"
onChange={(event) => void handleImportFileSelection(event)}
/>
<Button
variant="outline"
onClick={() => fileInputRef.current?.click()}
disabled={importMemoryMutation.isPending}
>
<UploadIcon className="mr-2 h-4 w-4" />
{importButton}
</Button>
<Button
variant="outline"
onClick={() => void handleExportMemory()}
disabled={isExporting}
>
<DownloadIcon className="mr-2 h-4 w-4" />
{isExporting ? t.common.loading : exportButton}
</Button>
<Button variant="outline" onClick={openCreateFactDialog}>
<PlusIcon className="mr-2 h-4 w-4" />
{addFactLabel}
</Button>
<Button
variant="destructive"
onClick={() => setClearDialogOpen(true)}
disabled={clearMemory.isPending}
>
{clearMemory.isPending ? t.common.loading : clearAllLabel}
</Button>
</div>
</div>
{!hasMatchingVisibleContent && normalizedQuery ? (
<div className="text-muted-foreground rounded-lg border border-dashed p-4 text-sm">
{noMatches}
</div>
) : null}
{shouldRenderSummariesBlock ? (
<div className="min-w-0 rounded-lg border p-4">
<div className="text-muted-foreground mb-4 text-sm">
{summaryReadOnly}
</div>
<Streamdown
className="size-full min-w-0 [overflow-wrap:anywhere] [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"
{...streamdownPlugins}
>
{summariesToMarkdown(memory, filteredSectionGroups, t)}
</Streamdown>
</div>
) : null}
{shouldRenderFactsBlock ? (
<div className="min-w-0 rounded-lg border p-4">
<div className="mb-4">
<h3 className="text-base font-medium">
{t.settings.memory.markdown.facts}
</h3>
</div>
{filteredFacts.length === 0 ? (
<div className="text-muted-foreground text-sm">
{normalizedQuery ? noMatches : noFacts}
</div>
) : (
<div className="space-y-3">
{filteredFacts.map((fact) => {
const { key } = confidenceToLevelKey(fact.confidence);
const confidenceText =
t.settings.memory.markdown.table.confidenceLevel[key];
return (
<div
key={fact.id}
className="flex flex-col gap-3 rounded-md border p-3 sm:flex-row sm:items-start sm:justify-between"
>
<div className="min-w-0 space-y-2 [overflow-wrap:anywhere]">
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
<span>
<span className="text-muted-foreground">
{t.settings.memory.markdown.table.category}:
</span>{" "}
{upperFirst(fact.category)}
</span>
<span>
<span className="text-muted-foreground">
{t.settings.memory.markdown.table.confidence}:
</span>{" "}
{confidenceText}
</span>
<span>
<span className="text-muted-foreground">
{t.settings.memory.markdown.table.createdAt}:
</span>{" "}
{formatTimeAgo(fact.createdAt)}
</span>
<span>
<span className="text-muted-foreground">
{t.settings.memory.markdown.table.source}:
</span>{" "}
{fact.source === "manual" ? (
t.settings.memory.manualFactSource
) : (
<Link
href={pathOfThread(fact.source)}
className="text-primary underline-offset-4 hover:underline"
>
{t.settings.memory.markdown.table.view}
</Link>
)}
</span>
</div>
<p className="text-sm [overflow-wrap:anywhere]">
{fact.content}
</p>
</div>
<div className="flex shrink-0 items-center gap-1 self-start sm:ml-3">
<Button
variant="ghost"
size="icon"
className="shrink-0"
onClick={() => openEditFactDialog(fact)}
disabled={deleteMemoryFact.isPending}
title={t.common.edit}
aria-label={t.common.edit}
>
<PenLineIcon className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-destructive hover:text-destructive shrink-0"
onClick={() => setFactToDelete(fact)}
disabled={deleteMemoryFact.isPending}
title={t.common.delete}
aria-label={t.common.delete}
>
<Trash2Icon className="h-4 w-4" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
) : null}
</div>
)}
</SettingsSection>
<Dialog open={clearDialogOpen} onOpenChange={setClearDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{clearAllConfirmTitle}</DialogTitle>
<DialogDescription>{clearAllConfirmDescription}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setClearDialogOpen(false)}
disabled={clearMemory.isPending}
>
{t.common.cancel}
</Button>
<Button
variant="destructive"
onClick={() => void handleClearMemory()}
disabled={clearMemory.isPending}
>
{clearMemory.isPending ? t.common.loading : clearAllLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog
open={factEditorOpen}
onOpenChange={(open) => {
setFactEditorOpen(open);
if (!open) {
setFactToEdit(null);
setFactForm(DEFAULT_FACT_FORM_STATE);
}
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>
{factToEdit ? editFactTitle : addFactTitle}
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<label
className="text-sm font-medium"
htmlFor={factContentInputId}
>
{factContentLabel}
</label>
<Textarea
id={factContentInputId}
value={factForm.content}
onChange={(event) =>
setFactForm((current) => ({
...current,
content: event.target.value,
}))
}
placeholder={factContentPlaceholder}
rows={4}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<label
className="text-sm font-medium"
htmlFor={factCategoryInputId}
>
{factCategoryLabel}
</label>
<Input
id={factCategoryInputId}
value={factForm.category}
onChange={(event) =>
setFactForm((current) => ({
...current,
category: event.target.value,
}))
}
placeholder={factCategoryPlaceholder}
/>
</div>
<div className="space-y-2">
<label
className="text-sm font-medium"
htmlFor={factConfidenceInputId}
>
{factConfidenceLabel}
</label>
<Input
id={factConfidenceInputId}
aria-describedby={factConfidenceHintId}
type="number"
min="0"
max="1"
step="0.01"
value={factForm.confidence}
onChange={(event) =>
setFactForm((current) => ({
...current,
confidence: event.target.value,
}))
}
/>
<div
className="text-muted-foreground text-xs"
id={factConfidenceHintId}
>
{factConfidenceHint}
</div>
</div>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => {
setFactEditorOpen(false);
setFactToEdit(null);
setFactForm(DEFAULT_FACT_FORM_STATE);
}}
disabled={isFactFormPending}
>
{t.common.cancel}
</Button>
<Button
onClick={() => void handleSaveFact()}
disabled={isFactFormPending}
>
{isFactFormPending ? t.common.loading : factSave}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog
open={factToDelete !== null}
onOpenChange={(open) => {
if (!open) {
setFactToDelete(null);
}
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{factDeleteConfirmTitle}</DialogTitle>
<DialogDescription>
{factDeleteConfirmDescription}
</DialogDescription>
</DialogHeader>
{factToDelete ? (
<div className="bg-muted rounded-md border p-3 text-sm">
<div className="text-muted-foreground mb-1 font-medium">
{factPreviewLabel}
</div>
<p className="break-words">
{truncateFactPreview(factToDelete.content)}
</p>
</div>
) : null}
<DialogFooter>
<Button
variant="outline"
onClick={() => setFactToDelete(null)}
disabled={deleteMemoryFact.isPending}
>
{t.common.cancel}
</Button>
<Button
variant="destructive"
onClick={() => void handleDeleteFact()}
disabled={deleteMemoryFact.isPending}
>
{deleteMemoryFact.isPending ? t.common.loading : t.common.delete}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog
open={pendingImport !== null}
onOpenChange={(open) => {
if (!open) {
setPendingImport(null);
}
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t.settings.memory.importConfirmTitle}</DialogTitle>
<DialogDescription>
{t.settings.memory.importConfirmDescription}
</DialogDescription>
</DialogHeader>
{pendingImport ? (
<div className="bg-muted rounded-md border p-3 text-sm">
<div>
<span className="text-muted-foreground">
{t.settings.memory.importFileLabel}:
</span>{" "}
{pendingImport.fileName}
</div>
<div>
<span className="text-muted-foreground">
{t.settings.memory.markdown.facts}:
</span>{" "}
{pendingImport.memory.facts.length}
</div>
<div>
<span className="text-muted-foreground">
{t.common.lastUpdated}:
</span>{" "}
{pendingImport.memory.lastUpdated
? formatTimeAgo(pendingImport.memory.lastUpdated)
: "-"}
</div>
</div>
) : null}
<DialogFooter>
<Button
variant="outline"
onClick={() => setPendingImport(null)}
disabled={importMemoryMutation.isPending}
>
{t.common.cancel}
</Button>
<Button
onClick={() => void handleConfirmImport()}
disabled={importMemoryMutation.isPending}
>
{importMemoryMutation.isPending
? t.common.loading
: t.common.import}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,92 @@
"use client";
import { BellIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useI18n } from "@/core/i18n/hooks";
import { useNotification } from "@/core/notification/hooks";
import { useLocalSettings } from "@/core/settings";
import { SettingsSection } from "./settings-section";
export function NotificationSettingsPage() {
const { t } = useI18n();
const { permission, isSupported, requestPermission, showNotification } =
useNotification();
const [settings, setSettings] = useLocalSettings();
const handleRequestPermission = async () => {
await requestPermission();
};
const handleTestNotification = () => {
showNotification(t.settings.notification.testTitle, {
body: t.settings.notification.testBody,
});
};
const handleEnableNotification = async (enabled: boolean) => {
setSettings("notification", {
enabled,
});
};
if (!isSupported) {
return (
<SettingsSection
title={t.settings.notification.title}
description={t.settings.notification.description}
>
<p className="text-muted-foreground text-sm">
{t.settings.notification.notSupported}
</p>
</SettingsSection>
);
}
return (
<SettingsSection
title={t.settings.notification.title}
description={
<div className="flex items-center gap-2">
<div>{t.settings.notification.description}</div>
<div>
<Switch
disabled={permission !== "granted"}
checked={
permission === "granted" && settings.notification.enabled
}
onCheckedChange={handleEnableNotification}
/>
</div>
</div>
}
>
<div className="flex flex-col gap-4">
{permission === "default" && (
<Button onClick={handleRequestPermission} variant="default">
<BellIcon className="mr-2 size-4" />
{t.settings.notification.requestPermission}
</Button>
)}
{permission === "denied" && (
<p className="text-muted-foreground rounded-md border border-amber-200 bg-amber-50 p-3 text-sm dark:border-amber-800 dark:bg-amber-950/50">
{t.settings.notification.deniedHint}
</p>
)}
{permission === "granted" && settings.notification.enabled && (
<div className="flex flex-col gap-4">
<Button onClick={handleTestNotification} variant="outline">
<BellIcon className="mr-2 size-4" />
{t.settings.notification.testButton}
</Button>
</div>
)}
</div>
</SettingsSection>
);
}
@@ -0,0 +1,143 @@
"use client";
import {
BellIcon,
InfoIcon,
BrainIcon,
PaletteIcon,
SparklesIcon,
WrenchIcon,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { AboutSettingsPage } from "@/components/workspace/settings/about-settings-page";
import { AppearanceSettingsPage } from "@/components/workspace/settings/appearance-settings-page";
import { MemorySettingsPage } from "@/components/workspace/settings/memory-settings-page";
import { NotificationSettingsPage } from "@/components/workspace/settings/notification-settings-page";
import { SkillSettingsPage } from "@/components/workspace/settings/skill-settings-page";
import { ToolSettingsPage } from "@/components/workspace/settings/tool-settings-page";
import { useI18n } from "@/core/i18n/hooks";
import { cn } from "@/lib/utils";
type SettingsSection =
| "appearance"
| "memory"
| "tools"
| "skills"
| "notification"
| "about";
type SettingsDialogProps = React.ComponentProps<typeof Dialog> & {
defaultSection?: SettingsSection;
};
export function SettingsDialog(props: SettingsDialogProps) {
const { defaultSection = "appearance", ...dialogProps } = props;
const { t } = useI18n();
const [activeSection, setActiveSection] =
useState<SettingsSection>(defaultSection);
useEffect(() => {
// When opening the dialog, ensure the active section follows the caller's intent.
// This allows triggers like "About" to open the dialog directly on that page.
if (dialogProps.open) {
setActiveSection(defaultSection);
}
}, [defaultSection, dialogProps.open]);
const sections = useMemo(
() => [
{
id: "appearance",
label: t.settings.sections.appearance,
icon: PaletteIcon,
},
{
id: "notification",
label: t.settings.sections.notification,
icon: BellIcon,
},
{
id: "memory",
label: t.settings.sections.memory,
icon: BrainIcon,
},
{ id: "tools", label: t.settings.sections.tools, icon: WrenchIcon },
{ id: "skills", label: t.settings.sections.skills, icon: SparklesIcon },
// { id: "about", label: t.settings.sections.about, icon: InfoIcon },
],
[
t.settings.sections.appearance,
t.settings.sections.memory,
t.settings.sections.tools,
t.settings.sections.skills,
t.settings.sections.notification,
t.settings.sections.about,
],
);
return (
<Dialog
{...dialogProps}
onOpenChange={(open) => props.onOpenChange?.(open)}
>
<DialogContent
className="flex h-[75vh] max-h-[calc(100vh-2rem)] flex-col sm:max-w-5xl md:max-w-6xl"
aria-describedby={undefined}
>
<DialogHeader className="gap-1">
<DialogTitle>{t.settings.title}</DialogTitle>
<p className="text-muted-foreground text-sm">
{t.settings.description}
</p>
</DialogHeader>
<div className="grid min-h-0 flex-1 gap-4 md:grid-cols-[220px_minmax(0,1fr)]">
<nav className="bg-sidebar min-h-0 overflow-y-auto rounded-lg border p-2">
<ul className="space-y-1 pr-1">
{sections.map(({ id, label, icon: Icon }) => {
const active = activeSection === id;
return (
<li key={id}>
<button
type="button"
onClick={() => setActiveSection(id as SettingsSection)}
className={cn(
"flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
active
? "bg-primary text-primary-foreground shadow-sm"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Icon className="size-4" />
<span>{label}</span>
</button>
</li>
);
})}
</ul>
</nav>
<ScrollArea className="h-full min-h-0 min-w-0 rounded-lg border">
<div className="min-w-0 space-y-8 p-6">
{activeSection === "appearance" && <AppearanceSettingsPage />}
{activeSection === "memory" && <MemorySettingsPage />}
{activeSection === "tools" && <ToolSettingsPage />}
{activeSection === "skills" && (
<SkillSettingsPage
onClose={() => props.onOpenChange?.(false)}
/>
)}
{activeSection === "notification" && <NotificationSettingsPage />}
{activeSection === "about" && <AboutSettingsPage />}
</div>
</ScrollArea>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,25 @@
import { cn } from "@/lib/utils";
export function SettingsSection({
className,
title,
description,
children,
}: {
className?: string;
title: React.ReactNode;
description?: React.ReactNode;
children: React.ReactNode;
}) {
return (
<section className={cn(className)}>
<header className="space-y-2">
<div className="text-lg font-semibold">{title}</div>
{description && (
<div className="text-muted-foreground text-sm">{description}</div>
)}
</header>
<main className="mt-4">{children}</main>
</section>
);
}
@@ -0,0 +1,135 @@
"use client";
import { SparklesIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Empty,
EmptyContent,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty";
import {
Item,
ItemActions,
ItemTitle,
ItemContent,
ItemDescription,
} from "@/components/ui/item";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useI18n } from "@/core/i18n/hooks";
import { useEnableSkill, useSkills } from "@/core/skills/hooks";
import type { Skill } from "@/core/skills/type";
import { env } from "@/env";
import { SettingsSection } from "./settings-section";
export function SkillSettingsPage({ onClose }: { onClose?: () => void } = {}) {
const { t } = useI18n();
const { skills, isLoading, error } = useSkills();
return (
<SettingsSection
title={t.settings.skills.title}
description={t.settings.skills.description}
>
{isLoading ? (
<div className="text-muted-foreground text-sm">{t.common.loading}</div>
) : error ? (
<div>Error: {error.message}</div>
) : (
<SkillSettingsList skills={skills} onClose={onClose} />
)}
</SettingsSection>
);
}
function SkillSettingsList({
skills,
onClose,
}: {
skills: Skill[];
onClose?: () => void;
}) {
const { t } = useI18n();
const router = useRouter();
const [filter, setFilter] = useState<string>("public");
const { mutate: enableSkill } = useEnableSkill();
const filteredSkills = useMemo(
() => skills.filter((skill) => skill.category === filter),
[skills, filter],
);
const handleCreateSkill = () => {
onClose?.();
router.push("/?mode=skill");
};
return (
<div className="flex w-full flex-col gap-4">
<header className="flex justify-between">
<div className="flex gap-2">
<Tabs defaultValue="public" onValueChange={setFilter}>
<TabsList variant="line">
<TabsTrigger value="public">{t.common.public}</TabsTrigger>
<TabsTrigger value="custom">{t.common.custom}</TabsTrigger>
</TabsList>
</Tabs>
</div>
<div>
<Button size="sm" onClick={handleCreateSkill}>
<SparklesIcon className="size-4" />
{t.settings.skills.createSkill}
</Button>
</div>
</header>
{filteredSkills.length === 0 && (
<EmptySkill onCreateSkill={handleCreateSkill} />
)}
{filteredSkills.length > 0 &&
filteredSkills.map((skill) => (
<Item className="w-full" variant="outline" key={skill.name}>
<ItemContent>
<ItemTitle>
<div className="flex items-center gap-2">{skill.name}</div>
</ItemTitle>
<ItemDescription className="line-clamp-4">
{skill.description}
</ItemDescription>
</ItemContent>
<ItemActions>
<Switch
checked={skill.enabled}
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"}
onCheckedChange={(checked) =>
enableSkill({ skillName: skill.name, enabled: checked })
}
/>
</ItemActions>
</Item>
))}
</div>
);
}
function EmptySkill({ onCreateSkill }: { onCreateSkill: () => void }) {
const { t } = useI18n();
return (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
<SparklesIcon />
</EmptyMedia>
<EmptyTitle>{t.settings.skills.emptyTitle}</EmptyTitle>
<EmptyDescription>
{t.settings.skills.emptyDescription}
</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button onClick={onCreateSkill}>{t.settings.skills.emptyButton}</Button>
</EmptyContent>
</Empty>
);
}
@@ -0,0 +1,70 @@
"use client";
import {
Item,
ItemActions,
ItemContent,
ItemDescription,
ItemTitle,
} from "@/components/ui/item";
import { Switch } from "@/components/ui/switch";
import { useI18n } from "@/core/i18n/hooks";
import { useMCPConfig, useEnableMCPServer } from "@/core/mcp/hooks";
import type { MCPServerConfig } from "@/core/mcp/types";
import { env } from "@/env";
import { SettingsSection } from "./settings-section";
export function ToolSettingsPage() {
const { t } = useI18n();
const { config, isLoading, error } = useMCPConfig();
return (
<SettingsSection
title={t.settings.tools.title}
description={t.settings.tools.description}
>
{isLoading ? (
<div className="text-muted-foreground text-sm">{t.common.loading}</div>
) : error ? (
<div>Error: {error.message}</div>
) : (
config && <MCPServerList servers={config.mcp_servers} />
)}
</SettingsSection>
);
}
function MCPServerList({
servers,
}: {
servers: Record<string, MCPServerConfig>;
}) {
const { mutate: enableMCPServer } = useEnableMCPServer();
return (
<div className="flex w-full flex-col gap-4">
{Object.entries(servers).map(([name, config]) => (
<Item className="w-full" variant="outline" key={name}>
<ItemContent>
<ItemTitle>
<div className="flex items-center gap-2">
<div>{name}</div>
</div>
</ItemTitle>
<ItemDescription className="line-clamp-4">
{config.description}
</ItemDescription>
</ItemContent>
<ItemActions>
<Switch
checked={config.enabled}
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"}
onCheckedChange={(checked) =>
enableMCPServer({ serverName: name, enabled: checked })
}
/>
</ItemActions>
</Item>
))}
</div>
);
}
@@ -0,0 +1,34 @@
import { cn } from "@/lib/utils";
export function StreamingIndicator({
className,
size = "normal",
}: {
className?: string;
size?: "normal" | "sm";
}) {
const dotSize = size === "sm" ? "w-1.5 h-1.5 mx-0.5" : "w-2 h-2 mx-1";
return (
<div className={cn("flex", className)}>
<div
className={cn(
dotSize,
"animate-bouncing bg-muted-foreground rounded-full opacity-100",
)}
/>
<div
className={cn(
dotSize,
"animate-bouncing bg-muted-foreground rounded-full opacity-100 [animation-delay:0.2s]",
)}
/>
<div
className={cn(
dotSize,
"animate-bouncing bg-muted-foreground rounded-full opacity-100 [animation-delay:0.4s]",
)}
/>
</div>
);
}
@@ -0,0 +1,50 @@
import type { BaseStream } from "@langchain/langgraph-sdk";
import { useEffect } from "react";
import { useI18n } from "@/core/i18n/hooks";
import type { AgentThreadState } from "@/core/threads";
import { useThreadChat } from "./chats";
import { FlipDisplay } from "./flip-display";
export function ThreadTitle({
threadId,
thread,
}: {
className?: string;
threadId: string;
thread: BaseStream<AgentThreadState>;
}) {
const { t } = useI18n();
const { isNewThread } = useThreadChat();
useEffect(() => {
let _title = t.pages.untitled;
if (thread.values?.title) {
_title = thread.values.title;
} else if (isNewThread) {
_title = t.pages.newChat;
}
if (thread.isThreadLoading) {
document.title = `Loading... - ${t.pages.appName}`;
} else {
document.title = `${_title} - ${t.pages.appName}`;
}
}, [
isNewThread,
t.pages.newChat,
t.pages.untitled,
t.pages.appName,
thread.isThreadLoading,
thread.values,
]);
if (!thread.values?.title) {
return null;
}
return (
<FlipDisplay uniqueKey={threadId}>
{thread.values.title ?? "Untitled"}
</FlipDisplay>
);
}
@@ -0,0 +1,99 @@
import { ChevronUpIcon, ListTodoIcon } from "lucide-react";
import { useState } from "react";
import type { Todo } from "@/core/todos";
import { cn } from "@/lib/utils";
import {
QueueItem,
QueueItemContent,
QueueItemIndicator,
QueueList,
} from "../ai-elements/queue";
export function TodoList({
className,
todos,
collapsed: controlledCollapsed,
hidden = false,
onToggle,
}: {
className?: string;
todos: Todo[];
collapsed?: boolean;
hidden?: boolean;
onToggle?: () => void;
}) {
const [internalCollapsed, setInternalCollapsed] = useState(true);
const isControlled = controlledCollapsed !== undefined;
const collapsed = isControlled ? controlledCollapsed : internalCollapsed;
const handleToggle = () => {
if (isControlled) {
onToggle?.();
} else {
setInternalCollapsed((prev) => !prev);
}
};
return (
<div
className={cn(
"flex h-fit w-full origin-bottom translate-y-4 flex-col overflow-hidden rounded-t-xl border border-b-0 bg-white backdrop-blur-sm transition-all duration-200 ease-out",
hidden ? "pointer-events-none translate-y-8 opacity-0" : "",
className,
)}
>
<header
className={cn(
"bg-accent flex min-h-8 shrink-0 cursor-pointer items-center justify-between px-4 text-sm transition-all duration-300 ease-out",
)}
onClick={handleToggle}
>
<div className="text-muted-foreground">
<div className="flex items-center justify-center gap-2">
<ListTodoIcon className="size-4" />
<div>To-dos</div>
</div>
</div>
<div>
<ChevronUpIcon
className={cn(
"text-muted-foreground size-4 transition-transform duration-300 ease-out",
collapsed ? "" : "rotate-180",
)}
/>
</div>
</header>
<main
className={cn(
"bg-accent flex grow px-2 transition-all duration-300 ease-out",
collapsed ? "h-0 pb-3" : "h-28 pb-4",
)}
>
<QueueList className="bg-background mt-0 w-full rounded-t-xl">
{todos.map((todo, i) => (
<QueueItem key={i + (todo.content ?? "")}>
<div className="flex items-center gap-2">
<QueueItemIndicator
className={
todo.status === "in_progress" ? "bg-primary/70" : ""
}
completed={todo.status === "completed"}
/>
<QueueItemContent
className={
todo.status === "in_progress" ? "text-primary/70" : ""
}
completed={todo.status === "completed"}
>
{todo.content}
</QueueItemContent>
</div>
</QueueItem>
))}
</QueueList>
</main>
</div>
);
}
@@ -0,0 +1,88 @@
"use client";
import type { Message } from "@langchain/langgraph-sdk";
import { CoinsIcon } from "lucide-react";
import { useMemo } from "react";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useI18n } from "@/core/i18n/hooks";
import { accumulateUsage, formatTokenCount } from "@/core/messages/usage";
import { cn } from "@/lib/utils";
interface TokenUsageIndicatorProps {
messages: Message[];
enabled?: boolean;
className?: string;
}
export function TokenUsageIndicator({
messages,
enabled = false,
className,
}: TokenUsageIndicatorProps) {
const { t } = useI18n();
const usage = useMemo(() => accumulateUsage(messages), [messages]);
if (!enabled) {
return null;
}
return (
<Tooltip delayDuration={200}>
<TooltipTrigger asChild>
<button
type="button"
className={cn(
"text-muted-foreground bg-background/70 flex cursor-default items-center gap-1.5 rounded-full border px-2 py-1 text-xs",
!usage && "opacity-60",
className,
)}
>
<CoinsIcon size={14} />
<span>{t.tokenUsage.label}</span>
<span className="font-mono">
{usage ? formatTokenCount(usage.totalTokens) : "-"}
</span>
</button>
</TooltipTrigger>
<TooltipContent side="bottom" align="end">
<div className="space-y-1 text-xs">
<div className="font-medium">{t.tokenUsage.title}</div>
{usage ? (
<>
<div className="flex justify-between gap-4">
<span>{t.tokenUsage.input}</span>
<span className="font-mono">
{formatTokenCount(usage.inputTokens)}
</span>
</div>
<div className="flex justify-between gap-4">
<span>{t.tokenUsage.output}</span>
<span className="font-mono">
{formatTokenCount(usage.outputTokens)}
</span>
</div>
<div className="border-t pt-1">
<div className="flex justify-between gap-4">
<span>{t.tokenUsage.total}</span>
<span className="font-mono font-medium">
{formatTokenCount(usage.totalTokens)}
</span>
</div>
</div>
</>
) : (
<div className="text-muted-foreground max-w-56">
{t.tokenUsage.unavailable}
</div>
)}
</div>
</TooltipContent>
</Tooltip>
);
}
@@ -0,0 +1,23 @@
"use client";
import {
Tooltip as TooltipPrimitive,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
export function Tooltip({
children,
content,
...props
}: {
children: React.ReactNode;
content?: React.ReactNode;
}) {
return (
<TooltipPrimitive delayDuration={500} {...props}>
<TooltipTrigger asChild>{children}</TooltipTrigger>
<TooltipContent>{content}</TooltipContent>
</TooltipPrimitive>
);
}
@@ -0,0 +1,74 @@
"use client";
import { useSearchParams } from "next/navigation";
import { useEffect, useMemo } from "react";
import { useI18n } from "@/core/i18n/hooks";
import { cn } from "@/lib/utils";
import { AuroraText } from "../ui/aurora-text";
let waved = false;
export function Welcome({
className,
mode,
}: {
className?: string;
mode?: "ultra" | "pro" | "thinking" | "flash";
}) {
const { t } = useI18n();
const searchParams = useSearchParams();
const isUltra = useMemo(() => mode === "ultra", [mode]);
const colors = useMemo(() => {
if (isUltra) {
return ["#efefbb", "#e9c665", "#e3a812"];
}
return ["var(--color-foreground)"];
}, [isUltra]);
useEffect(() => {
waved = true;
}, []);
return (
<div
className={cn(
"mx-auto flex w-full flex-col items-center justify-center gap-2 px-8 py-4 text-center",
className,
)}
>
<div className="text-2xl font-bold">
{searchParams.get("mode") === "skill" ? (
`✨ ${t.welcome.createYourOwnSkill} ✨`
) : (
<div className="flex items-center gap-2">
<div className={cn("inline-block", !waved ? "animate-wave" : "")}>
{isUltra ? "🚀" : "👋"}
</div>
<AuroraText colors={colors}>{t.welcome.greeting}</AuroraText>
</div>
)}
</div>
{searchParams.get("mode") === "skill" ? (
<div className="text-muted-foreground text-sm">
{t.welcome.createYourOwnSkillDescription.includes("\n") ? (
<pre className="font-sans whitespace-pre">
{t.welcome.createYourOwnSkillDescription}
</pre>
) : (
<p>{t.welcome.createYourOwnSkillDescription}</p>
)}
</div>
) : (
<div className="text-muted-foreground text-sm">
{t.welcome.description.includes("\n") ? (
<pre className="font-sans whitespace-pre">
{t.welcome.description}
</pre>
) : (
<p>{t.welcome.description}</p>
)}
</div>
)}
</div>
);
}
@@ -0,0 +1,135 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useMemo } from "react";
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { useI18n } from "@/core/i18n/hooks";
import { cn } from "@/lib/utils";
import { GithubIcon } from "./github-icon";
import { Tooltip } from "./tooltip";
export function WorkspaceContainer({
className,
children,
...props
}: React.ComponentProps<"div">) {
return (
<div className={cn("flex h-screen w-full flex-col", className)} {...props}>
{children}
</div>
);
}
export function WorkspaceHeader({
className,
children,
...props
}: React.ComponentProps<"header">) {
const { t } = useI18n();
const pathname = usePathname();
const segments = useMemo(() => {
const parts = pathname?.split("/") || [];
if (parts.length > 0) {
return parts.slice(1, 3);
}
}, [pathname]);
return (
<header
className={cn(
"top-0 right-0 left-0 z-20 flex h-16 shrink-0 items-center justify-between gap-2 border-b backdrop-blur-sm transition-[width,height] ease-out group-has-data-[collapsible=icon]/sidebar-wrapper:h-12",
className,
)}
{...props}
>
<div className="flex items-center gap-2 px-4">
<Breadcrumb>
<BreadcrumbList>
{segments?.[0] && (
<BreadcrumbItem className="hidden md:block">
<BreadcrumbLink asChild>
<Link href={`/${segments[0]}`}>
{nameOfSegment(segments[0], t)}
</Link>
</BreadcrumbLink>
</BreadcrumbItem>
)}
{segments?.[1] && (
<>
<BreadcrumbSeparator className="hidden md:block" />
<BreadcrumbItem>
{segments.length >= 2 ? (
<BreadcrumbLink asChild>
<Link href={`/${segments[0]}/${segments[1]}`}>
{nameOfSegment(segments[1], t)}
</Link>
</BreadcrumbLink>
) : (
<BreadcrumbPage>
{nameOfSegment(segments[1], t)}
</BreadcrumbPage>
)}
</BreadcrumbItem>
</>
)}
{children && (
<>
<BreadcrumbSeparator />
{children}
</>
)}
</BreadcrumbList>
</Breadcrumb>
</div>
<div className="pr-4">
<Tooltip content={t.workspace.githubTooltip}>
<a
href="https://github.com/bytedance/deer-flow"
target="_blank"
rel="noopener noreferrer"
className="opacity-75 transition hover:opacity-100"
>
<GithubIcon className="size-6" />
</a>
</Tooltip>
</div>
</header>
);
}
export function WorkspaceBody({
className,
children,
...props
}: React.ComponentProps<"main">) {
return (
<main
className={cn(
"relative flex min-h-0 w-full flex-1 flex-col items-center",
className,
)}
{...props}
>
<div className="flex h-full w-full flex-col items-center">{children}</div>
</main>
);
}
function nameOfSegment(
segment: string | undefined,
t: ReturnType<typeof useI18n>["t"],
) {
if (!segment) return t.common.home;
if (segment === "workspace") return t.breadcrumb.workspace;
if (segment === "chats") return t.breadcrumb.chats;
return segment[0]?.toUpperCase() + segment.slice(1);
}
@@ -0,0 +1,97 @@
"use client";
import { ChevronLeft, ChevronRight } from "lucide-react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useSidebar } from "@/components/ui/sidebar";
import { useI18n } from "@/core/i18n/hooks";
import { env } from "@/env";
import { cn } from "@/lib/utils";
function BrandMark({ className }: { className?: string }) {
return (
<div
className={cn(
"bg-primary text-primary-foreground flex size-9 shrink-0 items-center justify-center rounded-lg text-sm font-bold shadow-sm",
className,
)}
aria-hidden
>
C
</div>
);
}
function SidebarCollapseButton({ className }: { className?: string }) {
const { open, toggleSidebar } = useSidebar();
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
type="button"
variant="ghost"
size="icon"
className={cn(
"text-muted-foreground hover:text-sidebar-foreground size-8 shrink-0",
className,
)}
onClick={() => toggleSidebar()}
>
{open ? (
<ChevronLeft className="size-4" strokeWidth={2} />
) : (
<ChevronRight className="size-4" strokeWidth={2} />
)}
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
}
export function WorkspaceHeader({ className }: { className?: string }) {
const { t } = useI18n();
const { state } = useSidebar();
const titleBlock = (
<div className="min-w-0 flex-1">
<div className="text-sidebar-foreground truncate text-sm font-semibold leading-tight tracking-tight">
{t.pages.appName}
</div>
<div className="text-muted-foreground truncate text-[11px] leading-tight">
{t.pages.brandSubtitle}
</div>
</div>
);
return (
<div
className={cn(
"group/workspace-header border-sidebar-border/80 border-b",
className,
)}
>
{state === "collapsed" ? (
<div className="group/workspace-header relative flex min-h-[4.25rem] items-center justify-center py-3">
<div className="rounded-[1.15rem] bg-white/92 p-1.5 shadow-[0_16px_32px_-24px_rgba(15,23,42,0.3)] ring-1 ring-black/4 transition-opacity group-hover/workspace-header:pointer-events-none group-hover/workspace-header:opacity-0">
<BrandMark className="size-10 rounded-[0.95rem] text-base" />
</div>
<div className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover/workspace-header:opacity-100">
<SidebarCollapseButton className="rounded-2xl bg-white/92 shadow-sm ring-1 ring-black/5" />
</div>
</div>
) : (
<div className="flex items-center gap-2.5 px-2.5 py-3">
<BrandMark />
{env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" ? (
<Link href="/workspace/chats/new" className="min-w-0 flex-1 outline-none">
{titleBlock}
</Link>
) : (
titleBlock
)}
<SidebarCollapseButton />
</div>
)}
</div>
);
}
@@ -0,0 +1,65 @@
"use client";
import { BotIcon, ListChecks, MessageSquarePlus, MessagesSquare } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
SidebarGroup,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { useI18n } from "@/core/i18n/hooks";
export function WorkspaceNavChatList() {
const { t } = useI18n();
const pathname = usePathname();
return (
<SidebarGroup className="px-2 pt-2">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
isActive={pathname === "/workspace/chats/new"}
asChild
>
<Link className="text-sidebar-foreground" href="/workspace/chats/new">
<MessageSquarePlus />
<span>{t.sidebar.newChat}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton isActive={pathname === "/workspace/chats"} asChild>
<Link className="text-sidebar-foreground" href="/workspace/chats">
<MessagesSquare />
<span>{t.sidebar.chats}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton
isActive={pathname.startsWith("/workspace/agents")}
asChild
>
<Link className="text-sidebar-foreground" href="/workspace/agents">
<BotIcon />
<span>{t.sidebar.agents}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton
isActive={pathname === "/workspace/scheduled/tasks"}
asChild
>
<Link className="text-sidebar-foreground" href="/workspace/scheduled/tasks">
<ListChecks />
<span>任务管理</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
);
}
@@ -0,0 +1,104 @@
"use client";
import { ChevronsUpDown, Settings2Icon, SettingsIcon } from "lucide-react";
import { useEffect, useState } from "react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import { useI18n } from "@/core/i18n/hooks";
import { SettingsDialog } from "./settings";
function NavMenuButtonContent({
isSidebarOpen,
t,
}: {
isSidebarOpen: boolean;
t: ReturnType<typeof useI18n>["t"];
}) {
return isSidebarOpen ? (
<div className="text-sidebar-foreground/85 flex w-full items-center gap-2 text-left text-sm">
<SettingsIcon className="size-4" />
<span>{t.workspace.settingsAndMore}</span>
<ChevronsUpDown className="text-sidebar-foreground/55 ml-auto size-4" />
</div>
) : (
<div className="flex size-full items-center justify-center">
<SettingsIcon className="text-sidebar-foreground/80 size-4" />
</div>
);
}
export function WorkspaceNavMenu() {
const [settingsOpen, setSettingsOpen] = useState(false);
const [settingsDefaultSection, setSettingsDefaultSection] = useState<
"appearance" | "memory" | "tools" | "skills" | "notification" | "about"
>("appearance");
const [mounted, setMounted] = useState(false);
const { open: isSidebarOpen } = useSidebar();
const { t } = useI18n();
useEffect(() => {
setMounted(true);
}, []);
return (
<>
<SettingsDialog
open={settingsOpen}
onOpenChange={setSettingsOpen}
defaultSection={settingsDefaultSection}
/>
<SidebarMenu className="w-full">
<SidebarMenuItem>
{mounted ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton
size="lg"
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
<NavMenuButtonContent isSidebarOpen={isSidebarOpen} t={t} />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
align="end"
sideOffset={4}
>
<DropdownMenuGroup>
<DropdownMenuItem
onClick={() => {
setSettingsDefaultSection("appearance");
setSettingsOpen(true);
}}
>
<Settings2Icon />
{t.common.settings}
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
</DropdownMenuContent>
</DropdownMenu>
) : (
<SidebarMenuButton size="lg" className="pointer-events-none">
<NavMenuButtonContent isSidebarOpen={isSidebarOpen} t={t} />
</SidebarMenuButton>
)}
</SidebarMenuItem>
</SidebarMenu>
</>
);
}
@@ -0,0 +1,38 @@
"use client";
import {
Sidebar,
SidebarHeader,
SidebarContent,
SidebarFooter,
SidebarRail,
useSidebar,
} from "@/components/ui/sidebar";
import { RecentChatList } from "./recent-chat-list";
import { WorkspaceHeader } from "./workspace-header";
import { WorkspaceNavChatList } from "./workspace-nav-chat-list";
import { WorkspaceNavMenu } from "./workspace-nav-menu";
export function WorkspaceSidebar({
...props
}: React.ComponentProps<typeof Sidebar>) {
const { open: isSidebarOpen } = useSidebar();
return (
<>
<Sidebar variant="sidebar" collapsible="icon" {...props}>
<SidebarHeader className="py-0">
<WorkspaceHeader />
</SidebarHeader>
<SidebarContent>
<WorkspaceNavChatList />
{isSidebarOpen && <RecentChatList />}
</SidebarContent>
<SidebarFooter>
<WorkspaceNavMenu />
</SidebarFooter>
<SidebarRail />
</Sidebar>
</>
);
}