"use client"; import { ArrowDownUpIcon, BotIcon, Compass, Loader2, LockIcon, PlusIcon, ShieldIcon, XIcon } from "lucide-react"; import { useRouter } from "next/navigation"; import { useEffect, useState } from "react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Pagination } from "@/components/ui/pagination"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { TagSearchBar } from "@/components/workspace/tags/tag-search-bar"; import { ViewModeToggle } from "@/components/workspace/view-mode-toggle"; import { getStoredAuth } from "@/core/auth"; import { useAgentsPaginated, usePrivateAgentsPaginated } from "@/core/agents"; import type { Agent, AgentSort } from "@/core/agents"; import { useI18n } from "@/core/i18n/hooks"; import { useRouteBase } from "@/core/route-base"; import { isSentimentAgentVisible } from "@/core/sentiment-agent/config"; import { usePrivateSquareStatus, usePublishSquares, useViewMode } from "@/core/system-settings/hooks"; import { WX_RESTRICTED_TAB_DEFAULT_SQUARE, WX_RESTRICTED_TAB_NANJING_DB, isWxRestrictedPlaceholderTab, wxRestrictedDefaultSquareTabValue, wxRestrictedNanjingTabValue, } from "@/core/system-settings/wx-type-filter"; import { AgentCard } from "./agent-card"; import { SentimentAgentCard } from "./sentiment-agent-card"; import { AgentGuide, isAgentGuideEnvironment, startAgentGuide, } from "./agent-guide"; const PAGE_SIZE = 12; // Within a single tab the verified password is kept in sessionStorage so a // refresh / route navigation does not re-prompt. Cleared on tab close, so the // password never persists beyond the browsing session. const PRIVATE_SQUARE_PASSWORD_KEY = "deer-flow.private-square-password"; export function AgentGallery({ restrictWxTypes = false, }: { /** wx 侧栏入口:类型 Tab 只保留 我的 / 默认广场 / 南京-db。 */ restrictWxTypes?: boolean; } = {}) { const { t } = useI18n(); const router = useRouter(); const routeBase = useRouteBase(); const sentimentAgentVisible = isSentimentAgentVisible(); // 「内置智能体」筛选仅管理员可见(后端 scope=builtin 也做了 admin 闸门兜底)。 const isAdmin = getStoredAuth()?.system_role === "admin"; const [viewMode, setViewMode] = useViewMode("agent"); const [activeTab, setActiveTab] = useState("mine"); const [search, setSearch] = useState(""); const [tagIds, setTagIds] = useState([]); const [sort, setSort] = useState("time_desc"); const { data: publishSquares } = usePublishSquares(); // Each configured publish square (发布广场) becomes its own browse tab; the // backend always returns at least one (the built-in default). const squareTabs = publishSquares?.squares ?? []; // 默认广场固定排在「我的」之后;舆情分析是依附在默认广场后的前端虚拟类型, // 其余自定义广场继续保持后端给出的顺序。 const [defaultSquare, ...additionalSquares] = squareTabs; const defaultSquareTabValue = wxRestrictedDefaultSquareTabValue( publishSquares?.default_square_id, ); const nanjingTabValue = wxRestrictedNanjingTabValue(squareTabs); const wxPlaceholderTab = restrictWxTypes && isWxRestrictedPlaceholderTab(activeTab); // Publisher filter: click a card's 发布者 to keep only that user's agents. // {id} is the owner user_id (server filter), {label} the desensitized name. const [publisher, setPublisher] = useState<{ id: string; label: string } | null>( null, ); // Per-tab 1-based page index (keyed by tab value), preserved across switches. const [pages, setPages] = useState>({}); // Search + tag filtering are both server-side now. The backend mirrors the // frontend's desensitize map, so typing the displayed abbreviation (e.g. // "TS") still matches the stored raw name (e.g. "态势分析"). Whenever the // filters change, every tab returns to its first page. const tagKey = tagIds.join(","); useEffect(() => { setPages({}); }, [search, tagKey, sort, publisher?.id]); // If the active square tab disappears (admin removed that square), fall back // to "我的" so the gallery never points at a dead tab. useEffect(() => { if (restrictWxTypes) { if ( activeTab === WX_RESTRICTED_TAB_NANJING_DB && nanjingTabValue !== WX_RESTRICTED_TAB_NANJING_DB ) { setActiveTab(nanjingTabValue); return; } if ( activeTab === WX_RESTRICTED_TAB_DEFAULT_SQUARE && defaultSquareTabValue !== WX_RESTRICTED_TAB_DEFAULT_SQUARE ) { setActiveTab(defaultSquareTabValue); return; } if ( activeTab !== "mine" && activeTab !== defaultSquareTabValue && activeTab !== nanjingTabValue ) { setActiveTab("mine"); } return; } // 非管理员落到「内置」标签(理论上点不到,兜底)→ 回到「我的」。 if (activeTab === "builtin" && !isAdmin) { setActiveTab("mine"); return; } if ( activeTab !== "mine" && activeTab !== "private" && activeTab !== "builtin" && activeTab !== "sentiment" && squareTabs.length > 0 && !squareTabs.some((sq) => sq.id === activeTab) ) { setActiveTab("mine"); } }, [ activeTab, squareTabs, isAdmin, restrictWxTypes, defaultSquareTabValue, nanjingTabValue, ]); const { data: privateStatus } = usePrivateSquareStatus(); const privateFeatureAvailable = !!privateStatus?.enabled; const privateFeatureUsable = privateFeatureAvailable && !!privateStatus?.password_set; const [privatePassword, setPrivatePassword] = useState(() => { if (typeof window === "undefined") return null; return window.sessionStorage.getItem(PRIVATE_SQUARE_PASSWORD_KEY); }); const [passwordInput, setPasswordInput] = useState(""); // Only the active tab fetches. "广场" maps to the server "square" scope // (built-in/published, never private), "我的" to "mine" (owned + favorited), // "内置" to "builtin" (admin-only, user_id IS NULL). 「舆情分析」是前端虚拟 // 类型,不查后端列表。 const isSquareTab = activeTab !== "mine" && activeTab !== "private" && activeTab !== "builtin" && activeTab !== "sentiment"; const mainScope = activeTab === "mine" ? "mine" : activeTab === "builtin" ? "builtin" : "square"; const mainPage = pages[activeTab] ?? 1; const { agents: mainAgents, total: mainTotal, isLoading: mainLoading, isFetching: mainFetching, } = useAgentsPaginated({ scope: mainScope, search, tagIds, sort, page: mainPage, pageSize: PAGE_SIZE, enabled: activeTab !== "private" && activeTab !== "sentiment" && !wxPlaceholderTab, owner: publisher?.id, // Each square tab fetches only that square's agents. square: isSquareTab && !wxPlaceholderTab ? activeTab : undefined, }); const { agents: privateAgents, total: privateTotal, isLoading: isPrivateLoading, isFetching: isPrivateFetching, error: privateError, } = usePrivateAgentsPaginated(privatePassword, { search, tagIds, sort, page: pages.private ?? 1, pageSize: PAGE_SIZE, enabled: activeTab === "private", owner: publisher?.id, }); // If the server reports the stored password no longer works (likely the // admin rotated it), drop it from session storage and re-prompt. useEffect(() => { if (privatePassword && privateError) { window.sessionStorage.removeItem(PRIVATE_SQUARE_PASSWORD_KEY); setPrivatePassword(null); toast.error("私密广场密码已失效,请重新输入"); } }, [privateError, privatePassword]); // The private tab is only "unlocked" once the feature is usable and a // password has been verified. Until then we show the gate (or the lock // prompt) and hide the keyword/tag search bar — there is no list to filter. const privateUnlocked = privateFeatureUsable && !!privatePassword; const showSearchBar = activeTab !== "sentiment" && (activeTab !== "private" || privateUnlocked); const activeTotal = wxPlaceholderTab ? 0 : activeTab === "sentiment" ? 1 : activeTab === "private" ? privateTotal : mainTotal; const setTabPage = (tab: string, page: number) => setPages((prev) => ({ ...prev, [tab]: page })); const handleNewAgent = () => { router.push("/page/workspace/agents/new"); }; const handleSubmitPassword = () => { const trimmed = passwordInput.trim(); if (!trimmed) { toast.error("请输入密码"); return; } window.sessionStorage.setItem(PRIVATE_SQUARE_PASSWORD_KEY, trimmed); setPrivatePassword(trimmed); setPasswordInput(""); }; const handleLockPrivate = () => { window.sessionStorage.removeItem(PRIVATE_SQUARE_PASSWORD_KEY); setPrivatePassword(null); }; const handlePublisherClick = (p: { id: string; label: string }) => setPublisher(p); const renderGrid = (list: Agent[]) => viewMode === "list" ? (
{list.map((agent) => ( ))}
) : (
{list.map((agent) => ( ))}
); /** Loading / empty / (grid + pagination) for one paginated tab. */ const renderListBody = (opts: { list: Agent[]; total: number; isLoading: boolean; isFetching: boolean; tab: string; emptyDescription: string; showNewButton?: boolean; }) => { const { list, total, isLoading, isFetching, tab, emptyDescription, showNewButton } = opts; // keepPreviousData keeps the old page visible while a new page loads, so // this full-height spinner only covers the very first load (no rows yet), // or a filter change while the previous result was already empty (where // isLoading stays false but there is nothing to keep on screen). if ((isLoading || isFetching) && list.length === 0) { return (
{t.common.loading}
); } if (list.length === 0) { return renderEmpty(emptyDescription, showNewButton); } return (
{/* While a server-side search/tag/page query is in flight the stale keepPreviousData rows stay mounted — dim them and float a spinner on top so a slow backend query never looks like the filter was ignored, and block clicks on results that are about to change. */}
{renderGrid(list)}
{isFetching && (
正在查询…
)} setTabPage(tab, p)} className="pt-2" />
); }; const renderEmpty = (description: string, showNewButton = false) => (

{t.agents.emptyTitle}

{description}

{showNewButton && ( )}
); const renderPrivateTab = () => { if (!privateFeatureAvailable) { return (

私密广场尚未开启

请管理员前往「综合管理 → 私密广场配置」开启该功能并设置密码。

); } if (!privateFeatureUsable) { return (

私密广场未配置密码

请管理员在私密广场配置页设置一个访问密码。

); } if (!privatePassword) { return (

私密广场

请输入访问密码,验证通过后才能查看其中的智能体。

{ event.preventDefault(); handleSubmitPassword(); }} > setPasswordInput(e.target.value)} // This is a one-off access code, not a login credential. Tell // browsers / password managers not to save or autofill it (which // would also stop them from spilling a saved account into the // name search box on this page). name="private-square-access-code" autoComplete="off" data-1p-ignore data-lpignore="true" data-form-type="other" />
); } return renderListBody({ list: privateAgents, total: privateTotal, isLoading: isPrivateLoading, isFetching: isPrivateFetching, tab: "private", emptyDescription: "私密广场暂时还没有智能体。", }); }; return (
{/* Page header */}

{t.agents.title}

{t.agents.description}

{/* Tabs */} { setActiveTab(v); // Each tab starts from a clean slate: switching tabs clears the // keyword / tag / sort / publisher filters instead of carrying them // over. The TagSearchBar's own input box is reset via its key below. setSearch(""); setTagIds([]); setSort("time_desc"); setPublisher(null); }} className="flex min-h-0 flex-1 flex-col overflow-hidden" >
{restrictWxTypes ? ( <> 我的 默认广场 南京-db ) : ( <> 我的 {defaultSquare && ( {defaultSquare.name} )} {sentimentAgentVisible && ( /* 舆情分析:前端虚拟类型,直连外部舆情问答接口。 */ 舆情分析 )} {additionalSquares.map((sq) => ( {sq.name} ))} {privateFeatureAvailable && ( 私密广场 )} {isAdmin && ( 内置智能体 )} )}
共 {activeTotal} 个 {activeTab === "private" && privatePassword && ( )}
{showSearchBar && (
setSort(v as AgentSort)}> 最新创建 最早创建 最近更新 最早更新 名称 A-Z 名称 Z-A } />
)} {publisher && (
筛选发布者:
)}
{restrictWxTypes ? ( <> {wxPlaceholderTab && activeTab === defaultSquareTabValue ? renderEmpty("该广场暂无智能体") : renderListBody({ list: mainAgents, total: mainTotal, isLoading: mainLoading, isFetching: mainFetching, tab: defaultSquareTabValue, emptyDescription: "该广场暂无智能体", })} {wxPlaceholderTab && activeTab === nanjingTabValue ? renderEmpty("该类型暂无智能体") : renderListBody({ list: mainAgents, total: mainTotal, isLoading: mainLoading, isFetching: mainFetching, tab: nanjingTabValue, emptyDescription: "该类型暂无智能体", })} ) : ( squareTabs.map((sq) => ( {renderListBody({ list: mainAgents, total: mainTotal, isLoading: mainLoading, isFetching: mainFetching, tab: sq.id, emptyDescription: `「${sq.name}」广场暂时还没有智能体。`, })} )) )} {renderListBody({ list: mainAgents, total: mainTotal, isLoading: mainLoading, isFetching: mainFetching, tab: "mine", emptyDescription: t.agents.emptyDescription, showNewButton: true, })} {/* 舆情分析类型:固定一张虚拟智能体卡片(名称/简介可编辑), 接口地址与鉴权在 runtime-config.js 配置。 */} {!restrictWxTypes && sentimentAgentVisible && ( {viewMode === "list" ? (
) : (
)}
)} {!restrictWxTypes && isAdmin && ( {renderListBody({ list: mainAgents, total: mainTotal, isLoading: mainLoading, isFetching: mainFetching, tab: "builtin", emptyDescription: "暂时没有内置智能体。", })} )} {!restrictWxTypes && privateFeatureAvailable && ( {renderPrivateTab()} )}
); }