Files
deerflow-code/frontend-web/src/pages/NewAgentPage.tsx
T

667 lines
25 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import {
ArrowLeftIcon,
CheckCircleIcon,
SaveIcon,
} from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
PromptInput,
PromptInputFooter,
PromptInputSubmit,
PromptInputTextarea,
} from "@/components/ai-elements/prompt-input";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
} from "@/components/ui/resizable";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { ArtifactsProvider } from "@/components/workspace/artifacts";
import {
MessageList,
type SetupAgentApprovalPayload,
} from "@/components/workspace/messages";
import { ThreadContext } from "@/components/workspace/messages/context";
import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector";
import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog";
import { getAPIClient } from "@/core/api";
import type { Agent } from "@/core/agents";
import {
AgentNameCheckError,
checkAgentName,
createAgent,
updateAgent,
} from "@/core/agents/api";
import { getStoredAuth } from "@/core/auth";
import { useLiveAccount } from "@/core/auth/use-live-account";
import { useI18n } from "@/core/i18n/hooks";
import { useModels } from "@/core/models/hooks";
import { isAgentSkillCandidate } from "@/core/skills";
import { useSkills } from "@/core/skills/hooks";
import { useThreadStream } from "@/core/threads/hooks";
import { uuid } from "@/core/utils/uuid";
import { cn } from "@/lib/utils";
const DEFAULT_SELECTED_SKILL_COUNT = 3;
function getCreateAgentErrorMessage(
error: unknown,
networkErrorMessage: string,
fallbackMessage: string,
) {
if (error instanceof TypeError && error.message === "Failed to fetch") {
return networkErrorMessage;
}
if (error instanceof Error && error.message) {
return error.message;
}
return fallbackMessage;
}
export default function NewAgentPage() {
const { t } = useI18n();
const router = useRouter();
// 从「常用对话」点击某条智能体创建(bootstrap)会话回到本页时,URL 带 thread_id,
// 用它恢复该会话(加载历史消息、继续对话);正常进入则新开一个会话。
const { thread_id: resumeThreadId } = useParams<{ thread_id?: string }>();
const generatedThreadId = useMemo(() => uuid(), []);
const threadId = resumeThreadId || generatedThreadId;
const [nameInput, setNameInput] = useState("");
const [descriptionInput, setDescriptionInput] = useState("");
const [soulInput, setSoulInput] = useState("");
const [modelInput, setModelInput] = useState<string>("");
const [chatModelInput, setChatModelInput] = useState<string>("");
const [templateNameInput, setTemplateNameInput] = useState("");
// 会商席位「技能识别强化」开关(弱模型补偿)。默认关。
const [seatSkillDirectiveInput, setSeatSkillDirectiveInput] = useState(false);
const [formError, setFormError] = useState("");
const [agentId, setAgentId] = useState("");
const [agent, setAgent] = useState<Agent | null>(null);
const [isCreatingAgent, setIsCreatingAgent] = useState(false);
const [isSavingDraft, setIsSavingDraft] = useState(false);
const [selectedSkills, setSelectedSkills] = useState<string[]>([]);
const [isSkillSelectionTouched, setIsSkillSelectionTouched] = useState(false);
const [detailSkillName, setDetailSkillName] = useState<string | null>(null);
// 恢复已有 bootstrap 会话时该 thread 已存在,无需再 create(置为 true,跳过创建)。
const [threadPrepared, setThreadPrepared] = useState(!!resumeThreadId);
const { skills, isLoading: isSkillsLoading } = useSkills();
const { models, isLoading: isModelsLoading } = useModels();
// 创建请求的归属账号取自「实时」token(apiFetch 每次都重读 localStorage),而非
// 本页加载时缓存的身份 —— 用 live 账号提示归属并检测账号是否在会话中途被切换。
const live = useLiveAccount();
// 可配置的技能限定为「内置 + 自己的 + 已发布到广场的」,
// 其他用户未发布的自定义技能不可选。
const storedAuth = useMemo(() => getStoredAuth(), []);
const enabledSkills = useMemo(
() =>
skills.filter((skill) =>
isAgentSkillCandidate(
skill,
storedAuth?.user_id ?? null,
storedAuth?.system_role === "admin",
),
),
[skills, storedAuth],
);
useEffect(() => {
if (isSkillSelectionTouched) {
return;
}
setSelectedSkills(
enabledSkills
.slice(0, DEFAULT_SELECTED_SKILL_COUNT)
.map((skill) => skill.name),
);
}, [enabledSkills, isSkillSelectionTouched]);
// Seed both model selectors with the first available model the first time
// models load. The user can still change either independently afterwards.
useEffect(() => {
if (models.length === 0) {
return;
}
const first = models[0]!.name;
setModelInput((prev) =>
prev && models.some((m) => m.name === prev) ? prev : first,
);
setChatModelInput((prev) =>
prev && models.some((m) => m.name === prev) ? prev : first,
);
}, [models]);
const resolvedModelInput = useMemo(() => {
if (models.length === 0) {
return "";
}
if (modelInput && models.some((m) => m.name === modelInput)) {
return modelInput;
}
return models[0]!.name;
}, [modelInput, models]);
const resolvedChatModelInput = useMemo(() => {
if (models.length === 0) {
return "";
}
if (chatModelInput && models.some((m) => m.name === chatModelInput)) {
return chatModelInput;
}
return models[0]!.name;
}, [chatModelInput, models]);
const [thread, sendMessage] = useThreadStream({
threadId,
assistantId: agentId || undefined,
context: {
mode: "flash",
is_bootstrap: true,
model_name: chatModelInput || undefined,
},
onToolEnd() {
// setup_agent never actually executes in this flow 鈥?it gets
// intercepted by SetupAgentApprovalMiddleware and the form is filled
// from the approval ToolMessage payload (handleApproveSetupAgent).
// No agent record is fetched/refreshed during chat.
},
});
const ensureThreadExists = useCallback(async () => {
if (threadPrepared) {
return;
}
await getAPIClient().threads.create({ threadId, metadata: { thread_type: "bootstrap" } });
setThreadPrepared(true);
}, [threadId, threadPrepared]);
const validateForm = useCallback(() => {
// Name is intentionally NOT required here so the user can start chatting
// immediately. If they leave it blank, ensureAgent() generates a placeholder
// and writes it back into the input so they can rename it later.
// Zero skills is a valid choice: the backend treats an empty/omitted skill
// list as "no skills" for custom agents (never "all skills").
setFormError("");
return nameInput.trim();
}, [nameInput]);
const ensureAgent = useCallback(async () => {
const provided = validateForm();
if (provided === null) {
return null;
}
let name = provided;
if (!name) {
// Names are display-only and may collide, so a timestamped placeholder
// is safe to send to the backend just to satisfy the required-field
// validation. Intentionally NOT written back into the visible input 鈥?
// the user wants the name box to stay blank while they chat, and we
// refill it later (with the model's proposed name) on setup_agent
// approval.
name = `未命名智能体-${Date.now().toString(36)}`;
}
const modelOverride = modelInput.trim() || null;
if (agentId) {
setIsSavingDraft(true);
try {
const updated = await updateAgent(agentId, {
name,
description: descriptionInput,
soul: soulInput,
skills: selectedSkills,
model: modelOverride,
template_name: templateNameInput.trim(),
seat_skill_directive: seatSkillDirectiveInput,
});
setAgent(updated);
return updated;
} catch (error) {
toast.error(error instanceof Error ? error.message : String(error));
return null;
} finally {
setIsSavingDraft(false);
}
}
setIsCreatingAgent(true);
try {
await checkAgentName(name);
const created = await createAgent({
name,
description: descriptionInput,
soul: soulInput,
skills: selectedSkills,
model: modelOverride,
template_name: templateNameInput.trim(),
seat_skill_directive: seatSkillDirectiveInput,
});
setAgentId(created.id);
setAgent(created);
return created;
} catch (error) {
if (
error instanceof AgentNameCheckError &&
error.reason === "backend_unreachable"
) {
setFormError(t.agents.nameStepNetworkError);
} else {
setFormError(
getCreateAgentErrorMessage(
error,
t.agents.nameStepNetworkError,
t.agents.nameStepCheckError,
),
);
}
return null;
} finally {
setIsCreatingAgent(false);
}
}, [
agentId,
descriptionInput,
modelInput,
selectedSkills,
soulInput,
templateNameInput,
seatSkillDirectiveInput,
t.agents.nameStepCheckError,
t.agents.nameStepNetworkError,
validateForm,
]);
const handleSaveAgent = useCallback(async () => {
// 新建时归属账号 = 创建请求所用的实时 token 对应账号。若本页加载后登录被切换
// (常见于另一标签页登录了别的账号),现在创建会把智能体静默归到新账号名下。
// 先弹确认,避免「用 A 账号创建却归到 B 账号」。更新已有智能体不改归属,故跳过。
if (!agentId && live.switched) {
const ok = window.confirm(
`当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` +
`现在创建将把该智能体归属到「${live.displayName}」名下。\n` +
`如需归属「${live.mountDisplayName}」,请取消并刷新页面后重新登录。\n\n仍要以「${live.displayName}」创建吗?`,
);
if (!ok) {
return;
}
}
const saved = await ensureAgent();
if (!saved) {
return;
}
toast.success(
agentId
? `智能体「${saved.name}」已保存`
: `智能体「${saved.name}」已创建(归属账号:${live.displayName})`,
);
router.push("/page/workspace/agents");
}, [
agentId,
ensureAgent,
live.displayName,
live.mountDisplayName,
live.switched,
router,
]);
const handleChatSubmit = useCallback(
async (text: string) => {
const trimmed = text.trim();
if (!trimmed || thread.isLoading) {
return;
}
// Chat is purely a discussion channel. The agent record is only
// created when the user explicitly clicks Save (top-right). If the
// model proposes a config via setup_agent, our approval handler
// prefills the form locally 鈥?it does NOT persist anything.
await ensureThreadExists();
await sendMessage(threadId, { text: trimmed, files: [] });
},
[ensureThreadExists, sendMessage, thread.isLoading, threadId],
);
const handleApproveSetupAgent = useCallback(
async (payload: SetupAgentApprovalPayload) => {
// Approving the model's setup_agent proposal **does not** persist
// anything 鈥?it only mirrors the proposal into the form so the user
// can review it. Creation/update happens later when the user clicks
// the top-right Save button.
const proposedName = payload.name?.trim() ?? "";
const newDescription = payload.description ?? "";
const newSoul = payload.soul ?? "";
const newSkills = payload.skills ?? [];
if (proposedName) {
setNameInput(proposedName);
}
setDescriptionInput(newDescription);
setSoulInput(newSoul);
setSelectedSkills(newSkills);
setIsSkillSelectionTouched(true);
toast.success("已套用模型建议,可继续编辑或点保存");
},
[],
);
const handleRejectSetupAgent = useCallback(
async () => {
await handleChatSubmit("我暂时不批准创建这个智能体配置,请继续帮我调整。");
},
[handleChatSubmit],
);
const handleSkillSelectionChange = useCallback((next: string[]) => {
setIsSkillSelectionTouched(true);
setFormError("");
setSelectedSkills(next);
}, []);
const busy = isCreatingAgent || isSavingDraft || thread.isLoading;
return (
<ThreadContext.Provider value={{ thread }}>
<ArtifactsProvider>
<div className="flex size-full flex-col">
<header className="flex shrink-0 items-center justify-between gap-3 border-b px-4 py-3">
<div className="flex items-center gap-3">
<Button
variant="ghost"
size="icon-sm"
onClick={() => router.push("/page/workspace/agents")}
>
<ArrowLeftIcon className="h-4 w-4" />
</Button>
<h1 className="text-sm font-semibold">创建智能体</h1>
</div>
{agent ? (
<Button
variant="outline"
size="sm"
onClick={() => router.push(`/page/workspace/agents/${agent.id}/chats/new`)}
>
<CheckCircleIcon className="h-4 w-4" />
开始对话
</Button>
) : null}
</header>
<ResizablePanelGroup
id="new-agent-config-panels"
orientation="horizontal"
defaultLayout={{ chat: 62, config: 38 }}
className="min-h-0 flex-1"
>
<ResizablePanel
id="chat"
defaultSize={62}
minSize={40}
className="min-h-0"
>
<section className="flex size-full min-h-0 flex-col">
<div className="min-h-0 flex-1">
<MessageList
className="size-full"
threadId={threadId}
thread={thread}
onClarificationSubmit={handleChatSubmit}
onSetupAgentApprove={handleApproveSetupAgent}
onSetupAgentReject={handleRejectSetupAgent}
/>
</div>
<div className="bg-background shrink-0 space-y-2 border-t px-4 py-4">
<div className="flex items-center gap-2">
<span className="text-muted-foreground text-xs">
当前对话模型
</span>
{isModelsLoading || models.length === 0 ? (
<div className="border-input bg-background text-muted-foreground flex h-7 min-w-[10rem] items-center rounded-md border px-2 text-xs shadow-xs dark:border-[#1B477E] dark:bg-[#022248]">
{isModelsLoading ? "加载中…" : "暂无模型"}
</div>
) : (
<Select
value={resolvedChatModelInput}
onValueChange={setChatModelInput}
disabled={thread.isLoading}
>
<SelectTrigger
className={cn(
"border-input bg-background h-7 min-w-[10rem] px-2 text-xs shadow-xs outline-none",
"dark:border-[#1B477E] dark:bg-[#022248] dark:text-[#AACEFF] dark:hover:bg-[#022248]",
"data-[placeholder]:text-muted-foreground",
"[&_svg]:dark:text-[#AACEE2]",
)}
>
<SelectValue placeholder="选择模型" />
</SelectTrigger>
<SelectContent
position="popper"
className="w-[var(--radix-select-trigger-width)] dark:border-[#1B477E] dark:bg-[#022248]"
>
{models.map((model) => (
<SelectItem
key={model.name}
value={model.name}
className="dark:text-[#AACEFF] dark:data-[highlighted]:bg-[#0062D9] dark:data-[highlighted]:text-white"
>
{model.display_name || model.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
<PromptInput
onSubmit={({ text }) => {
if (thread.isLoading) {
void thread.stop();
return;
}
void handleChatSubmit(text);
}}
>
<PromptInputTextarea
placeholder="直接告诉模型你想要什么样的智能体,或回答模型的问题"
disabled={thread.isLoading}
/>
<PromptInputFooter className="justify-end">
<PromptInputSubmit
status={thread.isLoading ? "streaming" : "ready"}
/>
</PromptInputFooter>
</PromptInput>
</div>
</section>
</ResizablePanel>
<ResizableHandle withHandle />
<ResizablePanel
id="config"
defaultSize={38}
minSize={24}
maxSize={60}
className="min-h-0"
>
<aside className="bg-background size-full min-h-0 overflow-y-auto">
<div className="space-y-5 p-4">
<div>
<h2 className="text-sm font-semibold">智能体配置</h2>
<p className="text-muted-foreground mt-1 text-xs">
这些内容会作为创建智能体时的初始配置。
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">名称</label>
<Input
placeholder="例如:合同审查智能体"
value={nameInput}
onChange={(event) => {
setNameInput(event.currentTarget.value);
setFormError("");
}}
className={cn(formError && "border-destructive")}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">描述</label>
<Textarea
placeholder="简要说明这个智能体擅长什么"
value={descriptionInput}
onChange={(event) =>
setDescriptionInput(event.currentTarget.value)
}
className="min-h-24 resize-none"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">模型</label>
{isModelsLoading || models.length === 0 ? (
<div className="border-input bg-background text-muted-foreground flex h-9 w-full items-center rounded-md border px-3 text-sm shadow-xs dark:border-[#1B477E] dark:bg-[#022248]">
{isModelsLoading ? "加载模型…" : "暂无可用模型"}
</div>
) : (
<Select
value={resolvedModelInput}
onValueChange={setModelInput}
>
<SelectTrigger
className={cn(
"border-input bg-background h-9 w-full shadow-xs outline-none",
"dark:border-[#1B477E] dark:bg-[#022248] dark:text-[#AACEFF] dark:hover:bg-[#022248]",
"data-[placeholder]:text-muted-foreground",
"[&_svg]:dark:text-[#AACEE2]",
)}
>
<SelectValue placeholder="选择模型" />
</SelectTrigger>
<SelectContent
position="popper"
className="w-[var(--radix-select-trigger-width)] dark:border-[#1B477E] dark:bg-[#022248]"
>
{models.map((model) => (
<SelectItem
key={model.name}
value={model.name}
className="dark:text-[#AACEFF] dark:data-[highlighted]:bg-[#0062D9] dark:data-[highlighted]:text-white"
>
{model.display_name || model.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
<p className="text-muted-foreground text-xs">
该智能体被使用时调用的模型。
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">入库模板名</label>
<Input
placeholder="例如:临时策略库(留空表示不支持入库)"
value={templateNameInput}
onChange={(event) =>
setTemplateNameInput(event.currentTarget.value)
}
/>
<p className="text-muted-foreground text-xs">
配置后,该智能体对话中生成的 Markdown
文件右上角会出现"发布入库"按钮,可一键发送到知识入库接口。
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">SOUL.md</label>
<Textarea
placeholder="写下智能体的人设、边界、工作方式和输出要求"
value={soulInput}
onChange={(event) => setSoulInput(event.currentTarget.value)}
className="max-h-[50vh] min-h-64 resize-y overflow-y-auto text-xs"
/>
</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>
<SkillTransferSelector
skills={enabledSkills}
selected={selectedSkills}
onChange={handleSkillSelectionChange}
isLoading={isSkillsLoading}
onViewDetail={setDetailSkillName}
/>
</div>
<SkillDetailDialog
skillName={detailSkillName}
open={detailSkillName !== null}
onOpenChange={(o) => {
if (!o) setDetailSkillName(null);
}}
/>
{formError ? (
<p className="text-destructive text-sm">{formError}</p>
) : null}
<div className="rounded-md border px-3 py-2 text-xs dark:border-[#1B477E] dark:bg-[#022248]">
<p className="text-muted-foreground">
{agentId ? "当前登录账号:" : "创建后归属账号:"}
<span className="text-foreground font-medium">
「{live.displayName}」
</span>
</p>
{live.switched && (
<p className="text-destructive mt-1">
⚠ 本页加载时为「{live.mountDisplayName}」,现已切换为「
{live.displayName}」。
{agentId
? "继续保存将以当前账号执行。"
: `继续创建将归属「${live.displayName}」。`}
建议刷新页面确认账号。
</p>
)}
</div>
<Button
className="w-full"
onClick={() => void handleSaveAgent()}
disabled={busy || isSkillsLoading}
>
<SaveIcon className="h-4 w-4" />
{agentId ? "保存智能体" : "创建智能体"}
</Button>
</div>
</aside>
</ResizablePanel>
</ResizablePanelGroup>
</div>
</ArtifactsProvider>
</ThreadContext.Provider>
);
}