"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(""); const [chatModelInput, setChatModelInput] = useState(""); const [templateNameInput, setTemplateNameInput] = useState(""); // 会商席位「技能识别强化」开关(弱模型补偿)。默认关。 const [seatSkillDirectiveInput, setSeatSkillDirectiveInput] = useState(false); const [formError, setFormError] = useState(""); const [agentId, setAgentId] = useState(""); const [agent, setAgent] = useState(null); const [isCreatingAgent, setIsCreatingAgent] = useState(false); const [isSavingDraft, setIsSavingDraft] = useState(false); const [selectedSkills, setSelectedSkills] = useState([]); const [isSkillSelectionTouched, setIsSkillSelectionTouched] = useState(false); const [detailSkillName, setDetailSkillName] = useState(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 (

创建智能体

{agent ? ( ) : null}
当前对话模型 {isModelsLoading || models.length === 0 ? (
{isModelsLoading ? "加载中…" : "暂无模型"}
) : ( )}
{ if (thread.isLoading) { void thread.stop(); return; } void handleChatSubmit(text); }} >