"use client"; import { ClockIcon, CopyIcon, EyeOffIcon, GlobeIcon, LockIcon, MessageSquareIcon, MoreHorizontalIcon, PinIcon, ShieldIcon, SparklesIcon, SquarePenIcon, StarIcon, TagsIcon, Trash2Icon, UserIcon, } from "lucide-react"; import { useRouter } from "next/navigation"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, } 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 { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; import { Textarea } from "@/components/ui/textarea"; import { usePublishSquares } from "@/core/system-settings/hooks"; import { PublishSquarePickerDialog } from "@/components/workspace/publish-square-picker-dialog"; import { SkillDetailDialog } from "@/components/workspace/skills/skill-detail-dialog"; import { AgentQuestionEditor } from "@/components/workspace/agents/agent-question-editor"; import { AgentBrandIcon } from "@/components/workspace/agents/agent-brand-icon"; import { SkillTransferSelector } from "@/components/workspace/agents/skill-transfer-selector"; import { TagChipList } from "@/components/workspace/tags/tag-chip"; import { TagPickerDialog } from "@/components/workspace/tags/tag-picker-dialog"; import { normalizeAgentQuestions, useAgent, useCreateAgent, useDeleteAgent, useSetAgentFeatured, useSetAgentPrivate, useToggleAgentFavorite, useToggleAgentPin, useUpdateAgent, } from "@/core/agents"; import { getAgent } from "@/core/agents/api"; import type { Agent, AgentQuestion, UpdateAgentRequest } from "@/core/agents"; import { getStoredAuth } from "@/core/auth"; import { useLiveAccount } from "@/core/auth/use-live-account"; import { useI18n } from "@/core/i18n/hooks"; import { useSkills } from "@/core/skills/hooks"; import { formatDateTime } from "@/core/utils/datetime"; import { desensitize } from "@/lib/desensitize"; import { cn } from "@/lib/utils"; interface AgentCardProps { agent: Agent; /** "card" (default) renders the full gallery card; "list" renders a compact * single-row layout for the list view. All dialogs/actions are shared. */ layout?: "card" | "list"; /** Click the 发布者 line to filter the gallery to that publisher. Receives the * owner user_id + its desensitized display label. */ onPublisherClick?: (publisher: { id: string; label: string }) => void; } interface BadgeItem { key: string; node: ReactNode; } // Minimum number of skill/tool badges to always render before collapsing the // remainder into the "+N" chip. const MIN_VISIBLE_BADGES = 3; /** Render skill/tool-group badges clamped to at most two rows. Overflow is * collapsed into a clickable "+N" chip that opens a dialog listing the full * badge set (the visible rows stay as-is — only the chip is interactive). * * Badge widths are variable, so the cutoff is measured rather than assumed: an * off-screen mirror of the full badge set is laid out at the real container * width, and we keep only the badges that land within the first two rows * (reserving one slot for the "+N" chip). A ResizeObserver recomputes when the * responsive grid changes the card width. */ function ClampedBadgeRow({ items }: { items: BadgeItem[] }) { const measureRef = useRef(null); const [visible, setVisible] = useState(items.length); const [dialogOpen, setDialogOpen] = useState(false); const sig = items.map((i) => i.key).join("|"); useLayoutEffect(() => { const el = measureRef.current; if (!el) return; const compute = () => { const kids = Array.from(el.children) as HTMLElement[]; if (kids.length === 0) { setVisible(0); return; } const top0 = kids[0].offsetTop; const rowH = kids[0].offsetHeight; // +2px fudge so the second row's badges (which may sit a hair lower due // to line-box rounding) are not falsely treated as a third row. const maxBottom = top0 + rowH * 2 + 2; let count = 0; for (const k of kids) { if (k.offsetTop + k.offsetHeight <= maxBottom) count += 1; else break; } // Reserve one slot for the "+N" chip when anything overflows so the chip // itself never spills onto a third row. if (count < kids.length && count > 0) count -= 1; // Always surface a few badges before collapsing into "+N", even when the // card is narrow enough that two rows barely fit anything (otherwise a // skinny column could show just "+N" with no skills at all). Keeps at // least one badge hidden so the chip still makes sense. if (count < kids.length) { count = Math.max(count, Math.min(MIN_VISIBLE_BADGES, kids.length - 1)); } setVisible(count); }; compute(); const ro = new ResizeObserver(compute); ro.observe(el); return () => ro.disconnect(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [sig]); const hidden = items.length - visible; const showChip = hidden > 0; const shown = items.slice(0, visible); return (
{/* Off-screen full-width mirror used only for measuring row breaks. */}
{items.map((i) => i.node)}
{shown.map((i) => i.node)} {showChip && ( { e.stopPropagation(); setDialogOpen(true); }} > +{hidden} )}
全部技能与工具 共 {items.length} 项
{items.map((i) => i.node)}
); } export function AgentCard({ agent, layout = "card", onPublisherClick }: AgentCardProps) { const isList = layout === "list"; const { t } = useI18n(); const router = useRouter(); const deleteAgent = useDeleteAgent(); const updateAgent = useUpdateAgent(); const createAgent = useCreateAgent(); const setFeatured = useSetAgentFeatured(); const setPrivate = useSetAgentPrivate(); const toggleFavorite = useToggleAgentFavorite(); const togglePin = useToggleAgentPin(); const { skills, isLoading: isSkillsLoading } = useSkills(); const [deleteOpen, setDeleteOpen] = useState(false); const [editOpen, setEditOpen] = useState(false); const [tagPickerOpen, setTagPickerOpen] = useState(false); const [editName, setEditName] = useState(agent.name); const [editDescription, setEditDescription] = useState(agent.description ?? ""); const [editSoul, setEditSoul] = useState(agent.soul ?? ""); // Common questions (常用问题) — primary editing now lives in the agent chat // page's right-hand AgentDetailPanel; this dialog stays as a backup entry. // Each row has a short title (shown on the chip) and the full prompt sent // when clicked. const [editCommonQuestions, setEditCommonQuestions] = useState( () => normalizeAgentQuestions(agent.common_questions), ); const [editPublished, setEditPublished] = useState(agent.published); const [editIsPrivate, setEditIsPrivate] = useState(agent.is_private); // 会商席位「技能识别强化」开关(弱模型补偿)。默认关。 const [editSeatSkillDirective, setEditSeatSkillDirective] = useState( agent.seat_skill_directive ?? false, ); const [editSquareId, setEditSquareId] = useState(agent.square_id ?? ""); const [publishPickerOpen, setPublishPickerOpen] = useState(false); const { data: publishSquares } = usePublishSquares(); const [selectedSkills, setSelectedSkills] = useState( agent.skills ?? [], ); const [detailSkillName, setDetailSkillName] = useState(null); // The /api/agents list response intentionally omits `soul` (perf optimization // — SOUL.md is only read on demand). Fetch the detail row when the edit // dialog opens so the SOUL textarea can be hydrated. const { agent: agentDetail, isLoading: isAgentDetailLoading } = useAgent( editOpen ? agent.id : null, ); const storedAuth = useMemo(() => getStoredAuth(), []); const currentUserId = storedAuth?.user_id ?? null; // 发布请求实际以「实时」token 执行 —— 用 live 账号来提示发布者并检测账号是否被切换。 const live = useLiveAccount(); const isAdmin = storedAuth?.system_role === "admin"; const isBuiltin = agent.builtin; const isOwned = !isBuiltin && agent.user_id !== null && agent.user_id === currentUserId; const isFromOthers = !isBuiltin && !isOwned; // System admins are allowed to edit and delete any agent (built-in or owned // by another user) so the admin console can manage the full catalog. // Publish-toggle stays owner-only — built-ins are inherently visible to // everyone so toggling published is moot. const canEdit = isOwned || isAdmin; const canDelete = isOwned || isAdmin; // Favoriting collects a square agent into "我的"; pointless for one you // already own, so only offer it on built-in / others' agents. const canFavorite = !isOwned; const isFavorite = !!agent.is_favorite; const isPinned = !!agent.is_pinned; useEffect(() => { if (!editOpen) { return; } setEditName(agent.name); setEditDescription(agent.description ?? ""); setEditPublished(agent.published); setEditIsPrivate(agent.is_private); setEditSquareId(agent.square_id ?? ""); setSelectedSkills(agent.skills ?? []); setEditCommonQuestions(normalizeAgentQuestions(agent.common_questions)); setEditSeatSkillDirective(agent.seat_skill_directive ?? false); }, [ agent.common_questions, agent.description, agent.is_private, agent.name, agent.published, agent.square_id, agent.skills, agent.seat_skill_directive, editOpen, ]); useEffect(() => { if (!editOpen) { return; } // SOUL.md only ships on the detail endpoint; fall back to whatever the list // happened to carry so older deployments (or cached objects that still // include `soul`) keep working. if (agentDetail) { setEditSoul(agentDetail.soul ?? ""); setEditCommonQuestions(normalizeAgentQuestions(agentDetail.common_questions)); // 列表响应不带 config 额外字段(seat_skill_directive 为 null),详情才有真值。 setEditSeatSkillDirective(agentDetail.seat_skill_directive ?? false); } else { setEditSoul(agent.soul ?? ""); } }, [agent.soul, agentDetail, editOpen]); function handleChat() { router.push(`/page/workspace/agents/${agent.id}/chats/new`); } async function handleDelete() { try { await deleteAgent.mutateAsync(agent.id); toast.success(t.agents.deleteSuccess); setDeleteOpen(false); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } async function handleDuplicate() { if (createAgent.isPending) { return; } try { // SOUL.md is omitted from the list payload (perf), so fetch the detail // row to carry the source agent's personality into the copy. Fall back // to whatever the list happened to include if the detail fetch fails. let soul = agent.soul ?? ""; try { const detail = await getAgent(agent.id); soul = detail.soul ?? soul; } catch { // keep the list fallback } const created = await createAgent.mutateAsync({ name: `${agent.name} 副本`, description: agent.description ?? "", soul, skills: agent.skills ?? [], model: agent.model ?? null, tool_groups: agent.tool_groups ?? null, // A copy starts as a private, unpublished draft the owner can refine // before sharing — never inherit the source's published/private state. published: false, is_private: false, }); toast.success( `已复制为「${desensitize(created.name)}」,可在「我的」中编辑`, ); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } async function handleSaveEdit() { const trimmedName = editName.trim(); if (!trimmedName) { toast.error(t.agents.nameStepInvalidError ?? "名称不能为空"); return; } if (editIsPrivate && editPublished) { toast.warning("私密广场与公开发布互斥,请只勾选其一"); return; } // Private agents cannot also be published — force the value the // backend will see, regardless of any stale state in editPublished. const nextPublished = editIsPrivate ? false : editPublished; const nextQuestions = editCommonQuestions .map((q) => ({ title: q.title.trim() || q.prompt.trim(), prompt: q.prompt.trim() || q.title.trim(), })) .filter((q) => q.prompt.length > 0); // Only send the fields that actually changed: the backend merges partial // updates (model_fields_set), so e.g. a 常用问题 edit no longer rewrites // skills/SOUL and saving stays fast. const baselineQuestions = normalizeAgentQuestions( agentDetail?.common_questions ?? agent.common_questions, ); const request: UpdateAgentRequest = {}; if (trimmedName !== agent.name) request.name = trimmedName; if (editDescription !== (agent.description ?? "")) request.description = editDescription; if (editSoul !== (agentDetail?.soul ?? agent.soul ?? "")) request.soul = editSoul; if (nextPublished !== agent.published) request.published = nextPublished; if (editIsPrivate !== agent.is_private) request.is_private = editIsPrivate; if ((editSquareId || "") !== (agent.square_id ?? "")) request.square_id = editSquareId; if (JSON.stringify(selectedSkills) !== JSON.stringify(agent.skills ?? [])) request.skills = selectedSkills; if (JSON.stringify(nextQuestions) !== JSON.stringify(baselineQuestions)) request.common_questions = nextQuestions; if (editSeatSkillDirective !== ((agentDetail?.seat_skill_directive ?? agent.seat_skill_directive) ?? false)) request.seat_skill_directive = editSeatSkillDirective; if (Object.keys(request).length === 0) { setEditOpen(false); return; } try { await updateAgent.mutateAsync({ id: agent.id, request }); toast.success("智能体已更新"); setEditOpen(false); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } async function handleTogglePublished() { // Private and public squares are mutually exclusive — a private agent // can't simultaneously be published to everyone. Block the toggle // instead of silently moving the agent between squares. if (!agent.published && agent.is_private) { toast.warning("该智能体已加入私密广场,不可发布"); return; } // Publishing: prompt for which square to publish into (when any squares are // configured). Unpublishing: just flip it off. if (!agent.published && (publishSquares?.squares.length ?? 0) > 0) { setPublishPickerOpen(true); return; } if (!warnIfAccountSwitched()) { return; } try { await updateAgent.mutateAsync({ id: agent.id, request: { published: !agent.published }, }); toast.success( agent.published ? "已取消发布" : `已发布(操作账号:${live.displayName})`, ); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } // 发布操作以实时 token 执行。若会话中途账号被切换(常见于另一标签页登录了别的 // 账号),先弹一次确认 —— 避免误以本人之外的账号执行发布。返回 false = 用户取消。 function warnIfAccountSwitched(): boolean { if (!live.switched) { return true; } return window.confirm( `当前登录账号已从「${live.mountDisplayName}」切换为「${live.displayName}」。\n` + `本次发布将以「${live.displayName}」执行。如需以「${live.mountDisplayName}」操作,请取消并刷新页面。\n\n仍要继续吗?`, ); } async function handlePublishToSquare(squareId: string) { if (!warnIfAccountSwitched()) { return; } try { await updateAgent.mutateAsync({ id: agent.id, request: { published: true, square_id: squareId }, }); const sqName = publishSquares?.squares.find((s) => s.id === squareId)?.name ?? "广场"; toast.success(`已发布到「${sqName}」(操作账号:${live.displayName})`); setPublishPickerOpen(false); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } async function handleTogglePrivate() { const turningOn = !agent.is_private; try { if (isOwned) { // Owners can re-categorize their own agents through the normal update // endpoint — keeps publish/private edits in one transaction. await updateAgent.mutateAsync({ id: agent.id, request: { is_private: turningOn }, }); } else { // Admins can move any agent (built-in or other users') via the // dedicated admin endpoint. await setPrivate.mutateAsync({ id: agent.id, isPrivate: turningOn }); } toast.success(turningOn ? "已加入私密广场" : "已移出私密广场"); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } async function handleToggleFavorite() { const next = !isFavorite; try { await toggleFavorite.mutateAsync({ id: agent.id, favorite: next }); toast.success(next ? "已收藏到「我的」" : "已取消收藏"); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } async function handleTogglePin() { const next = !isPinned; try { await togglePin.mutateAsync({ id: agent.id, pinned: next }); toast.success(next ? "已置顶" : "已取消置顶"); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } async function handleToggleFeatured() { // One-click on/off — ordering is handled by the dedicated 管理 Agent 列表 // dialog. Featured agents get appended to the end on add (Date.now() is a // safe seed; the manage dialog can rewrite to 0..N-1 later). const turningOn = agent.featured_order == null; if (turningOn && !agent.published) { toast.error("只有已发布的智能体可以加入首页选择器"); return; } try { await setFeatured.mutateAsync({ id: agent.id, order: turningOn ? Date.now() : null, }); toast.success(turningOn ? "已加入首页选择器" : "已从首页选择器移除"); } catch (err) { toast.error(err instanceof Error ? err.message : String(err)); } } const enabledSkills = useMemo( () => skills.filter((skill) => skill.enabled), [skills], ); // Status badges (内置 / 我的 / 来自他人 / 已发布 / 私密 / 首页推荐) — shared by // both the card header and the compact list row. const statusBadges = ( <> {isBuiltin && ( 内置 )} {isOwned && ( 我的 )} {isFromOthers && ( 来自他人 )} {(isOwned || isAdmin) && !isBuiltin && agent.published && !agent.is_private && ( 已发布 )} {(isOwned || isAdmin) && !isBuiltin && !agent.published && !agent.is_private && ( 未发布 )} {agent.is_private && ( 私密 )} {agent.featured_order != null && ( 首页推荐 )} ); // 发布者(仅自定义/已发布的智能体显示;内置无 owner 不显示)。点击可按发布者筛选。 const publisherLabel = agent.owner_username ? desensitize(agent.owner_username) : ""; const canFilterByPublisher = !isBuiltin && !!agent.owner_username && !!agent.user_id && !!onPublisherClick; const publisherNode = !isBuiltin && agent.owner_username ? ( ) : null; const createdAtText = formatDateTime(agent.created_at); const createdAtNode = createdAtText ? (
创建时间:{createdAtText}
) : null; // 技能英文名 → 中文名映射,用于把智能体的技能徽章显示为中文(agent.skills 只存英文名)。 const skillNameZhMap = useMemo(() => { const map = new Map(); for (const s of skills) { if (s.name_zh?.trim()) map.set(s.name, s.name_zh.trim()); } return map; }, [skills]); const skillBadgeItems = [ ...(agent.tool_groups ?? []).map((group) => ({ key: `tg:${group}`, node: ( {desensitize(group)} ), })), ...(agent.skills ?? []).map((skill) => ({ key: `sk:${skill}`, node: ( { e.stopPropagation(); setDetailSkillName(skill); }} > {skillNameZhMap.get(skill) ?? desensitize(skill)} ), })), ]; const hasSkillsOrTools = (agent.tool_groups?.length ?? agent.skills?.length ?? 0) > 0; const showActionRow = canEdit || canDelete || isOwned || isAdmin || canFavorite; // The icon action buttons, shared by both layouts. const actionButtons = ( <> {canFavorite && ( )} {isAdmin && ( )} {isOwned && ( )} {(isOwned || isAdmin) && ( )} {canEdit && ( )} {canDelete && ( )} ); const chatButton = ( ); const cardStatusBadge = agent.is_private ? ( 私密 ) : agent.published || isBuiltin ? ( 已发布 ) : ( 运行中 ); const updatedAtText = formatDateTime(agent.updated_at ?? agent.created_at); const cardActionsMenu = ( {canFavorite && ( void handleToggleFavorite()}> {isFavorite ? "取消收藏" : "收藏到我的"} )} void handleTogglePin()}> {isPinned ? "取消置顶" : "置顶"} {isAdmin && ( void handleToggleFeatured()}> {agent.featured_order != null ? "取消推荐" : "设为推荐"} )} setTagPickerOpen(true)}> {t.adminTags.manageTags} {isOwned && ( void handleTogglePublished()}> {agent.published ? : } {agent.published ? "取消发布" : "发布"} )} {(isOwned || isAdmin) && ( void handleTogglePrivate()}> {agent.is_private ? "移出私密广场" : "放入私密广场"} )} void handleDuplicate()}> 复制智能体 {canEdit && ( setEditOpen(true)}> 编辑智能体 )} {canDelete && ( <> setDeleteOpen(true)} > {t.agents.delete} )} ); const cardLayout = ( {agent.featured_order != null ? ( <>
推荐 {cardActionsMenu}
) : (
{cardActionsMenu}
)} {desensitize(agent.name)} {agent.description && ( {desensitize(agent.description)} )}
{(agent.tags?.length ?? 0) > 0 && ( )} {hasSkillsOrTools && ( )}
{cardStatusBadge} {updatedAtText ? `更新于 ${updatedAtText}` : "最近更新"} {publisherLabel ? ` · 由 ${publisherLabel} 更新` : isBuiltin ? " · 由系统更新" : ""}
{chatButton}
); const listLayout = (
{desensitize(agent.name)}
{statusBadges}
{agent.description && (

{desensitize(agent.description)}

)} {publisherNode &&
{publisherNode}
} {createdAtNode &&
{createdAtNode}
}
{showActionRow && actionButtons} {chatButton}
); return ( <> {isList ? listLayout : cardLayout} 编辑智能体:{desensitize(agent.name)} 可以修改名称、描述、技能白名单、SOUL 内容、常用问题与发布状态。
setEditName(e.target.value)} placeholder="输入智能体名称(允许中文)" />