Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style: rebranding chat ui

arvinxxad1422237167
diff --git a/src/app/[variants]/(main)/chat/_layout/AgentIdSync.tsx b/src/app/[variants]/(main)/chat/_layout/AgentIdSync.tsx
new file mode 100644
index 00000000000..41eadb9ccb7
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/AgentIdSync.tsx
@@ -0,0 +1,25 @@
+import { useUnmount } from 'ahooks';
+import { useParams } from 'react-router-dom';
+import { createStoreUpdater } from 'zustand-utils';
+
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+
+const AgentIdSync = () => {
+ const useStoreUpdater = createStoreUpdater(useAgentStore);
+ const useChatStoreUpdater = createStoreUpdater(useChatStore);
+ const params = useParams<{ aid?: string }>();
+
+ useStoreUpdater('activeAgentId', params.aid);
+ useChatStoreUpdater('activeAgentId', params.aid ?? '');
+
+ // Clear activeAgentId when unmounting (leaving chat page)
+ useUnmount(() => {
+ useAgentStore.setState({ activeAgentId: undefined });
+ useChatStore.setState({ activeAgentId: undefined, activeTopicId: undefined });
+ });
+
+ return null;
+};
+
+export default AgentIdSync;
diff --git a/src/app/[variants]/(main)/chat/_layout/Desktop/SessionPanel.tsx b/src/app/[variants]/(main)/chat/_layout/Desktop/SessionPanel.tsx
deleted file mode 100644
index 6d58eda81f3..00000000000
--- a/src/app/[variants]/(main)/chat/_layout/Desktop/SessionPanel.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-'use client';
-
-import { DraggablePanel, DraggablePanelContainer, type DraggablePanelProps } from '@lobehub/ui';
-import { createStyles, useResponsive, useThemeMode } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import { memo, useEffect, useMemo, useState } from 'react';
-
-import { withSuspense } from '@/components/withSuspense';
-import { FOLDER_WIDTH } from '@/const/layoutTokens';
-import { useIsSingleMode } from '@/hooks/useIsSingleMode';
-import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-
-import SessionPanelContent from '../../components/SessionPanel';
-import { TOOGLE_PANEL_BUTTON_ID } from '../../features/TogglePanelButton';
-
-export const useStyles = createStyles(({ css, token }) => ({
- panel: css`
- height: 100%;
- color: ${token.colorTextSecondary};
- background: ${token.colorBgLayout};
-
- #${TOOGLE_PANEL_BUTTON_ID} {
- opacity: 0;
- transition: opacity 0.15s ${token.motionEaseInOut};
- }
-
- &:hover {
- #${TOOGLE_PANEL_BUTTON_ID} {
- opacity: 1;
- }
- }
- `,
-}));
-
-const SessionPanel = memo(() => {
- const isSingleMode = useIsSingleMode();
-
- const { md = true } = useResponsive();
-
- const [isPinned] = usePinnedAgentState();
-
- const { styles } = useStyles();
-
- const [sessionsWidth, sessionExpandable, updatePreference] = useGlobalStore((s) => [
- systemStatusSelectors.sessionWidth(s),
- systemStatusSelectors.showSessionPanel(s),
- s.updateSystemStatus,
- ]);
-
- const [cacheExpand, setCacheExpand] = useState<boolean>(Boolean(sessionExpandable));
- const [tmpWidth, setWidth] = useState(sessionsWidth);
- if (tmpWidth !== sessionsWidth) setWidth(sessionsWidth);
-
- const handleExpand = (expand: boolean) => {
- if (isEqual(expand, sessionExpandable)) return;
- updatePreference({ showSessionPanel: expand });
- setCacheExpand(expand);
- };
-
- const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {
- if (!size) return;
- const nextWidth = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;
- if (!nextWidth) return;
-
- if (isEqual(nextWidth, sessionsWidth)) return;
- setWidth(nextWidth);
- updatePreference({ sessionsWidth: nextWidth });
- };
-
- useEffect(() => {
- if (md && cacheExpand) updatePreference({ showSessionPanel: true });
- if (!md) updatePreference({ showSessionPanel: false });
- }, [md, cacheExpand]);
-
- const { appearance } = useThemeMode();
-
- const PanelContent = useMemo(() => {
- if (isSingleMode) {
- // 在单一模式下,仍然渲染 SessionPanelContent 以确保 SessionHydration 等逻辑组件正常工作
- // 但使用隐藏样式而不是 return null
- return (
- <div style={{ display: 'none' }}>
- <SessionPanelContent mobile={false} />
- </div>
- );
- }
-
- return (
- <DraggablePanel
- className={styles.panel}
- defaultSize={{ width: tmpWidth }}
- // 当进入 pin 模式下,不可展开
- expand={!isPinned && sessionExpandable}
- expandable={!isPinned}
- maxWidth={400}
- minWidth={FOLDER_WIDTH}
- mode={md ? 'fixed' : 'float'}
- onExpandChange={handleExpand}
- onSizeChange={handleSizeChange}
- placement="left"
- size={{ height: '100%', width: sessionsWidth }}
- >
- <DraggablePanelContainer style={{ flex: 'none', height: '100%', minWidth: FOLDER_WIDTH }}>
- <SessionPanelContent mobile={false} />
- </DraggablePanelContainer>
- </DraggablePanel>
- );
- }, [sessionsWidth, md, isPinned, sessionExpandable, tmpWidth, appearance, isSingleMode]);
-
- return PanelContent;
-});
-
-export default withSuspense(SessionPanel);
diff --git a/src/app/[variants]/(main)/chat/_layout/Desktop/Workspace.tsx b/src/app/[variants]/(main)/chat/_layout/Desktop/Workspace.tsx
deleted file mode 100644
index 30b24517556..00000000000
--- a/src/app/[variants]/(main)/chat/_layout/Desktop/Workspace.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-'use client';
-
-import { useTheme } from 'antd-style';
-import { PropsWithChildren, memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-const Workspace = memo<PropsWithChildren>(({ children }) => {
- const theme = useTheme();
- return (
- <Flexbox
- flex={1}
- style={{
- background: theme.colorBgContainerSecondary,
- overflow: 'hidden',
- position: 'relative',
- }}
- >
- {children}
- </Flexbox>
- );
-});
-
-export default Workspace;
diff --git a/src/app/[variants]/(main)/chat/_layout/FeatureFlagsProvider.tsx b/src/app/[variants]/(main)/chat/_layout/FeatureFlagsProvider.tsx
deleted file mode 100644
index 3f5ab02e494..00000000000
--- a/src/app/[variants]/(main)/chat/_layout/FeatureFlagsProvider.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-'use client';
-
-import { PropsWithChildren, createContext, useContext } from 'react';
-
-interface FeatureFlags {
- hideDocs?: boolean;
- showChangelog?: boolean;
-}
-
-const FeatureFlagsContext = createContext<FeatureFlags>({});
-
-export const useFeatureFlags = () => useContext(FeatureFlagsContext);
-
-export const FeatureFlagsProvider = ({
- children,
- hideDocs,
- showChangelog,
-}: PropsWithChildren<FeatureFlags>) => {
- return (
- <FeatureFlagsContext.Provider value={{ hideDocs, showChangelog }}>
- {children}
- </FeatureFlagsContext.Provider>
- );
-};
diff --git a/src/app/[variants]/(main)/chat/_layout/Mobile.tsx b/src/app/[variants]/(main)/chat/_layout/Mobile.tsx
deleted file mode 100644
index 1cbf26db347..00000000000
--- a/src/app/[variants]/(main)/chat/_layout/Mobile.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-'use client';
-
-import { createStyles } from 'antd-style';
-import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { withSuspense } from '@/components/withSuspense';
-import { useShowMobileWorkspace } from '@/hooks/useShowMobileWorkspace';
-
-import SessionPanelContent from '../components/SessionPanel';
-import { Outlet } from 'react-router-dom';
-
-const useStyles = createStyles(({ css, token }) => ({
- main: css`
- position: relative;
- overflow: hidden;
- background: ${token.colorBgLayout};
- `,
-}));
-
-const Layout = memo(( ) => {
- const showMobileWorkspace = useShowMobileWorkspace();
- const { styles } = useStyles();
-
- return (
- <>
- <Flexbox
- className={styles.main}
- height="100%"
- style={showMobileWorkspace ? { display: 'none' } : undefined}
- width="100%"
- >
- <SessionPanelContent mobile />
- </Flexbox>
- <Flexbox
- className={styles.main}
- height="100%"
- style={showMobileWorkspace ? undefined : { display: 'none' }}
- width="100%"
- >
- <Outlet />
- </Flexbox>
- </>
- );
-});
-
-Layout.displayName = 'MobileChatLayout';
-
-export default withSuspense(Layout);
diff --git a/src/app/[variants]/(main)/chat/_layout/Desktop/RegisterHotkeys.tsx b/src/app/[variants]/(main)/chat/_layout/RegisterHotkeys.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/_layout/Desktop/RegisterHotkeys.tsx
rename to src/app/[variants]/(main)/chat/_layout/RegisterHotkeys.tsx
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Body.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Body.tsx
new file mode 100644
index 00000000000..7151ab9d61f
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Body.tsx
@@ -0,0 +1,21 @@
+import { Accordion } from '@lobehub/ui';
+import React, { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import Topic from './Topic';
+
+export enum ChatSidebarKey {
+ Topic = 'topic',
+}
+
+const Body = memo(() => {
+ return (
+ <Flexbox paddingInline={4}>
+ <Accordion defaultExpandedKeys={[ChatSidebarKey.Topic]} gap={8}>
+ <Topic itemKey={ChatSidebarKey.Topic} />
+ </Accordion>
+ </Flexbox>
+ );
+});
+
+export default Body;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/AddTopicButon.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/AddTopicButon.tsx
new file mode 100644
index 00000000000..18879648a53
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/AddTopicButon.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { MessageSquarePlusIcon } from 'lucide-react';
+import { usePathname } from 'next/navigation';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useActionSWR } from '@/libs/swr';
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+import { HotkeyEnum } from '@/types/hotkey';
+
+const AddTopicButon = memo(() => {
+ const { t } = useTranslation('topic');
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.SaveTopic));
+ const params = useParams();
+ const agentId = params.aid;
+ const pathname = usePathname();
+ const isProfileActive = pathname.includes('/profile');
+ const router = useQueryRoute();
+ const [hasTopic, openNewTopicOrSaveTopic] = useChatStore((s) => [
+ !!s.activeTopicId,
+ s.openNewTopicOrSaveTopic,
+ ]);
+
+ const { mutate, isValidating } = useActionSWR('openNewTopicOrSaveTopic', openNewTopicOrSaveTopic);
+ const handleNewTopic = () => {
+ // If in agent sub-route, navigate back to agent chat first
+ if (isProfileActive && agentId) {
+ router.push(urlJoin('/agent', agentId));
+ }
+ mutate();
+ };
+
+ if (!hasTopic && !isProfileActive) return;
+
+ return (
+ <ActionIcon
+ icon={MessageSquarePlusIcon}
+ loading={isValidating}
+ onClick={handleNewTopic}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ title={t('actions.addNewTopic')}
+ tooltipProps={{
+ hotkey,
+ placement: 'bottom',
+ }}
+ />
+ );
+});
+
+export default AddTopicButon;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Agent/SwitchPanel.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
new file mode 100644
index 00000000000..64d5a7d765a
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
@@ -0,0 +1,45 @@
+import { Popover } from 'antd';
+import React, { PropsWithChildren, Suspense, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+import { useNavigate } from 'react-router-dom';
+
+import List from '@/app/[variants]/(main)/home/_layout/Body/Agent/List';
+import { AgentModalProvider } from '@/app/[variants]/(main)/home/_layout/Body/Agent/ModalProvider';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+
+const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
+ const navigate = useNavigate();
+ return (
+ <Popover
+ arrow={false}
+ content={
+ <Suspense fallback={<SkeletonList rows={6} />}>
+ <AgentModalProvider>
+ <Flexbox
+ gap={4}
+ padding={8}
+ style={{
+ maxHeight: '50vh',
+ overflowY: 'auto',
+ }}
+ >
+ <List onMoreClick={() => navigate('/')} />
+ </Flexbox>
+ </AgentModalProvider>
+ </Suspense>
+ }
+ placement={'bottomLeft'}
+ styles={{
+ body: {
+ padding: 0,
+ width: 240,
+ },
+ }}
+ trigger={['click']}
+ >
+ {children}
+ </Popover>
+ );
+});
+
+export default SwitchPanel;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Agent/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Agent/index.tsx
new file mode 100644
index 00000000000..8a432aa0631
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Agent/index.tsx
@@ -0,0 +1,68 @@
+'use client';
+
+import { ActionIcon, Avatar, Block, Text } from '@lobehub/ui';
+import { ChevronsUpDownIcon } from 'lucide-react';
+import React, { PropsWithChildren, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { SkeletonItem } from '@/features/NavPanel/components/SkeletonList';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+
+import SwitchPanel from './SwitchPanel';
+
+const Agent = memo<PropsWithChildren>(() => {
+ const { t } = useTranslation(['chat', 'common']);
+
+ const [isLoading, isInbox, title, avatar, backgroundColor] = useAgentStore((s) => [
+ agentSelectors.isAgentConfigLoading(s),
+ builtinAgentSelectors.isInboxAgent(s),
+ agentSelectors.currentAgentTitle(s),
+ agentSelectors.currentAgentAvatar(s),
+ agentSelectors.currentAgentBackgroundColor(s),
+ ]);
+
+ const displayTitle = isInbox ? 'Lobe AI' : title || t('defaultSession', { ns: 'common' });
+
+ if (isLoading) return <SkeletonItem height={32} padding={0} />;
+
+ return (
+ <SwitchPanel>
+ <Block
+ align={'center'}
+ clickable
+ gap={8}
+ horizontal
+ padding={2}
+ style={{
+ minWidth: 32,
+ overflow: 'hidden',
+ }}
+ variant={'borderless'}
+ >
+ <Avatar
+ avatar={isInbox ? DEFAULT_INBOX_AVATAR : avatar || DEFAULT_AVATAR}
+ background={backgroundColor || undefined}
+ shape={'square'}
+ size={28}
+ />
+ <Text ellipsis weight={500}>
+ {displayTitle}
+ </Text>
+ <ActionIcon
+ icon={ChevronsUpDownIcon}
+ size={{
+ blockSize: 28,
+ size: 16,
+ }}
+ style={{
+ width: 24,
+ }}
+ />
+ </Block>
+ </SwitchPanel>
+ );
+});
+
+export default Agent;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Nav.tsx
new file mode 100644
index 00000000000..72aeabfec50
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/Nav.tsx
@@ -0,0 +1,54 @@
+'use client';
+
+import { BotPromptIcon } from '@lobehub/ui/icons';
+import { SearchIcon } from 'lucide-react';
+import { usePathname } from 'next/navigation';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import { useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+
+const Nav = memo(() => {
+ const { t } = useTranslation('chat');
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const params = useParams();
+ const agentId = params.aid;
+ const pathname = usePathname();
+ const isProfileActive = pathname.includes('/profile');
+ const router = useQueryRoute();
+ const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
+ const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
+ const hideProfile = isInbox || !isAgentEditable;
+
+ return (
+ <Flexbox gap={1} paddingInline={4}>
+ {!hideProfile && (
+ <NavItem
+ active={isProfileActive}
+ icon={BotPromptIcon}
+ onClick={() => {
+ router.push(urlJoin('/agent', agentId!, 'profile'));
+ }}
+ title={t('tab.profile')}
+ />
+ )}
+ <NavItem
+ icon={SearchIcon}
+ onClick={() => {
+ toggleCommandMenu(true);
+ }}
+ title={t('tab.search')}
+ />
+ </Flexbox>
+ );
+});
+
+export default Nav;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/index.tsx
new file mode 100644
index 00000000000..b32ab421c30
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Header/index.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { PropsWithChildren, memo } from 'react';
+
+import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
+
+import AddTopicButon from './AddTopicButon';
+import Agent from './Agent';
+import Nav from './Nav';
+
+const HeaderInfo = memo<PropsWithChildren>(() => {
+ return (
+ <>
+ <SideBarHeaderLayout left={<Agent />} right={<AddTopicButon />} />
+ <Nav />
+ </>
+ );
+});
+
+export default HeaderInfo;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/Actions.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/Actions.tsx
new file mode 100644
index 00000000000..d07e82e2ab2
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/Actions.tsx
@@ -0,0 +1,26 @@
+import { ActionIcon, Dropdown } from '@lobehub/ui';
+import { MoreHorizontal } from 'lucide-react';
+import { memo } from 'react';
+
+import { useTopicActionsDropdownMenu } from './useDropdownMenu';
+
+const Actions = memo(() => {
+ const dropdownMenu = useTopicActionsDropdownMenu();
+
+ return (
+ <Dropdown
+ arrow={false}
+ menu={{
+ items: dropdownMenu,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ },
+ }}
+ trigger={['click']}
+ >
+ <ActionIcon icon={MoreHorizontal} size={'small'} />
+ </Dropdown>
+ );
+});
+
+export default Actions;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
new file mode 100644
index 00000000000..63bf5b1180d
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
@@ -0,0 +1,182 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback, useEffect, useRef } from 'react';
+import { Flexbox } from 'react-layout-kit';
+import { VList, VListHandle } from 'virtua';
+
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import TopicEmpty from '@/features/TopicEmpty';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import TopicItem from '../List/Item';
+
+const ITEM_HEIGHT = 44; // Each topic item height
+
+interface ContentProps {
+ open: boolean;
+ searchKeyword: string;
+}
+
+const Content = memo<ContentProps>(({ open, searchKeyword }) => {
+ const virtuaRef = useRef<VListHandle>(null);
+ const fetchedCountRef = useRef(-1);
+ const initializedRef = useRef(false);
+
+ const [
+ activeTopicId,
+ activeThreadId,
+ hasMore,
+ isLoadingMore,
+ isExpandingPageSize,
+ loadMoreTopics,
+ activeAgentId,
+ useSearchTopics,
+ ] = useChatStore((s) => [
+ s.activeTopicId,
+ s.activeThreadId,
+ topicSelectors.hasMoreTopics(s),
+ topicSelectors.isLoadingMoreTopics(s),
+ topicSelectors.isExpandingPageSize(s),
+ s.loadMoreTopics,
+ s.activeAgentId,
+ s.useSearchTopics,
+ ]);
+
+ // Use server-side search if there's a keyword
+ const trimmedKeyword = searchKeyword.trim();
+ const isSearching = trimmedKeyword.length > 0;
+
+ // Set searching state and trigger search
+ useEffect(() => {
+ if (isSearching) {
+ useChatStore.setState({ isSearchingTopic: true });
+ } else {
+ // Reset search results when clearing search
+ useChatStore.setState({ isSearchingTopic: false, searchTopics: [] });
+ }
+ }, [isSearching]);
+
+ // Only search when there's a keyword (pass undefined to disable SWR)
+ // Note: searchTopics uses sessionId in the service, but agentId in the hook
+ useSearchTopics(isSearching ? trimmedKeyword : undefined, {
+ agentId: activeAgentId,
+ groupId: undefined,
+ });
+
+ const searchResults = useChatStore(topicSelectors.searchTopics, isEqual);
+ const allTopicList = useChatStore(topicSelectors.displayTopics, isEqual);
+ const isSearchingTopic = useChatStore(topicSelectors.isSearchingTopic);
+
+ // Use search results if searching, otherwise use regular list
+ const activeTopicList = isSearching ? searchResults : allTopicList;
+ const count = activeTopicList?.length || 0;
+
+ // Initial load: calculate how many items needed to fill viewport
+ useEffect(() => {
+ if (!open || initializedRef.current || isLoadingMore || isSearching) return;
+
+ const timer = setTimeout(() => {
+ const ref = virtuaRef.current;
+ if (!ref) return;
+
+ const viewportSize = ref.viewportSize;
+ const itemsNeeded = Math.ceil(viewportSize / ITEM_HEIGHT) + 3;
+
+ // Mark as initialized
+ initializedRef.current = true;
+
+ // Calculate how many pages we need to load to fill screen
+ if (count < itemsNeeded && hasMore) {
+ fetchedCountRef.current = count;
+
+ // Calculate pages needed and load once
+ const itemsToLoad = itemsNeeded - count;
+ const pagesNeeded = Math.ceil(itemsToLoad / 20); // Assume 20 items per page
+
+ // Load the required pages
+ const loadPages = async () => {
+ for (let i = 0; i < pagesNeeded && hasMore; i++) {
+ await loadMoreTopics();
+ }
+ };
+ loadPages();
+ }
+ }, 100);
+
+ return () => clearTimeout(timer);
+ }, [open, count, hasMore, loadMoreTopics, isLoadingMore]);
+
+ // Reset initialized flag when drawer closes
+ useEffect(() => {
+ if (!open) {
+ initializedRef.current = false;
+ }
+ }, [open]);
+
+ // Handle scroll - use findItemIndex (official pattern)
+ const handleScroll = useCallback(async () => {
+ // Don't load more when searching
+ if (isSearching) return;
+
+ const ref = virtuaRef.current;
+ if (!ref || !hasMore) return;
+
+ // Use findItemIndex to detect scroll position
+ const bottomVisibleIndex = ref.findItemIndex(ref.scrollOffset + ref.viewportSize);
+
+ // When scrolled near the end (within 5 items), load more
+ if (fetchedCountRef.current < count && bottomVisibleIndex + 5 > count) {
+ fetchedCountRef.current = count;
+ await loadMoreTopics();
+ }
+ }, [hasMore, loadMoreTopics, count, isSearching]);
+
+ const showLoading = (isLoadingMore || isExpandingPageSize) && !isSearching;
+ const showSearchLoading = isSearching && isSearchingTopic;
+
+ // Show empty state when no topics
+ if (count === 0 && !showLoading && !showSearchLoading) {
+ return <TopicEmpty search={Boolean(searchKeyword)} />;
+ }
+
+ // Show loading when searching
+ if (showSearchLoading) {
+ return (
+ <Flexbox gap={1} paddingBlock={1} paddingInline={4}>
+ <SkeletonList rows={5} />
+ </Flexbox>
+ );
+ }
+
+ return (
+ <VList
+ bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
+ onScroll={handleScroll}
+ ref={virtuaRef}
+ style={{ height: '100%' }}
+ >
+ {activeTopicList?.map((topic) => (
+ <Flexbox gap={1} key={topic.id} padding={'4px 8px'}>
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ threadId={activeThreadId}
+ title={topic.title}
+ />
+ </Flexbox>
+ ))}
+ {showLoading && (
+ <Flexbox padding={'4px 8px'}>
+ <SkeletonList rows={3} />
+ </Flexbox>
+ )}
+ </VList>
+ );
+});
+
+Content.displayName = 'AllTopicsDrawerContent';
+
+export default Content;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
new file mode 100644
index 00000000000..f825e5ee937
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { SearchBar } from '@lobehub/ui';
+import dynamic from 'next/dynamic';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+
+const Content = dynamic(() => import('./Content'), {
+ loading: () => (
+ <Flexbox gap={1} paddingBlock={1} paddingInline={4}>
+ <SkeletonList rows={3} />
+ </Flexbox>
+ ),
+ ssr: false,
+});
+
+interface AllTopicsDrawerProps {
+ onClose: () => void;
+ open: boolean;
+}
+
+const AllTopicsDrawer = memo<AllTopicsDrawerProps>(({ open, onClose }) => {
+ const { t } = useTranslation('topic');
+ const [searchKeyword, setSearchKeyword] = useState('');
+
+ return (
+ <SideBarDrawer
+ onClose={onClose}
+ open={open}
+ subHeader={
+ <Flexbox paddingBlock={'0 8px'} paddingInline={8}>
+ <SearchBar
+ allowClear
+ defaultValue={searchKeyword}
+ onInputChange={(keyword) => {
+ if (!keyword) setSearchKeyword('');
+ }}
+ onSearch={(keyword) => setSearchKeyword(keyword)}
+ placeholder={t('searchPlaceholder')}
+ />
+ </Flexbox>
+ }
+ title={t('title')}
+ >
+ <Content open={open} searchKeyword={searchKeyword} />
+ </SideBarDrawer>
+ );
+});
+
+AllTopicsDrawer.displayName = 'AllTopicsDrawer';
+
+export default AllTopicsDrawer;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/Actions.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/Actions.tsx
new file mode 100644
index 00000000000..97e77c89bf9
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/Actions.tsx
@@ -0,0 +1,26 @@
+import { ActionIcon, Dropdown, type MenuProps } from '@lobehub/ui';
+import { MoreHorizontalIcon } from 'lucide-react';
+import { memo } from 'react';
+
+interface ActionProps {
+ dropdownMenu: MenuProps['items'];
+}
+
+const Actions = memo<ActionProps>(({ dropdownMenu }) => {
+ return (
+ <Dropdown
+ arrow={false}
+ menu={{
+ items: dropdownMenu,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ },
+ }}
+ trigger={['click']}
+ >
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} />
+ </Dropdown>
+ );
+});
+
+export default Actions;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/Editing.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/Editing.tsx
new file mode 100644
index 00000000000..c9af4d443f7
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/Editing.tsx
@@ -0,0 +1,87 @@
+import { Input } from '@lobehub/ui';
+import { Popover } from 'antd';
+import { memo, useCallback, useState } from 'react';
+
+import { useChatStore } from '@/store/chat';
+
+interface EditingProps {
+ id: string;
+ title: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {
+ const [newTitle, setNewTitle] = useState(title);
+ const [editing, updateTopicTitle] = useChatStore((s) => [
+ s.topicRenamingId === id,
+ s.updateTopicTitle,
+ ]);
+
+ const handleUpdate = useCallback(async () => {
+ if (newTitle && title !== newTitle) {
+ try {
+ // Set loading state
+ useChatStore.setState(
+ {
+ topicLoadingIds: [...useChatStore.getState().topicLoadingIds, id],
+ },
+ false,
+ 'setTopicUpdating',
+ );
+ await updateTopicTitle(id, newTitle);
+ } finally {
+ // Clear loading state
+ useChatStore.setState(
+ {
+ topicLoadingIds: useChatStore
+ .getState()
+ .topicLoadingIds.filter((loadingId) => loadingId !== id),
+ },
+ false,
+ 'clearTopicUpdating',
+ );
+ }
+ }
+ toggleEditing(false);
+ }, [newTitle, title, id, updateTopicTitle, toggleEditing]);
+
+ return (
+ <Popover
+ arrow={false}
+ content={
+ <Input
+ autoFocus
+ defaultValue={title}
+ onBlur={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ onChange={(e) => setNewTitle(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ onPressEnter={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ />
+ }
+ destroyOnHidden
+ onOpenChange={(open) => {
+ if (!open) handleUpdate();
+ toggleEditing(open);
+ }}
+ open={editing}
+ placement={'bottomLeft'}
+ styles={{
+ body: {
+ padding: 4,
+ width: 320,
+ },
+ }}
+ trigger={['click']}
+ >
+ <div />
+ </Popover>
+ );
+});
+
+export default Editing;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/index.tsx
new file mode 100644
index 00000000000..157ca9529f2
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -0,0 +1,141 @@
+import { ActionIcon, Dropdown, Icon, Tag , Skeleton } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { MessageSquareDashed, Star } from 'lucide-react';
+import { Suspense, memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { isDesktop } from '@/const/version';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+import ThreadList from '../../TopicListContent/ThreadList';
+import { useTopicNavigation } from '../../hooks/useTopicNavigation';
+import Actions from './Actions';
+import Editing from './Editing';
+import { useTopicItemDropdownMenu } from './useDropdownMenu';
+
+interface TopicItemProps {
+ active?: boolean;
+ fav?: boolean;
+ id?: string;
+ threadId?: string;
+ title: string;
+}
+
+const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId }) => {
+ const { t } = useTranslation('topic');
+
+ const theme = useTheme();
+ const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+
+ const [editing, isLoading] = useChatStore((s) => [
+ id ? s.topicRenamingId === id : false,
+ id ? s.topicLoadingIds.includes(id) : false,
+ ]);
+
+ const [favoriteTopic] = useChatStore((s) => [s.favoriteTopic]);
+
+ const { navigateToTopic, isInAgentSubRoute } = useTopicNavigation();
+
+ const toggleEditing = useCallback(
+ (visible?: boolean) => {
+ useChatStore.setState({ topicRenamingId: visible && id ? id : '' });
+ },
+ [id],
+ );
+
+ const handleClick = useCallback(() => {
+ if (editing) return;
+ navigateToTopic(id);
+ }, [editing, id, navigateToTopic]);
+
+ const handleDoubleClick = useCallback(() => {
+ if (!id || !activeAgentId) return;
+ if (isDesktop) {
+ openTopicInNewWindow(activeAgentId, id);
+ }
+ }, [id, activeAgentId, openTopicInNewWindow]);
+
+ const dropdownMenu = useTopicItemDropdownMenu({
+ id,
+ toggleEditing,
+ });
+
+ // For default topic (no id)
+ if (!id) {
+ return (
+ <NavItem
+ active={active && !isInAgentSubRoute}
+ icon={<Icon color={theme.colorTextDescription} icon={MessageSquareDashed} size={'small'} />}
+ loading={isLoading}
+ onClick={handleClick}
+ title={
+ <Flexbox align={'center'} flex={1} gap={6} horizontal>
+ {t('defaultTitle')}
+ <Tag
+ size={'small'}
+ style={{
+ color: theme.colorTextDescription,
+ fontSize: 10,
+ }}
+ >
+ {t('temp')}
+ </Tag>
+ </Flexbox>
+ }
+ />
+ );
+ }
+
+ return (
+ <Flexbox style={{ position: 'relative' }}>
+ <Dropdown
+ menu={{
+ items: dropdownMenu,
+ }}
+ trigger={['contextMenu']}
+ >
+ <NavItem
+ actions={<Actions dropdownMenu={dropdownMenu} />}
+ active={active && !threadId && !isInAgentSubRoute}
+ disabled={editing}
+ icon={
+ <ActionIcon
+ color={fav ? theme.colorWarning : undefined}
+ fill={fav ? theme.colorWarning : 'transparent'}
+ icon={Star}
+ onClick={(e) => {
+ e.stopPropagation();
+ favoriteTopic(id, !fav);
+ }}
+ size={'small'}
+ />
+ }
+ loading={isLoading}
+ onClick={handleClick}
+ onDoubleClick={handleDoubleClick}
+ title={title}
+ />
+ </Dropdown>
+ <Editing id={id} title={title} toggleEditing={toggleEditing} />
+ {active && (
+ <Suspense
+ fallback={
+ <Flexbox gap={8} paddingBlock={8} paddingInline={24} width={'100%'}>
+ <Skeleton.Button active size={'small'} style={{ height: 18, width: '100%' }} />
+ <Skeleton.Button active size={'small'} style={{ height: 18, width: '100%' }} />
+ </Flexbox>
+ }
+ >
+ <ThreadList />
+ </Suspense>
+ )}
+ </Flexbox>
+ );
+});
+
+export default TopicItem;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
new file mode 100644
index 00000000000..14a6a93da7b
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -0,0 +1,107 @@
+import { Icon, type MenuProps } from '@lobehub/ui';
+import { App } from 'antd';
+import { ExternalLink, LucideCopy, PencilLine, Trash, Wand2 } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isDesktop } from '@/const/version';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+interface TopicItemDropdownMenuProps {
+ id?: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+export const useTopicItemDropdownMenu = ({
+ id,
+ toggleEditing,
+}: TopicItemDropdownMenuProps): MenuProps['items'] => {
+ const { t } = useTranslation(['topic', 'common']);
+ const { modal } = App.useApp();
+
+ const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+
+ const [autoRenameTopicTitle, duplicateTopic, removeTopic] = useChatStore((s) => [
+ s.autoRenameTopicTitle,
+ s.duplicateTopic,
+ s.removeTopic,
+ ]);
+
+ return useMemo(() => {
+ if (!id) return [];
+
+ return [
+ {
+ icon: <Icon icon={Wand2} />,
+ key: 'autoRename',
+ label: t('actions.autoRename'),
+ onClick: () => {
+ autoRenameTopicTitle(id);
+ },
+ },
+ {
+ icon: <Icon icon={PencilLine} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: () => {
+ toggleEditing(true);
+ },
+ },
+ ...(isDesktop
+ ? [
+ {
+ icon: <Icon icon={ExternalLink} />,
+ key: 'openInNewWindow',
+ label: t('actions.openInNewWindow'),
+ onClick: () => {
+ if (activeAgentId) openTopicInNewWindow(activeAgentId, id);
+ },
+ },
+ ]
+ : []),
+ {
+ type: 'divider' as const,
+ },
+ {
+ icon: <Icon icon={LucideCopy} />,
+ key: 'duplicate',
+ label: t('actions.duplicate'),
+ onClick: () => {
+ duplicateTopic(id);
+ },
+ },
+ {
+ type: 'divider' as const,
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: () => {
+ modal.confirm({
+ centered: true,
+ okButtonProps: { danger: true },
+ onOk: async () => {
+ await removeTopic(id);
+ },
+ title: t('actions.confirmRemoveTopic'),
+ });
+ },
+ },
+ ].filter(Boolean) as MenuProps['items'];
+ }, [
+ id,
+ activeAgentId,
+ autoRenameTopicTitle,
+ duplicateTopic,
+ removeTopic,
+ openTopicInNewWindow,
+ toggleEditing,
+ t,
+ modal,
+ ]);
+};
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/index.tsx
new file mode 100644
index 00000000000..33bf09d6403
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/index.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useFetchTopics } from '@/hooks/useFetchTopics';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+import { TopicDisplayMode } from '@/types/topic';
+
+import AllTopicsDrawer from '../AllTopicsDrawer';
+import ByTimeMode from '../TopicListContent/ByTimeMode';
+import FlatMode from '../TopicListContent/FlatMode';
+
+const TopicList = memo(() => {
+ const { t } = useTranslation('topic');
+ const router = useQueryRoute();
+ const topicLength = useChatStore((s) => topicSelectors.currentTopicLength(s));
+ const isUndefinedTopics = useChatStore((s) => topicSelectors.isUndefinedTopics(s));
+
+ const [agentId, allTopicsDrawerOpen, closeAllTopicsDrawer] = useChatStore((s) => [
+ s.activeAgentId,
+ s.allTopicsDrawerOpen,
+ s.closeAllTopicsDrawer,
+ ]);
+
+ const [topicDisplayMode] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s)]);
+
+ useFetchTopics();
+
+ // Show skeleton when current session's topic data is not yet loaded
+ if (isUndefinedTopics) return <SkeletonList />;
+
+ return (
+ <>
+ {topicLength === 0 && (
+ <EmptyNavItem
+ onClick={() => {
+ router.push(urlJoin('/agent', agentId));
+ }}
+ title={t('actions.addNewTopic')}
+ />
+ )}
+ {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ <AllTopicsDrawer onClose={closeAllTopicsDrawer} open={allTopicsDrawerOpen} />
+ </>
+ );
+});
+
+export default TopicList;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
new file mode 100644
index 00000000000..083214c93fc
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
@@ -0,0 +1,57 @@
+import { AccordionItem, Icon, Text } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import { HashIcon } from 'lucide-react';
+import React, { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { GroupedTopic } from '@/types/topic';
+
+import TopicItem from '../../List/Item';
+
+const preformat = (id: string) =>
+ id.startsWith('20') ? (id.includes('-') ? dayjs(id).format('MMMM') : id) : undefined;
+
+interface GroupItemProps {
+ activeThreadId?: string;
+ activeTopicId?: string;
+ group: GroupedTopic;
+}
+
+const GroupItem = memo<GroupItemProps>(({ group, activeTopicId, activeThreadId }) => {
+ const { t } = useTranslation('topic');
+ const { id, title, children } = group;
+
+ const timeTitle = useMemo(() => preformat(id) ?? t(`groupTitle.byTime.${id}` as any), [id, t]);
+
+ return (
+ <AccordionItem
+ itemKey={id}
+ paddingBlock={4}
+ paddingInline={'8px 4px'}
+ title={
+ <Flexbox align="center" gap={6} height={24} horizontal style={{ overflow: 'hidden' }}>
+ <Icon icon={HashIcon} style={{ opacity: 0.5 }} />
+ <Text ellipsis fontSize={12} style={{ flex: 1 }} type={'secondary'} weight={500}>
+ {title || timeTitle}
+ </Text>
+ </Flexbox>
+ }
+ >
+ <Flexbox gap={1} paddingBlock={1}>
+ {children.map((topic) => (
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ key={topic.id}
+ threadId={activeThreadId}
+ title={topic.title}
+ />
+ ))}
+ </Flexbox>
+ </AccordionItem>
+ );
+});
+
+export default GroupItem;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
new file mode 100644
index 00000000000..87262ba2d7c
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { Accordion } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { MoreHorizontal } from 'lucide-react';
+import React, { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import GroupItem from './GroupItem';
+
+const ByTimeMode = memo(() => {
+ const { t } = useTranslation('topic');
+ const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+
+ const [hasMore, isExpandingPageSize, openAllTopicsDrawer] = useChatStore((s) => [
+ topicSelectors.hasMoreTopics(s),
+ topicSelectors.isExpandingPageSize(s),
+ s.openAllTopicsDrawer,
+ ]);
+ const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);
+ const groupTopics = useChatStore(topicSelectors.groupedTopicsForSidebar(topicPageSize), isEqual);
+
+ const [topicGroupKeys, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.topicGroupKeys(s),
+ s.updateSystemStatus,
+ ]);
+
+ const expandedKeys = useMemo(() => {
+ return topicGroupKeys || groupTopics.map((group) => group.id);
+ }, [topicGroupKeys, groupTopics]);
+
+ return (
+ <Flexbox gap={2}>
+ {/* Grouped topics */}
+ <Accordion
+ expandedKeys={expandedKeys}
+ gap={2}
+ onExpandedChange={(keys) => updateSystemStatus({ expandTopicGroupKeys: keys as any })}
+ >
+ {groupTopics.map((group) => (
+ <GroupItem
+ activeThreadId={activeThreadId}
+ activeTopicId={activeTopicId}
+ group={group}
+ key={group.id}
+ />
+ ))}
+ </Accordion>
+ {isExpandingPageSize && <SkeletonList rows={3} />}
+ {hasMore && !isExpandingPageSize && (
+ <NavItem icon={MoreHorizontal} onClick={openAllTopicsDrawer} title={t('loadMore')} />
+ )}
+ </Flexbox>
+ );
+});
+
+ByTimeMode.displayName = 'ByTimeMode';
+
+export default ByTimeMode;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
new file mode 100644
index 00000000000..c847ef7bd7c
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { MoreHorizontal } from 'lucide-react';
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import TopicItem from '../../List/Item';
+
+const FlatMode = memo(() => {
+ const { t } = useTranslation('topic');
+ const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+
+ const [activeTopicId, activeThreadId, hasMore, isExpandingPageSize, openAllTopicsDrawer] =
+ useChatStore((s) => [
+ s.activeTopicId,
+ s.activeThreadId,
+ topicSelectors.hasMoreTopics(s),
+ topicSelectors.isExpandingPageSize(s),
+ s.openAllTopicsDrawer,
+ ]);
+
+ const activeTopicList = useChatStore(
+ topicSelectors.displayTopicsForSidebar(topicPageSize),
+ isEqual,
+ );
+
+ return (
+ <Flexbox gap={1}>
+ {activeTopicList?.map((topic) => (
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ key={topic.id}
+ threadId={activeThreadId}
+ title={topic.title}
+ />
+ ))}
+ {isExpandingPageSize && <SkeletonList rows={3} />}
+ {hasMore && !isExpandingPageSize && (
+ <NavItem icon={MoreHorizontal} onClick={openAllTopicsDrawer} title={t('loadMore')} />
+ )}
+ </Flexbox>
+ );
+});
+
+FlatMode.displayName = 'FlatMode';
+
+export default FlatMode;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/SearchResult/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx
similarity index 50%
rename from src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/SearchResult/index.tsx
rename to src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx
index fb08fbacf3d..88653feabb1 100644
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/SearchResult/index.tsx
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx
@@ -2,36 +2,24 @@
import { Text } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
-import React, { memo, useCallback, useRef } from 'react';
+import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Center } from 'react-layout-kit';
-import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
-import { ChatTopic } from '@/types/topic';
-import { SkeletonList } from '../../../SkeletonList';
-import TopicItem from '../TopicItem';
+import TopicItem from '../../List/Item';
const SearchResult = memo(() => {
const { t } = useTranslation('topic');
- const virtuosoRef = useRef<VirtuosoHandle>(null);
const [activeTopicId, isSearchingTopic] = useChatStore((s) => [
s.activeTopicId,
topicSelectors.isSearchingTopic(s),
]);
const topics = useChatStore(topicSelectors.searchTopics, isEqual);
- const itemContent = useCallback(
- (index: number, { id, favorite, title }: ChatTopic) => (
- <TopicItem active={activeTopicId === id} fav={favorite} id={id} key={id} title={title} />
- ),
- [activeTopicId],
- );
-
- const activeIndex = topics.findIndex((topic) => topic.id === activeTopicId);
-
if (isSearchingTopic) return <SkeletonList />;
if (topics.length === 0)
@@ -42,15 +30,17 @@ const SearchResult = memo(() => {
);
return (
- <Virtuoso
- computeItemKey={(_, item) => item.id}
- data={topics}
- defaultItemHeight={44}
- initialTopMostItemIndex={Math.max(activeIndex, 0)}
- itemContent={itemContent}
- overscan={44 * 10}
- ref={virtuosoRef}
- />
+ <>
+ {topics.map((topic) => (
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ key={topic.id}
+ title={topic.title}
+ />
+ ))}
+ </>
);
});
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
new file mode 100644
index 00000000000..97e77c89bf9
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
@@ -0,0 +1,26 @@
+import { ActionIcon, Dropdown, type MenuProps } from '@lobehub/ui';
+import { MoreHorizontalIcon } from 'lucide-react';
+import { memo } from 'react';
+
+interface ActionProps {
+ dropdownMenu: MenuProps['items'];
+}
+
+const Actions = memo<ActionProps>(({ dropdownMenu }) => {
+ return (
+ <Dropdown
+ arrow={false}
+ menu={{
+ items: dropdownMenu,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ },
+ }}
+ trigger={['click']}
+ >
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} />
+ </Dropdown>
+ );
+});
+
+export default Actions;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx
new file mode 100644
index 00000000000..ff665e84074
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx
@@ -0,0 +1,66 @@
+import { Input } from '@lobehub/ui';
+import { Popover } from 'antd';
+import { memo, useCallback, useState } from 'react';
+
+import { useChatStore } from '@/store/chat';
+
+interface EditingProps {
+ id: string;
+ title: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {
+ const [newTitle, setNewTitle] = useState(title);
+ const [editing, updateThreadTitle] = useChatStore((s) => [
+ s.threadRenamingId === id,
+ s.updateThreadTitle,
+ ]);
+
+ const handleUpdate = useCallback(async () => {
+ if (newTitle && title !== newTitle) {
+ await updateThreadTitle(id, newTitle);
+ }
+ toggleEditing(false);
+ }, [newTitle, title, id, updateThreadTitle, toggleEditing]);
+
+ return (
+ <Popover
+ arrow={false}
+ content={
+ <Input
+ autoFocus
+ defaultValue={title}
+ onBlur={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ onChange={(e) => setNewTitle(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ onPressEnter={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ />
+ }
+ destroyOnHidden
+ onOpenChange={(open) => {
+ if (!open) handleUpdate();
+ toggleEditing(open);
+ }}
+ open={editing}
+ placement={'bottomLeft'}
+ styles={{
+ body: {
+ padding: 4,
+ width: 320,
+ },
+ }}
+ trigger={['click']}
+ >
+ <div />
+ </Popover>
+ );
+});
+
+export default Editing;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
new file mode 100644
index 00000000000..1454db297d5
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
@@ -0,0 +1,70 @@
+import { Dropdown, Icon } from '@lobehub/ui';
+import { TreeDownRightIcon } from '@lobehub/ui/icons';
+import { useTheme } from 'antd-style';
+import { memo, useCallback } from 'react';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useChatStore } from '@/store/chat';
+
+import { useThreadNavigation } from '../../../hooks/useThreadNavigation';
+import Actions from './Actions';
+import Editing from './Editing';
+import { useThreadItemDropdownMenu } from './useDropdownMenu';
+
+export interface ThreadItemProps {
+ id: string;
+ index: number;
+ title: string;
+}
+
+const ThreadItem = memo<ThreadItemProps>(({ title, id }) => {
+ const theme = useTheme();
+ const [editing, activeThreadId] = useChatStore((s) => [
+ s.threadRenamingId === id,
+ s.activeThreadId,
+ ]);
+
+ const { navigateToThread, isInAgentSubRoute } = useThreadNavigation();
+
+ const toggleEditing = useCallback(
+ (visible?: boolean) => {
+ useChatStore.setState({ threadRenamingId: visible ? id : '' });
+ },
+ [id],
+ );
+
+ const handleClick = useCallback(() => {
+ if (editing) return;
+ navigateToThread(id);
+ }, [editing, id, navigateToThread]);
+
+ const dropdownMenu = useThreadItemDropdownMenu({
+ id,
+ toggleEditing,
+ });
+
+ const active = id === activeThreadId;
+
+ return (
+ <>
+ <Dropdown
+ menu={{
+ items: dropdownMenu,
+ }}
+ trigger={['contextMenu']}
+ >
+ <NavItem
+ actions={<Actions dropdownMenu={dropdownMenu} />}
+ active={active && !isInAgentSubRoute}
+ disabled={editing}
+ icon={<Icon color={theme.colorTextDescription} icon={TreeDownRightIcon} size={'small'} />}
+ onClick={handleClick}
+ title={title}
+ />
+ </Dropdown>
+ <Editing id={id} title={title} toggleEditing={toggleEditing} />
+ </>
+ );
+});
+
+export default ThreadItem;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
new file mode 100644
index 00000000000..76e817a25ff
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
@@ -0,0 +1,54 @@
+import { Icon, type MenuProps } from '@lobehub/ui';
+import { App } from 'antd';
+import { PencilLine, Trash } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+
+interface ThreadItemDropdownMenuProps {
+ id: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+export const useThreadItemDropdownMenu = ({
+ id,
+ toggleEditing,
+}: ThreadItemDropdownMenuProps): MenuProps['items'] => {
+ const { t } = useTranslation(['thread', 'common']);
+ const { modal } = App.useApp();
+
+ const [removeThread] = useChatStore((s) => [s.removeThread]);
+
+ return useMemo(() => {
+ return [
+ {
+ icon: <Icon icon={PencilLine} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: () => {
+ toggleEditing(true);
+ },
+ },
+ {
+ type: 'divider' as const,
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: () => {
+ modal.confirm({
+ centered: true,
+ okButtonProps: { danger: true },
+ onOk: async () => {
+ await removeThread(id);
+ },
+ title: t('actions.confirmRemoveThread'),
+ });
+ },
+ },
+ ].filter(Boolean) as MenuProps['items'];
+ }, [id, removeThread, toggleEditing, t, modal]);
+};
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadList/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx
similarity index 57%
rename from src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadList/index.tsx
rename to src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx
index 69a44922197..6db2180c240 100644
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadList/index.tsx
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx
@@ -1,10 +1,11 @@
import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
import { useFetchThreads } from '@/hooks/useFetchThreads';
import { useChatStore } from '@/store/chat';
import { threadSelectors } from '@/store/chat/selectors';
-import ThreadItem from '../ThreadItem';
+import ThreadItem from './ThreadItem';
const ThreadList = memo(() => {
const [id] = useChatStore((s) => [s.activeTopicId]);
@@ -12,9 +13,15 @@ const ThreadList = memo(() => {
useFetchThreads(id);
- return threads?.map((item, index) => (
- <ThreadItem id={item.id} index={index} key={item.id} title={item.title} />
- ));
+ if (!threads || threads.length === 0) return;
+
+ return (
+ <Flexbox gap={1} paddingBlock={1}>
+ {threads?.map((item, index) => (
+ <ThreadItem id={item.id} index={index} key={item.id} title={item.title} />
+ ))}
+ </Flexbox>
+ );
});
ThreadList.displayName = 'ThreadList';
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/index.tsx
new file mode 100644
index 00000000000..530383909e6
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/index.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useFetchTopics } from '@/hooks/useFetchTopics';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+import { TopicDisplayMode } from '@/types/topic';
+
+import ByTimeMode from './ByTimeMode';
+import FlatMode from './FlatMode';
+import SearchResult from './SearchResult';
+
+const TopicListContent = memo(() => {
+ const { t } = useTranslation('topic');
+ const router = useQueryRoute();
+ const topicLength = useChatStore((s) => topicSelectors.currentTopicLength(s));
+ const [agentId, isUndefinedTopics, isInSearchMode] = useChatStore((s) => [
+ s.activeAgentId,
+ topicSelectors.isUndefinedTopics(s),
+ topicSelectors.isInSearchMode(s),
+ ]);
+
+ const [topicDisplayMode] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s)]);
+
+ useFetchTopics();
+
+ if (isInSearchMode) return <SearchResult />;
+
+ // Show skeleton when current session's topic data is not yet loaded
+ if (isUndefinedTopics) return <SkeletonList />;
+
+ return (
+ <>
+ {topicLength === 0 && (
+ <EmptyNavItem
+ onClick={() => {
+ router.push(urlJoin('/agent', agentId));
+ }}
+ title={t('actions.addNewTopic')}
+ />
+ )}
+ {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ </>
+ );
+});
+
+TopicListContent.displayName = 'TopicListContent';
+
+export default TopicListContent;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicSearchBar/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicSearchBar/index.tsx
similarity index 88%
rename from src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicSearchBar/index.tsx
rename to src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicSearchBar/index.tsx
index a879a0c4d47..27784d8156c 100644
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicSearchBar/index.tsx
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicSearchBar/index.tsx
@@ -14,9 +14,12 @@ const TopicSearchBar = memo<{ onClear?: () => void }>(({ onClear }) => {
const [tempValue, setTempValue] = useState('');
const [searchKeyword, setSearchKeywords] = useState('');
const mobile = useServerConfigStore((s) => s.isMobile);
- const [activeSessionId, useSearchTopics] = useChatStore((s) => [s.activeId, s.useSearchTopics]);
+ const [activeAgentId, useSearchTopics] = useChatStore((s) => [
+ s.activeAgentId,
+ s.useSearchTopics,
+ ]);
- useSearchTopics(searchKeyword, activeSessionId);
+ useSearchTopics(searchKeyword, { agentId: activeAgentId });
useUnmount(() => {
useChatStore.setState({ inSearchingMode: false, isSearchingTopic: false });
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
new file mode 100644
index 00000000000..b78c1cb1a34
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
@@ -0,0 +1,49 @@
+import { usePathname } from 'next/navigation';
+import { useCallback } from 'react';
+import { useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+/**
+ * Hook to handle thread navigation with automatic route detection
+ * If in agent sub-route (e.g., /agent/:aid/profile), navigate back to chat first
+ */
+export const useThreadNavigation = () => {
+ const pathname = usePathname();
+ const params = useParams();
+ const router = useQueryRoute();
+ const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
+ const switchThread = useChatStore((s) => s.switchThread);
+
+ const isInAgentSubRoute = useCallback(() => {
+ if (!params.aid) return false;
+ const agentBasePath = `/agent/${params.aid}`;
+ // If pathname has more segments after /agent/:aid, it's a sub-route
+ return (
+ pathname.startsWith(agentBasePath) &&
+ pathname !== agentBasePath &&
+ pathname !== `${agentBasePath}/`
+ );
+ }, [pathname, params.aid]);
+
+ const navigateToThread = useCallback(
+ (threadId: string) => {
+ // If in agent sub-route, navigate back to agent chat first
+ if (isInAgentSubRoute() && params.aid) {
+ router.push(urlJoin('/agent', params.aid as string));
+ }
+
+ switchThread(threadId);
+ toggleConfig(false);
+ },
+ [params.aid, router, switchThread, toggleConfig, isInAgentSubRoute],
+ );
+
+ return {
+ isInAgentSubRoute: isInAgentSubRoute(),
+ navigateToThread,
+ };
+};
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
new file mode 100644
index 00000000000..16acaede85a
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
@@ -0,0 +1,49 @@
+import { usePathname } from 'next/navigation';
+import { useCallback } from 'react';
+import { useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+/**
+ * Hook to handle topic navigation with automatic route detection
+ * If in agent sub-route (e.g., /agent/:aid/profile), navigate back to chat first
+ */
+export const useTopicNavigation = () => {
+ const pathname = usePathname();
+ const params = useParams();
+ const router = useQueryRoute();
+ const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
+ const switchTopic = useChatStore((s) => s.switchTopic);
+
+ const isInAgentSubRoute = useCallback(() => {
+ if (!params.aid) return false;
+ const agentBasePath = `/agent/${params.aid}`;
+ // If pathname has more segments after /agent/:aid, it's a sub-route
+ return (
+ pathname.startsWith(agentBasePath) &&
+ pathname !== agentBasePath &&
+ pathname !== `${agentBasePath}/`
+ );
+ }, [pathname, params.aid]);
+
+ const navigateToTopic = useCallback(
+ (topicId?: string) => {
+ // If in agent sub-route, navigate back to agent chat first
+ if (isInAgentSubRoute() && params.aid) {
+ router.push(urlJoin('/agent', params.aid as string));
+ }
+
+ switchTopic(topicId);
+ toggleConfig(false);
+ },
+ [params.aid, router, switchTopic, toggleConfig, isInAgentSubRoute],
+ );
+
+ return {
+ isInAgentSubRoute: isInAgentSubRoute(),
+ navigateToTopic,
+ };
+};
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/index.tsx
new file mode 100644
index 00000000000..cbe84bbe07a
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/index.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { AccordionItem, Dropdown, Text } from '@lobehub/ui';
+import React, { Suspense, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import Actions from './Actions';
+import List from './List';
+import { useTopicActionsDropdownMenu } from './useDropdownMenu';
+
+interface TopicProps {
+ itemKey: string;
+}
+
+const Topic = memo<TopicProps>(({ itemKey }) => {
+ const { t } = useTranslation(['topic', 'common']);
+ const [topicCount] = useChatStore((s) => [topicSelectors.currentTopicCount(s)]);
+ const dropdownMenu = useTopicActionsDropdownMenu();
+
+ return (
+ <AccordionItem
+ action={<Actions />}
+ headerWrapper={(header) => (
+ <Dropdown
+ menu={{
+ items: dropdownMenu,
+ }}
+ trigger={['contextMenu']}
+ >
+ {header}
+ </Dropdown>
+ )}
+ itemKey={itemKey}
+ paddingBlock={4}
+ paddingInline={'8px 4px'}
+ title={
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {`${t('title')} ${topicCount > 0 ? topicCount : ''}`}
+ </Text>
+ }
+ >
+ <Suspense fallback={<SkeletonList />}>
+ <Flexbox gap={1} paddingBlock={1}>
+ <List />
+ </Flexbox>
+ </Suspense>
+ </AccordionItem>
+ );
+});
+
+export default Topic;
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/useDropdownMenu.tsx
new file mode 100644
index 00000000000..beef73fc002
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -0,0 +1,109 @@
+import { Icon, type MenuProps } from '@lobehub/ui';
+import { App } from 'antd';
+import { Hash, LucideCheck, Trash } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+import { TopicDisplayMode } from '@/types/topic';
+
+export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {
+ const { t } = useTranslation(['topic', 'common']);
+ const { modal } = App.useApp();
+
+ const [removeUnstarredTopic, removeAllTopic] = useChatStore((s) => [
+ s.removeUnstarredTopic,
+ s.removeSessionTopics,
+ ]);
+
+ const [topicDisplayMode, updatePreference] = useUserStore((s) => [
+ preferenceSelectors.topicDisplayMode(s),
+ s.updatePreference,
+ ]);
+
+ const [topicPageSize, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.topicPageSize(s),
+ s.updateSystemStatus,
+ ]);
+
+ return useMemo(() => {
+ const displayModeItems = Object.values(TopicDisplayMode).map((mode) => ({
+ icon: topicDisplayMode === mode ? <Icon icon={LucideCheck} /> : <div />,
+ key: mode,
+ label: t(`groupMode.${mode}`),
+ onClick: () => {
+ updatePreference({ topicDisplayMode: mode });
+ },
+ }));
+
+ const pageSizeOptions = [20, 40, 60, 100];
+ const pageSizeItems = pageSizeOptions.map((size) => ({
+ icon: topicPageSize === size ? <Icon icon={LucideCheck} /> : <div />,
+ key: `pageSize-${size}`,
+ label: `${size} 个条目`,
+ onClick: () => {
+ updateSystemStatus({ topicPageSize: size });
+ },
+ }));
+
+ return [
+ ...displayModeItems,
+ {
+ type: 'divider' as const,
+ },
+ {
+ children: pageSizeItems,
+ icon: <Icon icon={Hash} />,
+ key: 'displayItems',
+ label: t('displayItems'),
+ },
+ {
+ type: 'divider' as const,
+ },
+ {
+ icon: <Icon icon={Trash} />,
+ key: 'deleteUnstarred',
+ label: t('actions.removeUnstarred'),
+ onClick: () => {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ centered: true,
+ okButtonProps: { danger: true },
+ okText: t('ok', { ns: 'common' }),
+ onOk: removeUnstarredTopic,
+ title: t('actions.confirmRemoveUnstarred'),
+ });
+ },
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'deleteAll',
+ label: t('actions.removeAll'),
+ onClick: () => {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ centered: true,
+ okButtonProps: { danger: true },
+ okText: t('ok', { ns: 'common' }),
+ onOk: removeAllTopic,
+ title: t('actions.confirmRemoveAll'),
+ });
+ },
+ },
+ ].filter(Boolean) as MenuProps['items'];
+ }, [
+ topicDisplayMode,
+ topicPageSize,
+ updatePreference,
+ updateSystemStatus,
+ removeUnstarredTopic,
+ removeAllTopic,
+ t,
+ modal,
+ ]);
+};
diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/index.tsx
new file mode 100644
index 00000000000..db1183cf640
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/index.tsx
@@ -0,0 +1,19 @@
+import React, { memo } from 'react';
+
+import { NavPanelPortal } from '@/features/NavPanel';
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import Body from './Body';
+import Header from './Header';
+
+const Sidebar = memo(() => {
+ return (
+ <NavPanelPortal navKey="agent">
+ <SideBarLayout body={<Body />} header={<Header />} />
+ </NavPanelPortal>
+ );
+});
+
+Sidebar.displayName = 'ChatSidebar';
+
+export default Sidebar;
diff --git a/src/app/[variants]/(main)/chat/_layout/index.tsx b/src/app/[variants]/(main)/chat/_layout/index.tsx
new file mode 100644
index 00000000000..1d78b9a1358
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/_layout/index.tsx
@@ -0,0 +1,44 @@
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+import { Outlet } from 'react-router-dom';
+
+import AgentIdSync from '@/app/[variants]/(main)/chat/_layout/AgentIdSync';
+import { isDesktop } from '@/const/version';
+import ProtocolUrlHandler from '@/features/ProtocolUrlHandler';
+import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
+
+import RegisterHotkeys from './RegisterHotkeys';
+import Sidebar from './Sidebar';
+
+const Layout = memo(() => {
+ const theme = useTheme();
+ useInitAgentConfig();
+
+ return (
+ <>
+ <Sidebar />
+ <Flexbox
+ flex={1}
+ height={'100%'}
+ style={{
+ background: theme.colorBgContainer,
+ overflow: 'hidden',
+ position: 'relative',
+ }}
+ >
+ <Outlet />
+ </Flexbox>
+ {/* ↓ cloud slot ↓ */}
+
+ {/* ↑ cloud slot ↑ */}
+ <RegisterHotkeys />
+ {isDesktop && <ProtocolUrlHandler />}
+ <AgentIdSync />
+ </>
+ );
+});
+
+Layout.displayName = 'DesktopChatLayout';
+
+export default Layout;
diff --git a/src/app/[variants]/(main)/chat/_layout/type.ts b/src/app/[variants]/(main)/chat/_layout/type.ts
deleted file mode 100644
index 4d063a09f7f..00000000000
--- a/src/app/[variants]/(main)/chat/_layout/type.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { ReactNode } from 'react';
-
-export interface LayoutProps {
- children: ReactNode;
-}
diff --git a/src/app/[variants]/(main)/chat/components/ConversationArea.tsx b/src/app/[variants]/(main)/chat/components/ConversationArea.tsx
deleted file mode 100644
index d880461fa6e..00000000000
--- a/src/app/[variants]/(main)/chat/components/ConversationArea.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { memo } from 'react';
-
-import ChatHydration from './conversation/features/ChatHydration';
-import ChatInput from './conversation/features/ChatInput';
-import ChatList from './conversation/features/ChatList';
-import ChatMinimap from './conversation/features/ChatMinimap';
-import ThreadHydration from './conversation/features/ThreadHydration';
-import ZenModeToast from './conversation/features/ZenModeToast';
-
-interface ConversationAreaProps {
- mobile?: boolean;
-}
-
-const ConversationArea = memo<ConversationAreaProps>(({ mobile = false }) => {
- return (
- <>
- <ZenModeToast />
- <ChatList mobile={mobile} />
- <ChatInput mobile={mobile} />
- <ChatHydration />
- <ThreadHydration />
- {!mobile && <ChatMinimap />}
- </>
- );
-});
-
-ConversationArea.displayName = 'ConversationArea';
-
-export default ConversationArea;
diff --git a/src/app/[variants]/(main)/chat/components/SessionPanel.tsx b/src/app/[variants]/(main)/chat/components/SessionPanel.tsx
deleted file mode 100644
index c6b5a707afb..00000000000
--- a/src/app/[variants]/(main)/chat/components/SessionPanel.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Suspense, lazy, memo } from 'react';
-
-import CircleLoading from '@/components/Loading/CircleLoading';
-
-import DesktopLayout from '../session/layout/Desktop';
-import MobileLayout from '../session/layout/Mobile';
-import SessionHydration from '../session/features/SessionHydration';
-import SkeletonList from '../session/features/SkeletonList';
-
-const SessionListContent = lazy(() => import('../session/features/SessionListContent'));
-
-interface SessionPanelProps {
- mobile?: boolean;
-}
-
-const SessionPanel = memo<SessionPanelProps>(({ mobile }) => {
- const Layout = mobile ? MobileLayout : DesktopLayout;
-
- return (
- <Suspense fallback={<CircleLoading />}>
- <Layout>
- <Suspense fallback={<SkeletonList />}>
- <SessionListContent />
- </Suspense>
- </Layout>
- <SessionHydration />
- </Suspense>
- );
-});
-
-SessionPanel.displayName = 'SessionPanel';
-
-export default SessionPanel;
diff --git a/src/app/[variants]/(main)/chat/components/TopicSidebar.tsx b/src/app/[variants]/(main)/chat/components/TopicSidebar.tsx
deleted file mode 100644
index 279e0d94239..00000000000
--- a/src/app/[variants]/(main)/chat/components/TopicSidebar.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import dynamic from 'next/dynamic';
-import { memo } from 'react';
-
-import DesktopLayout from './topic/_layout/Desktop';
-import MobileLayout from './topic/_layout/Mobile';
-import SkeletonList from './topic/features/SkeletonList';
-import Topic from './topic/features/Topic';
-
-const ConfigSwitcher = dynamic(() => import('./topic/features/ConfigSwitcher'), {
- loading: () => <SkeletonList />,
-});
-
-interface TopicSidebarProps {
- mobile?: boolean;
-}
-
-const TopicSidebar = memo<TopicSidebarProps>(({ mobile }) => {
- const Layout = mobile ? MobileLayout : DesktopLayout;
-
- return (
- <Layout>
- <ConfigSwitcher />
- <Topic />
- </Layout>
- );
-});
-
-TopicSidebar.displayName = 'TopicSidebar';
-
-export default TopicSidebar;
diff --git a/src/app/[variants]/(main)/chat/components/WorkspaceLayout.tsx b/src/app/[variants]/(main)/chat/components/WorkspaceLayout.tsx
deleted file mode 100644
index 7567da8fb6c..00000000000
--- a/src/app/[variants]/(main)/chat/components/WorkspaceLayout.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import { Suspense, memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import MainInterfaceTracker from '@/components/Analytics/MainInterfaceTracker';
-import BrandTextLoading from '@/components/Loading/BrandTextLoading';
-import MobileContentLayout from '@/components/server/MobileNavLayout';
-
-import ChatHeaderDesktop from '../components/layout/Desktop/ChatHeader';
-import Portal from '../components/layout/Desktop/Portal';
-import TopicPanel from '../components/layout/Desktop/TopicPanel';
-import ChatHeaderMobile from '../components/layout/Mobile/ChatHeader';
-import TopicModal from '../components/layout/Mobile/TopicModal';
-import ConversationArea from './ConversationArea';
-import PortalPanel from './PortalPanel';
-import TopicSidebar from './TopicSidebar';
-
-
-const DesktopWorkspace = memo(() => (
- <>
- <ChatHeaderDesktop />
- <Flexbox
- height={'100%'}
- horizontal
- style={{ overflow: 'hidden', position: 'relative' }}
- width={'100%'}
- >
- <Flexbox height={'100%'} style={{ overflow: 'hidden', position: 'relative' }} width={'100%'}>
- <ConversationArea mobile={false} />
- </Flexbox>
- <Portal>
- <Suspense fallback={<BrandTextLoading />}>
- <PortalPanel mobile={false} />
- </Suspense>
- </Portal>
- <TopicPanel>
- <TopicSidebar mobile={false} />
- </TopicPanel>
- </Flexbox>
- <MainInterfaceTracker />
- </>
-));
-
-DesktopWorkspace.displayName = 'DesktopWorkspace';
-
-const MobileWorkspace = memo(() => (
- <>
- <MobileContentLayout header={<ChatHeaderMobile />} style={{ overflowY: 'hidden' }}>
- <ConversationArea mobile />
- </MobileContentLayout>
- <TopicModal>
- <TopicSidebar mobile />
- </TopicModal>
- <PortalPanel mobile />
- <MainInterfaceTracker />
- </>
-));
-
-MobileWorkspace.displayName = 'MobileWorkspace';
-
-export { DesktopWorkspace, MobileWorkspace };
diff --git a/src/app/[variants]/(main)/chat/components/conversation/default.tsx b/src/app/[variants]/(main)/chat/components/conversation/default.tsx
deleted file mode 100644
index 5c4e5b6e5bd..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/default.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { DynamicLayoutProps } from '@/types/next';
-import { RouteVariants } from '@/utils/server/routeVariants';
-
-import ChatHydration from './features/ChatHydration';
-import ChatInput from './features/ChatInput';
-import ChatList from './features/ChatList';
-import ChatMinimap from './features/ChatMinimap';
-import ThreadHydration from './features/ThreadHydration';
-import ZenModeToast from './features/ZenModeToast';
-
-const ChatConversation = async (props: DynamicLayoutProps) => {
- const isMobile = await RouteVariants.getIsMobile(props);
-
- return (
- <>
- <ZenModeToast />
- <ChatList mobile={isMobile} />
- <ChatInput mobile={isMobile} />
- <ChatHydration />
- <ThreadHydration />
- {!isMobile && <ChatMinimap />}
- </>
- );
-};
-
-ChatConversation.displayName = 'ChatConversation';
-
-export default ChatConversation;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/ClassicChat.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/ClassicChat.tsx
deleted file mode 100644
index 9a9b886bd4d..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/ClassicChat.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-'use client';
-
-import { Alert } from '@lobehub/ui';
-import { Suspense, memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { type ActionKeys, ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';
-import WideScreenContainer from '@/features/ChatList/components/WideScreenContainer';
-import { useChatStore } from '@/store/chat';
-import { aiChatSelectors } from '@/store/chat/selectors';
-
-import { useSend } from '../useSend';
-import MessageFromUrl from './MessageFromUrl';
-import { useSendMenuItems } from './useSendMenuItems';
-
-const leftActions: ActionKeys[] = [
- 'model',
- 'search',
- 'typo',
- 'fileUpload',
- 'knowledgeBase',
- 'tools',
- '---',
- ['params', 'history', 'stt', 'clear'],
- 'mainToken',
-];
-
-const rightActions: ActionKeys[] = ['saveTopic'];
-
-const ClassicChatInput = memo(() => {
- const { t } = useTranslation('chat');
- const { send, generating, disabled, stop } = useSend();
-
- const [mainInputSendErrorMsg, clearSendMessageError] = useChatStore((s) => [
- aiChatSelectors.isCurrentSendMessageError(s),
- s.clearSendMessageError,
- ]);
-
- const sendMenuItems = useSendMenuItems();
-
- return (
- <ChatInputProvider
- chatInputEditorRef={(instance) => {
- if (!instance) return;
- useChatStore.setState({ mainInputEditor: instance });
- }}
- leftActions={leftActions}
- onMarkdownContentChange={(content) => {
- useChatStore.setState({ inputMessage: content });
- }}
- onSend={() => {
- send();
- }}
- rightActions={rightActions}
- sendButtonProps={{ disabled, generating, onStop: stop }}
- sendMenu={{
- items: sendMenuItems,
- }}
- >
- <WideScreenContainer>
- {mainInputSendErrorMsg && (
- <Flexbox paddingBlock={'0 6px'} paddingInline={12}>
- <Alert
- closable
- message={t('input.errorMsg', { errorMsg: mainInputSendErrorMsg })}
- onClose={clearSendMessageError}
- type={'warning'}
- />
- </Flexbox>
- )}
- <DesktopChatInput />
- </WideScreenContainer>
- <Suspense>
- <MessageFromUrl />
- </Suspense>
- </ChatInputProvider>
- );
-});
-
-export default ClassicChatInput;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/index.tsx
deleted file mode 100644
index f2e8683be72..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/index.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-'use client';
-
-import { memo } from 'react';
-
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-
-import ClassicChatInput from './ClassicChat';
-import GroupChatInput from './GroupChat';
-
-const Desktop = memo((props: { targetMemberId?: string }) => {
- const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);
- return isGroupSession ? <GroupChatInput {...props} /> : <ClassicChatInput />;
-});
-
-export default Desktop;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/MentionedUsers/MentionedUserItem.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/MentionedUsers/MentionedUserItem.tsx
deleted file mode 100644
index 40bf85def3d..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/MentionedUsers/MentionedUserItem.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { Avatar, Text } from '@lobehub/ui';
-import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { useMentionStore } from '@/store/mention';
-
-interface MentionedUserItemProps {
- agent: any; // The actual agent data from the group
-}
-
-const MentionedUserItem = memo<MentionedUserItemProps>(({ agent }) => {
- const removeMentionedUser = useMentionStore((s: any) => s.removeMentionedUser);
-
- const handleRemove = () => {
- removeMentionedUser(agent.id);
- };
-
- return (
- <Flexbox
- align={'center'}
- gap={8}
- horizontal
- style={{
- background: 'rgba(0, 0, 0, 0.04)',
- borderRadius: 16,
- padding: '8px 12px',
- position: 'relative',
- }}
- >
- <Avatar avatar={agent.avatar} background={agent.backgroundColor} shape="circle" size={24} />
- <Text ellipsis={{ tooltip: true }} style={{ fontSize: 12, maxWidth: 80 }}>
- {agent.title || agent.id}
- </Text>
- <div
- onClick={handleRemove}
- style={{
- alignItems: 'center',
- background: 'rgba(0, 0, 0, 0.1)',
- borderRadius: '50%',
- cursor: 'pointer',
- display: 'flex',
- height: 16,
- justifyContent: 'center',
- padding: 2,
- width: 16,
- }}
- >
- <Text style={{ fontSize: 10, lineHeight: 1 }}>×</Text>
- </div>
- </Flexbox>
- );
-});
-
-export default MentionedUserItem;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/MentionedUsers/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/MentionedUsers/index.tsx
deleted file mode 100644
index 82292ae90da..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/MentionedUsers/index.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { useMentionStore } from '@/store/mention';
-import { mentionSelectors } from '@/store/mention/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-
-import MentionedUserItem from './MentionedUserItem';
-
-const MentionedUsers = memo(() => {
- const currentSession = useSessionStore(sessionSelectors.currentSession);
- const mentionedUsers = useMentionStore(mentionSelectors.mentionedUsers);
- const hasMentionedUsers = useMentionStore(mentionSelectors.hasMentionedUsers);
-
- const groupMembers = useSessionStore(sessionSelectors.currentGroupAgents);
-
- const mentionedAgents = (groupMembers || []).filter((member) =>
- mentionedUsers.includes(member.id || ''),
- );
-
- if (currentSession?.type !== 'group' || !hasMentionedUsers || mentionedAgents.length === 0)
- return null;
-
- return (
- <Flexbox paddingBlock={4} style={{ position: 'relative' }}>
- <Flexbox
- gap={4}
- horizontal
- padding={'4px 8px 8px'}
- style={{ overflow: 'scroll', width: '100%' }}
- >
- {mentionedAgents.map((member) => (
- <MentionedUserItem agent={member} key={member.id} />
- ))}
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default MentionedUsers;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/index.tsx
deleted file mode 100644
index 1f1f14e75fb..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Mobile/index.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-'use client';
-
-import { Alert } from '@lobehub/ui';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import {
- type ActionKey,
- type ActionKeys,
- MobileChatInput as ChatInput,
- ChatInputProvider,
-} from '@/features/ChatInput';
-import { useChatStore } from '@/store/chat';
-import { aiChatSelectors } from '@/store/chat/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-
-import { useSend, useSendGroupMessage } from '../useSend';
-
-const leftActions: ActionKeys[] = [
- 'model',
- 'search',
- 'fileUpload',
- 'knowledgeBase',
- 'tools',
- '---',
- ['params', 'history', 'stt', 'clear'],
- 'mainToken',
- 'mention',
-];
-
-const rightActions: ActionKey[] = ['saveTopic'];
-
-const MobileChatInput = memo(() => {
- const { t } = useTranslation('chat');
- const { send, disabled, generating, stop } = useSend();
- const { send: sendGroupMessage } = useSendGroupMessage();
-
- const isSessionGroup = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);
-
- const [mainInputSendErrorMsg, clearSendMessageError] = useChatStore((s) => [
- aiChatSelectors.isCurrentSendMessageError(s),
- s.clearSendMessageError,
- ]);
- return (
- <ChatInputProvider
- chatInputEditorRef={(instance) => {
- if (!instance) return;
- useChatStore.setState({ mainInputEditor: instance });
- }}
- leftActions={leftActions}
- mobile
- onMarkdownContentChange={(content) => {
- useChatStore.setState({ inputMessage: content });
- }}
- onSend={() => {
- if (isSessionGroup) {
- sendGroupMessage();
- } else {
- send();
- }
- }}
- rightActions={rightActions}
- sendButtonProps={{ disabled, generating, onStop: stop }}
- >
- {mainInputSendErrorMsg && (
- <Flexbox paddingBlock={'0 6px'} paddingInline={12}>
- <Alert
- closable
- message={t('input.errorMsg', { errorMsg: mainInputSendErrorMsg })}
- onClose={clearSendMessageError}
- type={'warning'}
- />
- </Flexbox>
- )}
- <ChatInput />
- </ChatInputProvider>
- );
-});
-
-MobileChatInput.displayName = 'MobileChatInput';
-
-export default MobileChatInput;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/ActionBar.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/ActionBar.tsx
deleted file mode 100644
index 6c9ecb6dea3..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/ActionBar.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { ChatInputActionBar } from '@lobehub/ui/chat';
-import { memo } from 'react';
-
-import { ActionKeys, actionMap } from '@/features/ChatInput/ActionBar/config';
-
-const RenderActionList = ({ dataSource }: { dataSource: ActionKeys[] }) => (
- <>
- {dataSource.map((key) => {
- // @ts-ignore
- const Render = actionMap[key];
- return <Render key={key} />;
- })}
- </>
-);
-
-export interface ActionBarProps {
- leftActions: ActionKeys[];
- padding?: number | string;
- rightActions: ActionKeys[];
-}
-
-const ActionBar = memo<ActionBarProps>(({ padding = '0 8px', leftActions, rightActions }) => (
- <ChatInputActionBar
- leftAddons={<RenderActionList dataSource={leftActions} />}
- padding={padding}
- rightAddons={<RenderActionList dataSource={rightActions} />}
- />
-));
-
-export default ActionBar;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/Files/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/Files/index.tsx
deleted file mode 100644
index 52d3f5c8708..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/Files/index.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { PreviewGroup } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
-import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import FileItem from '@/features/ChatInput/Mobile/FilePreview/FileItem';
-import { filesSelectors, useFileStore } from '@/store/file';
-
-const Files = memo(() => {
- const list = useFileStore(filesSelectors.chatUploadFileList, isEqual);
-
- if (!list || list?.length === 0) return null;
-
- return (
- <Flexbox paddingBlock={4} style={{ position: 'relative' }}>
- <Flexbox
- gap={4}
- horizontal
- padding={'4px 8px 8px'}
- style={{ overflow: 'scroll', width: '100%' }}
- >
- <PreviewGroup>
- {list.map((i) => (
- <FileItem {...i} key={i.id} loading={i.status === 'pending'} />
- ))}
- </PreviewGroup>
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default Files;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/InputArea/Container.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/InputArea/Container.tsx
deleted file mode 100644
index e24c628f311..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/InputArea/Container.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { css, cx } from 'antd-style';
-import { FC, ReactNode, memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-const container = css`
- height: inherit;
- padding-block: 0;
- padding-inline: 8px;
-`;
-
-interface InnerContainerProps {
- bottomAddons?: ReactNode;
- children: ReactNode;
- expand?: boolean;
- textAreaLeftAddons?: ReactNode;
- textAreaRightAddons?: ReactNode;
- topAddons?: ReactNode;
-}
-
-const InnerContainer: FC<InnerContainerProps> = memo(
- ({ children, expand, textAreaRightAddons, textAreaLeftAddons, bottomAddons, topAddons }) =>
- expand ? (
- <Flexbox className={cx(container)} gap={8}>
- <Flexbox gap={8} horizontal justify={'flex-end'}>
- {textAreaLeftAddons}
- {textAreaRightAddons}
- </Flexbox>
- {children}
- {topAddons}
- {bottomAddons}
- </Flexbox>
- ) : (
- <Flexbox align={'flex-end'} className={cx(container)} gap={8} horizontal>
- {textAreaLeftAddons}
- {children}
- {textAreaRightAddons}
- </Flexbox>
- ),
-);
-
-export default InnerContainer;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/InputArea/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/InputArea/index.tsx
deleted file mode 100644
index bfa8d36fb2f..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/InputArea/index.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import { ActionIcon, TextArea } from '@lobehub/ui';
-import { SafeArea } from '@lobehub/ui/mobile';
-import { useSize } from 'ahooks';
-import { createStyles } from 'antd-style';
-import { TextAreaRef } from 'antd/es/input/TextArea';
-import { ChevronDown, ChevronUp } from 'lucide-react';
-import { rgba } from 'polished';
-import { CSSProperties, ReactNode, forwardRef, useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import InnerContainer from './Container';
-
-const useStyles = createStyles(({ css, token }) => {
- return {
- container: css`
- flex: none;
- padding-block: 12px 12px;
- border-block-start: 1px solid ${rgba(token.colorBorder, 0.25)};
- background: ${token.colorFillQuaternary};
- `,
- expand: css`
- position: absolute;
- height: 100%;
- `,
- expandButton: css`
- position: absolute;
- inset-inline-start: 14px;
- `,
- textarea: css`
- flex: 1;
- transition: none !important;
- `,
- };
-});
-
-export interface MobileChatInputAreaProps {
- bottomAddons?: ReactNode;
- className?: string;
- expand?: boolean;
- loading?: boolean;
- onInput?: (value: string) => void;
- onSend?: () => void;
- safeArea?: boolean;
- setExpand?: (expand: boolean) => void;
- style?: CSSProperties;
- textAreaLeftAddons?: ReactNode;
- textAreaRightAddons?: ReactNode;
- topAddons?: ReactNode;
- value: string;
-}
-
-const MobileChatInputArea = forwardRef<TextAreaRef, MobileChatInputAreaProps>(
- (
- {
- className,
- style,
- topAddons,
- textAreaLeftAddons,
- textAreaRightAddons,
- bottomAddons,
- expand = false,
- setExpand,
- onSend,
- onInput,
- loading,
- value,
- safeArea,
- },
- ref,
- ) => {
- const { t } = useTranslation('chat');
- const isChineseInput = useRef(false);
- const containerRef = useRef<HTMLDivElement>(null);
- const { cx, styles } = useStyles();
- const size = useSize(containerRef);
- const [showFullscreen, setShowFullscreen] = useState<boolean>(false);
- const [isFocused, setIsFocused] = useState<boolean>(false);
-
- useEffect(() => {
- if (!size?.height) return;
- setShowFullscreen(size.height > 72);
- }, [size]);
-
- const showAddons = !expand && !isFocused;
-
- return (
- <Flexbox
- className={cx(styles.container, expand && styles.expand, className)}
- gap={12}
- style={style}
- >
- {topAddons && <Flexbox style={showAddons ? {} : { display: 'none' }}>{topAddons}</Flexbox>}
- <Flexbox
- className={cx(expand && styles.expand)}
- ref={containerRef}
- style={{ position: 'relative' }}
- >
- {showFullscreen && (
- <ActionIcon
- active
- className={styles.expandButton}
- icon={expand ? ChevronDown : ChevronUp}
- onClick={() => setExpand?.(!expand)}
- size={{ blockSize: 24, borderRadius: '50%', size: 14 }}
- style={expand ? { top: 6 } : {}}
- />
- )}
- <InnerContainer
- bottomAddons={bottomAddons}
- expand={expand}
- textAreaLeftAddons={textAreaLeftAddons}
- textAreaRightAddons={textAreaRightAddons}
- topAddons={topAddons}
- >
- <TextArea
- autoSize={expand ? false : { maxRows: 6, minRows: 0 }}
- className={styles.textarea}
- onBlur={(e) => {
- onInput?.(e.target.value);
- setIsFocused(false);
- }}
- onChange={(e) => {
- onInput?.(e.target.value);
- }}
- onCompositionEnd={() => {
- isChineseInput.current = false;
- }}
- onCompositionStart={() => {
- isChineseInput.current = true;
- }}
- onFocus={() => setIsFocused(true)}
- onPressEnter={(e) => {
- if (!loading && !isChineseInput.current && e.shiftKey) {
- e.preventDefault();
- onSend?.();
- }
- }}
- placeholder={t('sendPlaceholder')}
- ref={ref}
- style={{ height: 36, paddingBlock: 6 }}
- value={value}
- variant={expand ? 'borderless' : 'filled'}
- />
- </InnerContainer>
- </Flexbox>
- {bottomAddons && (
- <Flexbox style={showAddons ? {} : { display: 'none' }}>{bottomAddons}</Flexbox>
- )}
- {safeArea && !isFocused && <SafeArea position={'bottom'} />}
- </Flexbox>
- );
- },
-);
-
-export default MobileChatInputArea;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/Send.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/Send.tsx
deleted file mode 100644
index f5f54de983a..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/Send.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { ActionIcon, type ActionIconSize, Button } from '@lobehub/ui';
-import { Loader2, SendHorizontal } from 'lucide-react';
-import { memo } from 'react';
-
-export interface MobileChatSendButtonProps {
- disabled?: boolean;
- loading?: boolean;
- onSend?: () => void;
- onStop?: () => void;
-}
-
-const MobileChatSendButton = memo<MobileChatSendButtonProps>(
- ({ loading, onStop, onSend, disabled }) => {
- const size: ActionIconSize = {
- blockSize: 36,
- size: 16,
- };
-
- return loading ? (
- <ActionIcon active icon={Loader2} onClick={onStop} size={size} spin />
- ) : (
- <Button
- disabled={disabled}
- icon={SendHorizontal}
- onClick={onSend}
- style={{ flex: 'none' }}
- type={'primary'}
- />
- );
- },
-);
-
-export default MobileChatSendButton;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/index.tsx
deleted file mode 100644
index d509fca9bf2..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/index.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-'use client';
-
-import { Skeleton } from 'antd';
-import { useTheme } from 'antd-style';
-import { TextAreaRef } from 'antd/es/input/TextArea';
-import { memo, useRef, useState } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { ActionKeys } from '@/features/ChatInput/ActionBar/config';
-import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
-import { useChatStore } from '@/store/chat';
-import { operationSelectors } from '@/store/chat/selectors';
-
-import ActionBar from './ActionBar';
-import Files from './Files';
-import InputArea from './InputArea';
-import SendButton from './Send';
-import { useSendMessage } from './useSend';
-
-const defaultLeftActions: ActionKeys[] = [
- 'model',
- 'search',
- 'fileUpload',
- 'knowledgeBase',
- 'tools',
- 'params',
- 'mainToken',
-];
-
-const defaultRightActions: ActionKeys[] = ['saveTopic', 'clear'];
-
-const MobileChatInput = memo(() => {
- const theme = useTheme();
- const ref = useRef<TextAreaRef>(null);
- const [expand, setExpand] = useState<boolean>(false);
- const { send: sendMessage, canSend } = useSendMessage();
- const { isLoading } = useInitAgentConfig();
-
- const [loading, value, onInput, onStop] = useChatStore((s) => [
- operationSelectors.isAgentRuntimeRunning(s),
- s.inputMessage,
- s.updateMessageInput,
- s.stopGenerateMessage,
- ]);
-
- return (
- <InputArea
- expand={expand}
- onInput={onInput}
- onSend={() => {
- setExpand(false);
-
- sendMessage();
- }}
- ref={ref}
- setExpand={setExpand}
- style={{
- background: theme.colorBgLayout,
- top: expand ? 0 : undefined,
- width: '100%',
- zIndex: 101,
- }}
- textAreaRightAddons={
- <SendButton disabled={!canSend} loading={loading} onSend={sendMessage} onStop={onStop} />
- }
- topAddons={
- isLoading ? (
- <Flexbox paddingInline={8}>
- <Skeleton.Button active block size={'small'} />
- </Flexbox>
- ) : (
- <>
- <Files />
- <ActionBar
- leftActions={defaultLeftActions}
- padding={'0 8px'}
- rightActions={defaultRightActions}
- />
- </>
- )
- }
- value={value}
- />
- );
-});
-
-MobileChatInput.displayName = 'MobileChatInput';
-
-export default MobileChatInput;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/useSend.ts b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/useSend.ts
deleted file mode 100644
index 4c06714194f..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/V1Mobile/useSend.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { SendMessageParams } from '@lobechat/types';
-import { useAnalytics } from '@lobehub/analytics/react';
-import { useCallback, useMemo } from 'react';
-
-import { useGeminiChineseWarning } from '@/hooks/useGeminiChineseWarning';
-import { getAgentStoreState } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
-import {
- chatSelectors,
- messageStateSelectors,
- operationSelectors,
- topicSelectors,
-} from '@/store/chat/selectors';
-import { fileChatSelectors, useFileStore } from '@/store/file';
-import { getUserStoreState } from '@/store/user';
-
-export type UseSendMessageParams = Pick<
- SendMessageParams,
- 'onlyAddUserMessage' | 'isWelcomeQuestion'
->;
-
-export const useSendMessage = () => {
- const [sendMessage, updateMessageInput] = useChatStore((s) => [
- s.sendMessage,
- s.updateMessageInput,
- ]);
- const { analytics } = useAnalytics();
- const checkGeminiChineseWarning = useGeminiChineseWarning();
-
- const clearChatUploadFileList = useFileStore((s) => s.clearChatUploadFileList);
-
- const isUploadingFiles = useFileStore(fileChatSelectors.isUploadingFiles);
- const isSendButtonDisabledByMessage = useChatStore(
- messageStateSelectors.isSendButtonDisabledByMessage,
- );
-
- const canSend = !isUploadingFiles && !isSendButtonDisabledByMessage;
-
- const send = useCallback(async (params: UseSendMessageParams = {}) => {
- const store = useChatStore.getState();
- if (operationSelectors.isAgentRuntimeRunning(store)) return;
-
- // if uploading file or send button is disabled by message, then we should not send the message
- const isUploadingFiles = fileChatSelectors.isUploadingFiles(useFileStore.getState());
- const isSendButtonDisabledByMessage = messageStateSelectors.isSendButtonDisabledByMessage(
- useChatStore.getState(),
- );
-
- const canSend = !isUploadingFiles && !isSendButtonDisabledByMessage;
- if (!canSend) return;
-
- const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());
- // if there is no message and no image, then we should not send the message
- if (!store.inputMessage && fileList.length === 0) return;
-
- // Check for Chinese text warning with Gemini model
- const agentStore = getAgentStoreState();
- const currentModel = agentSelectors.currentAgentModel(agentStore);
- const shouldContinue = await checkGeminiChineseWarning({
- model: currentModel,
- prompt: store.inputMessage,
- scenario: 'chat',
- });
-
- if (!shouldContinue) return;
-
- sendMessage({
- files: fileList,
- message: store.inputMessage,
- ...params,
- });
-
- updateMessageInput('');
- clearChatUploadFileList();
-
- // 获取分析数据
- const userStore = getUserStoreState();
-
- // 直接使用现有数据结构判断消息类型
- const hasImages = fileList.some((file) => file.file?.type?.startsWith('image'));
- const messageType = fileList.length === 0 ? 'text' : hasImages ? 'image' : 'file';
-
- analytics?.track({
- name: 'send_message',
- properties: {
- chat_id: store.activeId || 'unknown',
- current_topic: topicSelectors.currentActiveTopic(store)?.title || null,
- has_attachments: fileList.length > 0,
- history_message_count: chatSelectors.activeBaseChats(store).length,
- message: store.inputMessage,
- message_length: store.inputMessage.length,
- message_type: messageType,
- selected_model: agentSelectors.currentAgentModel(agentStore),
- session_id: store.activeId || 'inbox', // 当前活跃的会话ID
- user_id: userStore.user?.id || 'anonymous',
- },
- });
- // const hasSystemRole = agentSelectors.hasSystemRole(useAgentStore.getState());
- // const agentSetting = useAgentStore.getState().agentSettingInstance;
-
- // // if there is a system role, then we need to use agent setting instance to autocomplete agent meta
- // if (hasSystemRole && !!agentSetting) {
- // agentSetting.autocompleteAllMeta();
- // }
- }, []);
-
- return useMemo(() => ({ canSend, send }), [canSend]);
-};
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/index.tsx
deleted file mode 100644
index 9365a7af1f1..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/index.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import DesktopChatInput from './Desktop';
-import MobileChatInput from './V1Mobile';
-
-interface ChatInputProps {
- mobile: boolean;
- targetMemberId?: string;
-}
-
-const ChatInput = ({ mobile, targetMemberId }: ChatInputProps) => {
- const Input = mobile ? MobileChatInput : DesktopChatInput;
-
- return <Input targetMemberId={targetMemberId} />;
-};
-
-export default ChatInput;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/useSend.ts b/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/useSend.ts
deleted file mode 100644
index 68b5de8ff83..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/useSend.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-import { useAnalytics } from '@lobehub/analytics/react';
-import { useCallback, useMemo } from 'react';
-
-import { useGeminiChineseWarning } from '@/hooks/useGeminiChineseWarning';
-import { getAgentStoreState } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { getChatStoreState, useChatStore } from '@/store/chat';
-import {
- aiChatSelectors,
- displayMessageSelectors,
- messageStateSelectors,
- operationSelectors,
- topicSelectors,
-} from '@/store/chat/selectors';
-import { fileChatSelectors, useFileStore } from '@/store/file';
-import { mentionSelectors, useMentionStore } from '@/store/mention';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors } from '@/store/session/selectors';
-import { getUserStoreState } from '@/store/user';
-
-export interface UseSendMessageParams {
- isWelcomeQuestion?: boolean;
- onlyAddAIMessage?: boolean;
- onlyAddUserMessage?: boolean;
-}
-
-export type UseSendGroupMessageParams = UseSendMessageParams & {
- targetMemberId?: string;
-};
-
-export const useSend = () => {
- const [
- isContentEmpty,
- sendMessage,
- addAIMessage,
- stopGenerateMessage,
- cancelSendMessageInServer,
- isAgentRuntimeRunning,
- isSendButtonDisabledByMessage,
- isSendingMessage,
- ] = useChatStore((s) => [
- !s.inputMessage,
- s.sendMessage,
- s.addAIMessage,
- s.stopGenerateMessage,
- s.cancelSendMessageInServer,
- operationSelectors.isMainWindowAgentRuntimeRunning(s),
- messageStateSelectors.isSendButtonDisabledByMessage(s),
- aiChatSelectors.isCurrentSendMessageLoading(s),
- ]);
- const { analytics } = useAnalytics();
- const checkGeminiChineseWarning = useGeminiChineseWarning();
-
- // 使用订阅以保持最新文件列表
- const reactiveFileList = useFileStore(fileChatSelectors.chatUploadFileList);
- const [isUploadingFiles, clearChatUploadFileList] = useFileStore((s) => [
- fileChatSelectors.isUploadingFiles(s),
- s.clearChatUploadFileList,
- ]);
-
- const isInputEmpty = isContentEmpty && reactiveFileList.length === 0;
-
- const canNotSend =
- isInputEmpty || isUploadingFiles || isSendButtonDisabledByMessage || isSendingMessage;
-
- const handleSend = async (params: UseSendMessageParams = {}) => {
- if (canNotSend) return;
-
- const store = useChatStore.getState();
- const mainInputEditor = store.mainInputEditor;
-
- if (!mainInputEditor) {
- console.warn('not found mainInputEditor instance');
- return;
- }
-
- if (operationSelectors.isMainWindowAgentRuntimeRunning(store)) return;
-
- const inputMessage = store.inputMessage;
- // 发送时再取一次最新的文件列表,防止闭包拿到旧值
- const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());
-
- // if there is no message and no image, then we should not send the message
- if (!inputMessage && fileList.length === 0) return;
-
- // Check for Chinese text warning with Gemini model
- const agentStore = getAgentStoreState();
- const currentModel = agentSelectors.currentAgentModel(agentStore);
- const shouldContinue = await checkGeminiChineseWarning({
- model: currentModel,
- prompt: inputMessage,
- scenario: 'chat',
- });
-
- if (!shouldContinue) return;
-
- if (params.onlyAddAIMessage) {
- addAIMessage();
- } else {
- sendMessage({ files: fileList, message: inputMessage, ...params });
- }
-
- clearChatUploadFileList();
- mainInputEditor.setExpand(false);
- mainInputEditor.clearContent();
- mainInputEditor.focus();
-
- // 获取分析数据
- const userStore = getUserStoreState();
-
- // 直接使用现有数据结构判断消息类型(支持 video)
- const hasImages = fileList.some((file) => file.file?.type?.startsWith('image'));
- const hasVideos = fileList.some((file) => file.file?.type?.startsWith('video'));
- const messageType =
- fileList.length === 0 ? 'text' : hasVideos ? 'video' : hasImages ? 'image' : 'file';
-
- analytics?.track({
- name: 'send_message',
- properties: {
- chat_id: store.activeId || 'unknown',
- current_topic: topicSelectors.currentActiveTopic(store)?.title || null,
- has_attachments: fileList.length > 0,
- history_message_count: displayMessageSelectors.activeDisplayMessages(store).length,
- message: inputMessage,
- message_length: inputMessage.length,
- message_type: messageType,
- selected_model: agentSelectors.currentAgentModel(agentStore),
- session_id: store.activeId || 'inbox', // 当前活跃的会话ID
- user_id: userStore.user?.id || 'anonymous',
- },
- });
- };
-
- const stop = () => {
- const store = getChatStoreState();
- const isRunning = operationSelectors.isMainWindowAgentRuntimeRunning(store);
-
- if (isRunning) {
- stopGenerateMessage();
- return;
- }
-
- const isCreatingMessage = aiChatSelectors.isCurrentSendMessageLoading(store);
-
- if (isCreatingMessage) {
- cancelSendMessageInServer();
- }
- };
-
- return useMemo(
- () => ({
- disabled: canNotSend,
- generating: isAgentRuntimeRunning || isSendingMessage,
- send: handleSend,
- stop,
- }),
- [canNotSend, isAgentRuntimeRunning, isSendingMessage, stop, handleSend],
- );
-};
-
-export const useSendGroupMessage = () => {
- const [
- isContentEmpty,
- sendGroupMessage,
- updateMessageInput,
- stopGenerateMessage,
- isSendButtonDisabledByMessage,
- isCreatingMessage,
- ] = useChatStore((s) => [
- !s.inputMessage,
- s.sendGroupMessage,
- s.updateMessageInput,
- s.stopGenerateMessage,
- messageStateSelectors.isSendButtonDisabledByMessage(s),
- messageStateSelectors.isCreatingMessage(s),
- ]);
-
- const isSupervisorThinking = useChatStore((s) =>
- displayMessageSelectors.isSupervisorLoading(s.activeId)(s),
- );
- const { analytics } = useAnalytics();
- const checkGeminiChineseWarning = useGeminiChineseWarning();
-
- const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());
- const [isUploadingFiles, clearChatUploadFileList] = useFileStore((s) => [
- fileChatSelectors.isUploadingFiles(s),
- s.clearChatUploadFileList,
- ]);
-
- const isInputEmpty = isContentEmpty && fileList.length === 0;
-
- const canNotSend =
- isInputEmpty ||
- isUploadingFiles ||
- isSendButtonDisabledByMessage ||
- isCreatingMessage ||
- isSupervisorThinking;
-
- const handleSend = useCallback(
- async (params: UseSendGroupMessageParams = {}) => {
- if (canNotSend) return;
-
- const store = useChatStore.getState();
- if (!store.activeId) return;
-
- const mainInputEditor = store.mainInputEditor;
- if (!mainInputEditor) {
- console.warn('not found mainInputEditor instance');
- return;
- }
-
- if (
- displayMessageSelectors.isSupervisorLoading(store.activeId)(store) ||
- messageStateSelectors.isCreatingMessage(store)
- )
- return;
-
- const inputMessage = store.inputMessage;
-
- // if there is no message and no files, then we should not send the message
- if (!inputMessage && fileList.length === 0) return;
-
- // Check for Chinese text warning with Gemini model
- const agentStore = getAgentStoreState();
- const currentModel = agentSelectors.currentAgentModel(agentStore);
- const shouldContinue = await checkGeminiChineseWarning({
- model: currentModel,
- prompt: inputMessage,
- scenario: 'chat',
- });
-
- if (!shouldContinue) return;
-
- // Append mentioned users as plain text like "@userName"
- const mentionState = useMentionStore.getState();
- const mentioned = mentionSelectors.mentionedUsers(mentionState);
- const sessionState = useSessionStore.getState();
- const mentionText =
- mentioned.length > 0
- ? ` ${mentioned
- .map((id) => sessionMetaSelectors.getAgentMetaByAgentId(id)(sessionState).title || id)
- .map((name) => `@${name}`)
- .join(' ')}`
- : '';
- const messageWithMentions = `${inputMessage}${mentionText}`.trim();
-
- sendGroupMessage({
- files: fileList,
- groupId: store.activeId,
- message: messageWithMentions,
- targetMemberId: params.targetMemberId,
- ...params,
- });
-
- clearChatUploadFileList();
- mainInputEditor.setExpand(false);
- mainInputEditor.clearContent();
- mainInputEditor.focus();
- updateMessageInput('');
- // clear mentioned users after sending
- mentionState.clearMentionedUsers();
-
- // 获取分析数据
- const userStore = getUserStoreState();
- const hasImages = fileList.some((file) => file.file?.type?.startsWith('image'));
- const messageType = fileList.length === 0 ? 'text' : hasImages ? 'image' : 'file';
-
- analytics?.track({
- name: 'send_group_message',
- properties: {
- chat_id: store.activeId || 'unknown',
- current_topic: topicSelectors.currentActiveTopic(store)?.title || null,
- has_attachments: fileList.length > 0,
- history_message_count: displayMessageSelectors.activeDisplayMessages(store).length,
- message: inputMessage,
- message_length: inputMessage.length,
- message_type: messageType,
- selected_model: agentSelectors.currentAgentModel(agentStore),
- session_id: store.activeId || 'inbox', // 当前活跃的会话ID
- user_id: userStore.user?.id || 'anonymous',
- },
- });
- },
- [
- canNotSend,
- fileList,
- clearChatUploadFileList,
- updateMessageInput,
- analytics,
- checkGeminiChineseWarning,
- ],
- );
-
- const stop = useCallback(() => {
- const store = getChatStoreState();
- const isAgentRunning = operationSelectors.isMainWindowAgentRuntimeRunning(store);
- const isCreating = messageStateSelectors.isCreatingMessage(store);
-
- if (isAgentRunning) {
- stopGenerateMessage();
- return;
- }
-
- if (isCreating) {
- // For group messages, we don't have a separate cancel method like in single chat
- // The isCreatingMessage state will be reset when the operation completes
- // We can potentially add a cancel group message functionality in the future
- console.warn('Group message creation in progress, cannot cancel');
- }
- }, [stopGenerateMessage]);
-
- return useMemo(
- () => ({
- disabled: canNotSend,
- generating: isSupervisorThinking || isCreatingMessage,
- send: handleSend,
- stop,
- updateMessageInput,
- }),
- [canNotSend, isSupervisorThinking, isCreatingMessage, handleSend, stop, updateMessageInput],
- );
-};
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/OrchestratorThinking.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/OrchestratorThinking.tsx
deleted file mode 100644
index 371a8581086..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/OrchestratorThinking.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { ActionIcon, Text } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { StopCircle } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Center } from 'react-layout-kit';
-
-import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
-import { useSessionStore } from '@/store/session';
-import { shinyTextStylish } from '@/styles/loading';
-
-const useStyles = createStyles(({ token, css }) => ({
- container: css`
- .show-on-hover {
- opacity: 0;
- transition: all ease-in-out 0.3ms;
- }
-
- :hover {
- .show-on-hover {
- opacity: 1;
- }
- }
- `,
-
- shinyText: shinyTextStylish(token),
-}));
-
-const SupervisorThinkingTag = memo(() => {
- const { t } = useTranslation('chat');
- const activeGroupId = useSessionStore((s) => s.activeId);
- const isSupervisorLoading = useChatStore(chatSelectors.isSupervisorLoading(activeGroupId || ''));
- const cancelSupervisorDecision = useChatStore((s) => s.internal_cancelSupervisorDecision);
- const { styles } = useStyles();
-
- if (!isSupervisorLoading) return null;
-
- return (
- <Center className={styles.container} gap={4} horizontal paddingBlock={'12px 24px'}>
- <Text className={styles.shinyText} type={'secondary'}>
- {t('group.orchestratorThinking')}
- </Text>
- <ActionIcon
- icon={StopCircle}
- onClick={(e) => {
- e.stopPropagation();
- cancelSupervisorDecision(activeGroupId);
- }}
- size={'small'}
- title={t('groupSidebar.members.stopOrchestrator')}
- />
- </Center>
- );
-});
-
-export default SupervisorThinkingTag;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/index.tsx
deleted file mode 100644
index 2988bd3a448..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/index.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { createStyles } from 'antd-style';
-import React, { memo } from 'react';
-
-import { ChatItem } from '@/features/ChatList';
-import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors } from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
-import { displayMessageSelectors, threadSelectors } from '@/store/chat/selectors';
-
-import SupervisorThinkingTag from './OrchestratorThinking';
-import Thread from './Thread';
-
-const useStyles = createStyles(({ css, token, isDarkMode }) => {
- const borderColor = isDarkMode ? token.colorFillSecondary : token.colorFillTertiary;
-
- return {
- end: css`
- &::after {
- inset-inline-end: 36px;
- border-inline-end: 2px solid ${borderColor};
- border-end-end-radius: 8px;
- }
- `,
- line: css`
- &::after {
- content: '';
-
- position: absolute;
- inset-block-end: 60px;
-
- width: 38px;
- height: 53px;
- border-block-end: 2px solid ${borderColor};
- }
- `,
- start: css`
- &::after {
- inset-inline-start: 30px;
- border-inline-start: 2px solid ${borderColor};
- border-end-start-radius: 8px;
- }
- `,
- };
-});
-
-export interface ThreadChatItemProps {
- id: string;
- index: number;
-}
-
-const MainChatItem = memo<ThreadChatItemProps>(({ id, index }) => {
- const { styles, cx } = useStyles();
-
- const [showThread, historyLength] = useChatStore((s) => [
- threadSelectors.hasThreadBySourceMsgId(id)(s),
- displayMessageSelectors.mainDisplayChatIDs(s).length,
- ]);
-
- const [displayMode, enableHistoryDivider] = useAgentStore((s) => [
- agentChatConfigSelectors.displayMode(s),
- agentChatConfigSelectors.enableHistoryDivider(historyLength, index)(s),
- ]);
-
- const userRole = useChatStore((s) => displayMessageSelectors.getDisplayMessageById(id)(s)?.role);
-
- const placement = displayMode === 'chat' && userRole === 'user' ? 'end' : 'start';
-
- const isLatestItem = historyLength === index + 1;
-
- return (
- <>
- <ChatItem
- className={showThread ? cx(styles.line, styles[placement]) : ''}
- enableHistoryDivider={enableHistoryDivider}
- endRender={showThread && <Thread id={id} placement={placement} />}
- id={id}
- index={index}
- isLatestItem={isLatestItem}
- />
- {isLatestItem && <SupervisorThinkingTag />}
- </>
- );
-});
-
-export default MainChatItem;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/Content.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/Content.tsx
deleted file mode 100644
index c839538cec1..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/Content.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-'use client';
-
-import React, { memo, useCallback } from 'react';
-
-import { SkeletonList, VirtualizedList } from '@/features/ChatList';
-import WideScreenContainer from '@/features/ChatList/components/WideScreenContainer';
-import { useFetchMessages } from '@/hooks/useFetchMessages';
-import { useChatStore } from '@/store/chat';
-import { displayMessageSelectors } from '@/store/chat/selectors';
-
-import MainChatItem from './ChatItem';
-import Welcome from './WelcomeChatItem';
-
-interface ListProps {
- mobile?: boolean;
-}
-
-const Content = memo<ListProps>(({ mobile }) => {
- const [isCurrentChatLoaded] = useChatStore((s) => [
- displayMessageSelectors.isCurrentDisplayChatLoaded(s),
- ]);
-
- useFetchMessages();
- const data = useChatStore(displayMessageSelectors.mainDisplayChatIDs);
-
- const itemContent = useCallback(
- (index: number, id: string) => <MainChatItem id={id} index={index} />,
- [mobile],
- );
-
- if (!isCurrentChatLoaded) return <SkeletonList mobile={mobile} />;
-
- if (data.length === 0)
- return (
- <WideScreenContainer flex={1} height={'100%'}>
- <Welcome />
- </WideScreenContainer>
- );
-
- return <VirtualizedList dataSource={data} itemContent={itemContent} mobile={mobile} />;
-});
-
-Content.displayName = 'ChatListRender';
-
-export default Content;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/index.tsx
deleted file mode 100644
index 6f1e6b9abad..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/index.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-'use client';
-
-import { BRANDING_NAME } from '@lobechat/const';
-import { FluentEmoji, Markdown } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import React, { memo, useMemo } from 'react';
-import { Trans, useTranslation } from 'react-i18next';
-import { Center, Flexbox } from 'react-layout-kit';
-
-import { useGreeting } from '@/hooks/useGreeting';
-import { useIsMobile } from '@/hooks/useIsMobile';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors } from '@/store/session/selectors';
-
-import AddButton from './AddButton';
-import OpeningQuestions from './OpeningQuestions';
-
-const useStyles = createStyles(({ css, responsive }) => ({
- container: css`
- align-items: center;
- ${responsive.mobile} {
- align-items: flex-start;
- }
- `,
- desc: css`
- font-size: 14px;
- text-align: center;
- ${responsive.mobile} {
- text-align: start;
- }
- `,
- title: css`
- margin-block: 0.2em 0;
- font-size: 32px;
- font-weight: bolder;
- line-height: 1;
- ${responsive.mobile} {
- font-size: 24px;
- }
- `,
-}));
-
-const InboxWelcome = memo(() => {
- const { t } = useTranslation(['welcome', 'chat']);
- const { styles } = useStyles();
- const mobile = useIsMobile();
- const greeting = useGreeting();
- const { showCreateSession } = useServerConfigStore(featureFlagsSelectors);
- const openingQuestions = useAgentStore(agentSelectors.openingQuestions);
-
- const meta = useSessionStore(sessionMetaSelectors.currentAgentMeta, isEqual);
-
- const agentSystemRoleMsg = t('agentDefaultMessageWithSystemRole', {
- name: meta.title || t('defaultAgent', { ns: 'chat' }),
- ns: 'chat',
- });
- const openingMessage = useAgentStore(agentSelectors.openingMessage);
-
- const showInboxWelcome = useChatStore(chatSelectors.showInboxWelcome);
-
- const message = useMemo(() => {
- if (openingMessage) return openingMessage;
- return agentSystemRoleMsg;
- }, [openingMessage, agentSystemRoleMsg, meta.description]);
-
- return (
- <Center gap={12} padding={16} width={'100%'}>
- <Flexbox className={styles.container} gap={16} style={{ maxWidth: 800 }} width={'100%'}>
- <Flexbox align={'center'} gap={8} horizontal>
- <FluentEmoji emoji={'👋'} size={40} type={'anim'} />
- <h1 className={styles.title}>{greeting}</h1>
- </Flexbox>
- <Markdown
- className={styles.desc}
- customRender={(dom, context) => {
- if (context.text.includes('<plus />')) {
- return (
- <Trans
- components={{
- br: <br />,
- plus: <AddButton />,
- }}
- i18nKey="guide.defaultMessage"
- ns="welcome"
- values={{ appName: BRANDING_NAME }}
- />
- );
- }
- return dom;
- }}
- variant={'chat'}
- >
- {showInboxWelcome
- ? t(showCreateSession ? 'guide.defaultMessage' : 'guide.defaultMessageWithoutCreate', {
- appName: BRANDING_NAME,
- })
- : message}
- </Markdown>
- {openingQuestions.length > 0 && (
- <OpeningQuestions mobile={mobile} questions={openingQuestions} />
- )}
- </Flexbox>
- </Center>
- );
-});
-
-export default InboxWelcome;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/GroupUsageSuggest.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/GroupUsageSuggest.tsx
deleted file mode 100644
index b0d32c35117..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/GroupUsageSuggest.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-'use client';
-
-import { ActionIcon, Block, Grid, Text } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { shuffle } from 'lodash-es';
-import { RefreshCw } from 'lucide-react';
-import { memo, useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useSendGroupMessage } from '../../../ChatInput/useSend';
-import { useTemplateMatching } from './useTemplateMatching';
-
-const useStyles = createStyles(({ css, token, responsive }) => ({
- card: css`
- cursor: pointer;
-
- position: relative;
-
- overflow: hidden;
-
- height: 100%;
- min-height: 110px;
- padding: 16px;
- border-radius: ${token.borderRadiusLG}px;
-
- background: ${token.colorBgContainer};
-
- transition: all ${token.motionDurationMid};
-
- &:hover {
- border-color: ${token.colorPrimary};
- box-shadow: 0 2px 8px ${token.colorPrimaryBg};
- }
-
- ${responsive.mobile} {
- min-height: 72px;
- }
- `,
- cardDesc: css`
- margin-block: 0 !important;
- color: ${token.colorTextDescription};
- `,
- cardTitle: css`
- margin-block: 0 !important;
- font-size: 16px;
- font-weight: bold;
- `,
- emoji: css`
- display: flex;
- flex: none;
- align-items: center;
- justify-content: center;
-
- width: 40px;
- height: 40px;
- border-radius: ${token.borderRadius}px;
-
- font-size: 24px;
-
- background: ${token.colorFillTertiary};
- `,
- title: css`
- color: ${token.colorTextDescription};
- `,
-}));
-
-// Get fallback activities from general section
-const getFallbackActivities = (t: any) => {
- const generalActivities = t('guide.groupActivities.general', { returnObjects: true }) as Record<
- string,
- { description: string; emoji: string; prompt: string; title: string }
- >;
- return generalActivities || {};
-};
-
-const GroupUsageSuggest = memo<{ mobile?: boolean }>(({ mobile }) => {
- const { t } = useTranslation('welcome');
- const { styles } = useStyles();
- const { updateMessageInput, send } = useSendGroupMessage();
- const templateMatch = useTemplateMatching();
-
- const itemsPerPage = mobile ? 2 : 4;
-
- // Use template-specific activities if available, otherwise use fallback
- const availableActivities = useMemo(() => {
- if (templateMatch?.activities && Object.keys(templateMatch.activities).length > 0) {
- return templateMatch.activities;
- }
- return getFallbackActivities(t);
- }, [templateMatch?.templateId, t]); // Use templateId instead of activities to prevent object reference issues
-
- const activityKeys = useMemo(() => Object.keys(availableActivities), [availableActivities]);
- const [shuffledActivityKeys, setShuffledActivityKeys] = useState<string[]>([]);
-
- // Initialize shuffled activities only once when activityKeys change
- useEffect(() => {
- if (activityKeys.length > 0) {
- setShuffledActivityKeys(shuffle([...activityKeys]));
- }
- }, [activityKeys]);
-
- const displayedActivityKeys = shuffledActivityKeys.slice(0, itemsPerPage);
-
- const handleRefresh = () => {
- if (activityKeys.length > 0) {
- setShuffledActivityKeys(shuffle([...activityKeys]));
- }
- };
-
- // Don't render if no activities available or not yet initialized
- if (!activityKeys.length || !shuffledActivityKeys.length) {
- return null;
- }
-
- return (
- <Flexbox gap={8} width={'100%'}>
- <Flexbox align={'center'} horizontal justify={'space-between'}>
- <div className={styles.title}>{t('guide.groupActivities.title')}</div>
- <ActionIcon
- icon={RefreshCw}
- onClick={handleRefresh}
- size={{ blockSize: 24, size: 14 }}
- title="Show more activities"
- />
- </Flexbox>
- <Grid gap={8} rows={2}>
- {displayedActivityKeys.map((activityKey) => {
- const activity = availableActivities[activityKey];
- if (!activity) return null;
-
- const { title, emoji, description, prompt } = activity;
-
- return (
- <Block
- className={styles.card}
- clickable
- gap={12}
- horizontal
- key={activityKey}
- onClick={() => {
- updateMessageInput(prompt);
- send();
- }}
- variant={'outlined'}
- >
- <div className={styles.emoji}>{emoji}</div>
- <Flexbox gap={2} style={{ overflow: 'hidden', width: '100%' }}>
- <Text className={styles.cardTitle} ellipsis={{ rows: 1 }}>
- {title}
- </Text>
- <Text className={styles.cardDesc} ellipsis={{ rows: mobile ? 1 : 2 }}>
- {description}
- </Text>
- </Flexbox>
- </Block>
- );
- })}
- </Grid>
- </Flexbox>
- );
-});
-
-export default GroupUsageSuggest;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/index.tsx
deleted file mode 100644
index 53180309e64..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/index.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-'use client';
-
-import { createStyles } from 'antd-style';
-import { memo } from 'react';
-import { Center, Flexbox } from 'react-layout-kit';
-
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-
-import GroupUsageSuggest from './GroupUsageSuggest';
-
-const useStyles = createStyles(({ css, responsive }) => ({
- container: css`
- align-items: center;
- ${responsive.mobile} {
- align-items: flex-start;
- }
- `,
- desc: css`
- font-size: 14px;
- text-align: center;
- ${responsive.mobile} {
- text-align: start;
- }
- `,
- title: css`
- margin-block: 0.2em 0;
- font-size: 32px;
- font-weight: bolder;
- line-height: 1;
- ${responsive.mobile} {
- font-size: 24px;
- }
- `,
-}));
-
-const GroupWelcome = memo(() => {
- const { styles } = useStyles();
- const mobile = useServerConfigStore((s) => s.isMobile);
- const { showWelcomeSuggest } = useServerConfigStore(featureFlagsSelectors);
-
- return (
- <Center padding={16} width={'100%'}>
- <Flexbox
- className={styles.container}
- gap={16}
- style={{ maxWidth: 800, paddingTop: '20px' }}
- width={'100%'}
- >
- {showWelcomeSuggest && <GroupUsageSuggest mobile={mobile} />}
- </Flexbox>
- </Center>
- );
-});
-
-export default GroupWelcome;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/index.tsx
deleted file mode 100644
index dc285620d88..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/index.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import React, { memo } from 'react';
-
-import { sessionSelectors } from '@/store/session/selectors';
-import { useSessionStore } from '@/store/session/store';
-
-import AgentWelcome from './AgentWelcome';
-import GroupWelcome from './GroupWelcome';
-
-const WelcomeChatItem = memo(() => {
- const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);
-
- if (isGroupSession) return <GroupWelcome />;
-
- return <AgentWelcome />;
-});
-
-export default WelcomeChatItem;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/index.tsx b/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/index.tsx
deleted file mode 100644
index f95522c96ef..00000000000
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/index.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Suspense, lazy } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { SkeletonList } from '@/features/ChatList';
-
-const Content = lazy(() => import('./Content'));
-
-interface ChatListProps {
- mobile?: boolean;
-}
-
-const ChatList = ({ mobile }: ChatListProps) => (
- <Flexbox
- flex={1}
- style={{
- overflowX: 'hidden',
- overflowY: 'auto',
- position: 'relative',
- }}
- width={'100%'}
- >
- <Suspense fallback={<SkeletonList mobile={mobile} />}>
- <Content mobile={mobile} />
- </Suspense>
- </Flexbox>
-);
-
-export default ChatList;
diff --git a/src/app/[variants]/(main)/chat/components/features/AgentSettings/index.tsx b/src/app/[variants]/(main)/chat/components/features/AgentSettings/index.tsx
deleted file mode 100644
index 0758dbbfaad..00000000000
--- a/src/app/[variants]/(main)/chat/components/features/AgentSettings/index.tsx
+++ /dev/null
@@ -1,188 +0,0 @@
-'use client';
-
-import { Drawer } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import HeaderContent from '@/app/[variants]/(main)/chat/settings/features/HeaderContent';
-import BrandWatermark from '@/components/BrandWatermark';
-import PanelTitle from '@/components/PanelTitle';
-import { INBOX_SESSION_ID } from '@/const/session';
-import { isDesktop } from '@/const/version';
-import { AgentCategory, AgentSettings as Settings } from '@/features/AgentSetting';
-import { AgentSettingsProvider } from '@/features/AgentSetting/AgentSettingsProvider';
-import { TITLE_BAR_HEIGHT } from '@/features/ElectronTitlebar';
-import Footer from '@/features/Setting/Footer';
-import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
-import { ChatSettingsTabs } from '@/store/global/initialState';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors } from '@/store/session/selectors';
-import { LobeSessionType } from '@/types/session';
-
-export interface AgentSettingsProps {
- agentId?: string;
- onClose?: () => void;
- open?: boolean;
-}
-
-/**
- * Support both agent ID and session ID
- * Consider choose agent id first, since
- * session ID will soon be deprecated
- */
-const AgentSettings = memo<AgentSettingsProps>(({ agentId, onClose, open }) => {
- const { t } = useTranslation('setting');
-
- // Use provided agentId or fall back to current active session
- const activeId = useSessionStore((s) => s.activeId);
- const id = agentId || activeId;
-
- // Get agent config and meta based on the provided or active agent ID
- const config = useAgentStore((s) => {
- if (agentId) {
- // Use the new selector that works with agent IDs
- return agentSelectors.getAgentConfigByAgentId(agentId)(s);
- } else if (id) {
- // Use the existing selector for session IDs
- return agentSelectors.getAgentConfigById(id)(s);
- } else {
- // Use current agent config
- return agentSelectors.currentAgentConfig(s);
- }
- }, isEqual);
- const meta = useSessionStore((s) => {
- if (agentId) {
- // Use the selector that works with agent IDs
- return sessionMetaSelectors.getAgentMetaByAgentId(agentId)(s);
- } else {
- // Use current agent meta for session-based access
- return sessionMetaSelectors.currentAgentMeta(s);
- }
- }, isEqual);
-
- const { isLoading } = useInitAgentConfig(agentId);
-
- // Handle global store state or use props
- const [showAgentSetting, globalUpdateAgentConfig] = useAgentStore((s) => [
- s.showAgentSetting,
- s.updateAgentConfig,
- ]);
- const [globalUpdateAgentMeta] = useSessionStore((s) => [
- s.updateSessionMeta,
- sessionMetaSelectors.currentAgentTitle(s),
- ]);
-
- // Create custom update functions that can target specific sessions
- const updateAgentConfig = async (config: any) => {
- if (agentId) {
- // Find the agent session ID from the agent ID
- const sessions = useSessionStore.getState().sessions || [];
- const agentSession = sessions.find(
- (session) => session.type === LobeSessionType.Agent && session.config?.id === agentId,
- );
-
- if (agentSession) {
- // Use the internal agent store function with the specific session ID
- await useAgentStore.getState().internal_updateAgentConfig(agentSession.id, config);
- }
- } else {
- // Use the global update function for current session
- await globalUpdateAgentConfig(config);
- }
- };
-
- const updateAgentMeta = async (meta: any) => {
- if (agentId) {
- // Find the agent session ID from the agent ID
- const sessions = useSessionStore.getState().sessions || [];
- const agentSession = sessions.find(
- (session) => session.type === LobeSessionType.Agent && session.config?.id === agentId,
- );
-
- if (agentSession) {
- // Use the session service directly with the specific session ID
- const { sessionService } = await import('@/services/session');
- await sessionService.updateSessionMeta(agentSession.id, meta);
- // Refresh sessions to update the UI
- await useSessionStore.getState().refreshSessions();
- }
- } else {
- // Use the global update function for current session
- await globalUpdateAgentMeta(meta);
- }
- };
-
- // Determine visibility - use prop if provided, otherwise use global state
- const isOpen = open !== undefined ? open : showAgentSetting;
-
- // Handle close - use prop if provided, otherwise use global state setter
- const handleClose = onClose || (() => useAgentStore.setState({ showAgentSetting: false }));
-
- const isInbox = id === INBOX_SESSION_ID;
-
- const [tab, setTab] = useState(isInbox ? ChatSettingsTabs.Prompt : ChatSettingsTabs.Meta);
-
- return (
- <AgentSettingsProvider
- config={config}
- id={id}
- loading={isLoading}
- meta={meta}
- onConfigChange={updateAgentConfig}
- onMetaChange={updateAgentMeta}
- >
- <Drawer
- containerMaxWidth={1280}
- height={isDesktop ? `calc(100vh - ${TITLE_BAR_HEIGHT}px)` : '100vh'}
- noHeader
- onClose={handleClose}
- open={isOpen}
- placement={'bottom'}
- sidebar={
- <Flexbox
- gap={20}
- style={{
- height: 'calc(100vh - 28px)',
- }}
- >
- <PanelTitle desc={t('header.sessionDesc')} title={t('header.session')} />
- <Flexbox flex={1} width={'100%'}>
- <AgentCategory setTab={setTab} tab={tab} />
- </Flexbox>
- <Flexbox align={'center'} gap={8} paddingInline={8} width={'100%'}>
- <HeaderContent modal />
- </Flexbox>
- <BrandWatermark paddingInline={12} />
- </Flexbox>
- }
- sidebarWidth={280}
- styles={{
- sidebarContent: {
- gap: 48,
- justifyContent: 'space-between',
- minHeight: isDesktop ? `calc(100% - ${TITLE_BAR_HEIGHT}px)` : '100%',
- paddingBlock: 24,
- paddingInline: 48,
- },
- }}
- >
- <Settings
- config={config}
- id={id}
- loading={isLoading}
- meta={meta}
- onConfigChange={updateAgentConfig}
- onMetaChange={updateAgentMeta}
- tab={tab}
- />
- <Footer />
- </Drawer>
- </AgentSettingsProvider>
- );
-});
-
-export default AgentSettings;
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/HeaderAction.tsx b/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/HeaderAction.tsx
deleted file mode 100644
index ca466e119cf..00000000000
--- a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/HeaderAction.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-'use client';
-
-import { ActionIcon } from '@lobehub/ui';
-import {
- PanelLeftRightDashedIcon,
- PanelRightClose,
- PanelRightOpen,
- SquareChartGanttIcon,
-} from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
-import { HotkeyEnum } from '@/types/hotkey';
-
-import SettingButton from '../../../features/SettingButton';
-import ShareButton from '../../../features/ShareButton';
-
-const HeaderAction = memo<{ className?: string }>(({ className }) => {
- const { t } = useTranslation('chat');
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleRightPanel));
- const [showAgentSettings, wideScreen, toggleConfig, toggleWideScreen] = useGlobalStore((s) => [
- systemStatusSelectors.showChatSideBar(s),
- systemStatusSelectors.wideScreen(s),
- s.toggleChatSideBar,
- s.toggleWideScreen,
- ]);
-
- const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
-
- return (
- <Flexbox className={className} gap={4} horizontal>
- <ActionIcon
- icon={wideScreen ? SquareChartGanttIcon : PanelLeftRightDashedIcon}
- onClick={() => toggleWideScreen()}
- size={DESKTOP_HEADER_ICON_SIZE}
- title={t(wideScreen ? 'toggleWideScreen.off' : 'toggleWideScreen.on')}
- tooltipProps={{
- placement: 'bottom',
- }}
- />
- <ShareButton />
- <ActionIcon
- icon={showAgentSettings ? PanelRightClose : PanelRightOpen}
- onClick={() => toggleConfig()}
- size={DESKTOP_HEADER_ICON_SIZE}
- title={t('toggleRightPanel.title', { ns: 'hotkey' })}
- tooltipProps={{
- hotkey,
- placement: 'bottom',
- }}
- />
- {isAgentEditable && <SettingButton />}
- </Flexbox>
- );
-});
-
-export default HeaderAction;
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Main.tsx b/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Main.tsx
deleted file mode 100644
index 23720005ddc..00000000000
--- a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Main.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-'use client';
-
-import { Avatar, GroupAvatar } from '@lobehub/ui';
-import { Skeleton } from 'antd';
-import { createStyles } from 'antd-style';
-import { Suspense, memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { DEFAULT_AVATAR } from '@/const/meta';
-import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
-import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
-import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors, sessionSelectors } from '@/store/session/selectors';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-import { GroupMemberWithAgent } from '@/types/session';
-
-import TogglePanelButton from '../../../../features/TogglePanelButton';
-import Tags from './Tags';
-
-const useStyles = createStyles(({ css }) => ({
- container: css`
- position: relative;
- overflow: hidden;
- flex: 1;
- max-width: 100%;
- `,
- tag: css`
- flex: none;
- align-items: baseline;
- `,
- title: css`
- overflow: hidden;
-
- font-size: 14px;
- font-weight: bold;
- line-height: 1.2;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
-}));
-
-const Main = memo<{ className?: string }>(({ className }) => {
- const { t } = useTranslation(['chat', 'hotkey']);
- const { styles } = useStyles();
- useInitAgentConfig();
- const [isPinned] = usePinnedAgentState();
-
- const [init, isInbox, title, avatar, backgroundColor, members, sessionType] = useSessionStore(
- (s) => {
- const session = sessionSelectors.currentSession(s);
-
- return [
- sessionSelectors.isSomeSessionActive(s),
- sessionSelectors.isInboxSession(s),
- sessionMetaSelectors.currentAgentTitle(s),
- sessionMetaSelectors.currentAgentAvatar(s),
- sessionMetaSelectors.currentAgentBackgroundColor(s),
- session?.type === 'group' ? session.members : undefined,
- session?.type,
- ];
- },
- );
-
- const currentUser = useUserStore((s) => ({
- avatar: userProfileSelectors.userAvatar(s),
- name: userProfileSelectors.displayUserName(s) || userProfileSelectors.nickName(s) || 'You',
- }));
-
- const isGroup = sessionType === 'group';
-
- const openChatSettings = useOpenChatSettings();
-
- const displayTitle = isInbox ? t('inbox.title') : title;
- const showSessionPanel = useGlobalStore(systemStatusSelectors.showSessionPanel);
-
- if (!init)
- return (
- <Flexbox align={'center'} className={className} gap={8} horizontal>
- {!isPinned && !showSessionPanel && <TogglePanelButton />}
- <Skeleton
- active
- avatar={{ shape: 'circle', size: 28 }}
- paragraph={false}
- title={{ style: { margin: 0, marginTop: 4 }, width: 200 }}
- />
- </Flexbox>
- );
-
- if (isGroup) {
- return (
- <Flexbox align={'center'} className={className} gap={12} horizontal>
- {!isPinned && !showSessionPanel && <TogglePanelButton />}
- <GroupAvatar
- avatars={[
- {
- avatar: currentUser.avatar || DEFAULT_AVATAR,
- },
- ...(members?.map((member: GroupMemberWithAgent) => ({
- avatar: member.avatar || DEFAULT_AVATAR,
- background: member.backgroundColor || undefined,
- })) || []),
- ]}
- onClick={() => openChatSettings()}
- size={32}
- title={title}
- />
- <Flexbox align={'center'} className={styles.container} gap={8} horizontal>
- <div className={styles.title}>{displayTitle}</div>
- <Tags />
- </Flexbox>
- </Flexbox>
- );
- }
-
- return (
- <Flexbox align={'center'} className={className} gap={12} horizontal>
- {!isPinned && !showSessionPanel && <TogglePanelButton />}
- <Avatar
- avatar={avatar}
- background={backgroundColor}
- onClick={() => openChatSettings()}
- size={32}
- title={title}
- />
- <Flexbox align={'center'} className={styles.container} gap={8} horizontal>
- <div className={styles.title}>{displayTitle}</div>
- <Tags />
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default memo<{ className?: string }>(({ className }) => (
- <Suspense
- fallback={
- <Skeleton
- active
- avatar={{ shape: 'circle', size: 'default' }}
- paragraph={false}
- title={{ style: { margin: 0, marginTop: 8 }, width: 200 }}
- />
- }
- >
- <Main className={className} />
- </Suspense>
-));
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/index.tsx b/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/index.tsx
deleted file mode 100644
index 86f7cf2fe43..00000000000
--- a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/index.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-'use client';
-
-import { ChatHeader } from '@lobehub/ui/chat';
-
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-
-import HeaderAction from './HeaderAction';
-import Main from './Main';
-
-const Header = () => {
- const showHeader = useGlobalStore(systemStatusSelectors.showChatHeader);
-
- return (
- showHeader && (
- <ChatHeader
- left={<Main />}
- right={<HeaderAction />}
- style={{
- height: 40,
- maxHeight: 40,
- minHeight: 40,
- paddingInline: 8,
- position: 'initial',
- zIndex: 11,
- }}
- />
- )
- );
-};
-
-export default Header;
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/TopicPanel.tsx b/src/app/[variants]/(main)/chat/components/layout/Desktop/TopicPanel.tsx
deleted file mode 100644
index a5bb2a3643e..00000000000
--- a/src/app/[variants]/(main)/chat/components/layout/Desktop/TopicPanel.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-'use client';
-
-import { DraggablePanel, DraggablePanelContainer } from '@lobehub/ui';
-import { createStyles, useResponsive } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import { PropsWithChildren, memo, useEffect, useState } from 'react';
-
-import { CHAT_SIDEBAR_WIDTH } from '@/const/layoutTokens';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-
-const useStyles = createStyles(({ css, token }) => ({
- content: css`
- display: flex;
- flex-direction: column;
- height: 100% !important;
- `,
- drawer: css`
- z-index: 20;
- background: ${token.colorBgContainerSecondary};
- `,
- header: css`
- border-block-end: 1px solid ${token.colorBorderSecondary};
- `,
-}));
-
-const TopicPanel = memo(({ children }: PropsWithChildren) => {
- const { styles } = useStyles();
- const { md = true, lg = true } = useResponsive();
- const [showTopic, toggleConfig] = useGlobalStore((s) => [
- systemStatusSelectors.showChatSideBar(s),
- s.toggleChatSideBar,
- ]);
- const showPortal = useChatStore(chatPortalSelectors.showPortal);
-
- const [cacheExpand, setCacheExpand] = useState<boolean>(Boolean(showTopic));
-
- const handleExpand = (expand: boolean) => {
- if (isEqual(expand, Boolean(showTopic))) return;
- toggleConfig(expand);
- setCacheExpand(expand);
- };
-
- useEffect(() => {
- if (lg && cacheExpand) toggleConfig(true);
- if (!lg) toggleConfig(false);
- }, [lg, cacheExpand]);
-
- return (
- <DraggablePanel
- className={styles.drawer}
- classNames={{
- content: styles.content,
- }}
- expand={showTopic && !showPortal}
- minWidth={CHAT_SIDEBAR_WIDTH}
- mode={md ? 'fixed' : 'float'}
- onExpandChange={handleExpand}
- placement={'right'}
- showHandleWhenCollapsed={false}
- showHandleWideArea={false}
- styles={{
- handle: { display: 'none' },
- }}
- >
- <DraggablePanelContainer
- style={{
- flex: 'none',
- height: '100%',
- maxHeight: '100vh',
- minWidth: CHAT_SIDEBAR_WIDTH,
- }}
- >
- {children}
- </DraggablePanelContainer>
- </DraggablePanel>
- );
-});
-
-export default TopicPanel;
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/index.tsx b/src/app/[variants]/(main)/chat/components/layout/Desktop/index.tsx
deleted file mode 100644
index 3bf54201415..00000000000
--- a/src/app/[variants]/(main)/chat/components/layout/Desktop/index.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { Suspense } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import MainInterfaceTracker from '@/components/Analytics/MainInterfaceTracker';
-import BrandTextLoading from '@/components/Loading/BrandTextLoading';
-
-import { LayoutProps } from '../type';
-import ChatHeader from './ChatHeader';
-import Portal from './Portal';
-import TopicPanel from './TopicPanel';
-
-const Layout = ({ children, topic, conversation, portal }: LayoutProps) => {
- return (
- <>
- <ChatHeader />
- <Flexbox
- height={'100%'}
- horizontal
- style={{ overflow: 'hidden', position: 'relative' }}
- width={'100%'}
- >
- <Flexbox
- height={'100%'}
- style={{ overflow: 'hidden', position: 'relative' }}
- width={'100%'}
- >
- {conversation}
- </Flexbox>
- {children}
- <Portal>
- <Suspense fallback={<BrandTextLoading />}>{portal}</Suspense>
- </Portal>
- <TopicPanel>{topic}</TopicPanel>
- </Flexbox>
- <MainInterfaceTracker />
- </>
- );
-};
-
-Layout.displayName = 'DesktopConversationLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/chat/components/layout/Mobile/index.tsx b/src/app/[variants]/(main)/chat/components/layout/Mobile/index.tsx
deleted file mode 100644
index 3ea84832a92..00000000000
--- a/src/app/[variants]/(main)/chat/components/layout/Mobile/index.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import MainInterfaceTracker from '@/components/Analytics/MainInterfaceTracker';
-import MobileContentLayout from '@/components/server/MobileNavLayout';
-
-import { LayoutProps } from '../type';
-import ChatHeader from './ChatHeader';
-import TopicModal from './TopicModal';
-
-const Layout = ({ children, topic, conversation, portal }: LayoutProps) => {
- return (
- <>
- <MobileContentLayout header={<ChatHeader />} style={{ overflowY: 'hidden' }}>
- {conversation}
- {children}
- </MobileContentLayout>
- <TopicModal>{topic}</TopicModal>
- {portal}
- <MainInterfaceTracker />
- </>
- );
-};
-
-Layout.displayName = 'MobileConversationLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/chat/components/layout/type.ts b/src/app/[variants]/(main)/chat/components/layout/type.ts
deleted file mode 100644
index 640fd305284..00000000000
--- a/src/app/[variants]/(main)/chat/components/layout/type.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { ReactNode } from 'react';
-
-export interface LayoutProps {
- children: ReactNode;
- conversation: ReactNode;
- portal: ReactNode;
- topic: ReactNode;
-}
diff --git a/src/app/[variants]/(main)/chat/components/portal/default.tsx b/src/app/[variants]/(main)/chat/components/portal/default.tsx
deleted file mode 100644
index 2fbfcb925fb..00000000000
--- a/src/app/[variants]/(main)/chat/components/portal/default.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import React, { Suspense, lazy } from 'react';
-
-import Loading from '@/components/Loading/BrandTextLoading';
-import { DynamicLayoutProps } from '@/types/next';
-import { RouteVariants } from '@/utils/server/routeVariants';
-
-import Desktop from './_layout/Desktop';
-import Mobile from './_layout/Mobile';
-
-const PortalBody = lazy(() => import('@/features/Portal/router'));
-
-const Inspector = async (props: DynamicLayoutProps) => {
- const isMobile = await RouteVariants.getIsMobile(props);
-
- const Layout = isMobile ? Mobile : Desktop;
-
- return (
- <Suspense fallback={<Loading />}>
- <Layout>
- <PortalBody />
- </Layout>
- </Suspense>
- );
-};
-
-Inspector.displayName = 'ChatInspector';
-
-export default Inspector;
diff --git a/src/app/[variants]/(main)/chat/components/topic/_layout/Desktop.tsx b/src/app/[variants]/(main)/chat/components/topic/_layout/Desktop.tsx
deleted file mode 100644
index f7e86b94ffe..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/_layout/Desktop.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import { PropsWithChildren } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-const Layout = ({ children }: PropsWithChildren) => {
- return (
- <Flexbox height={'100%'} style={{ overflow: 'hidden', position: 'relative' }} width={'100%'}>
- {children}
- </Flexbox>
- );
-};
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/chat/components/topic/_layout/Mobile.tsx b/src/app/[variants]/(main)/chat/components/topic/_layout/Mobile.tsx
deleted file mode 100644
index a5527e35030..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/_layout/Mobile.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { PropsWithChildren } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import TopicSearchBar from '../features/Topic/TopicSearchBar';
-
-const Layout = ({ children }: PropsWithChildren) => {
- return (
- <Flexbox gap={8} height={'100%'} padding={'8px 8px 0'} style={{ overflow: 'hidden' }}>
- <TopicSearchBar />
- <Flexbox
- height={'100%'}
- style={{ marginInline: -8, overflow: 'hidden', position: 'relative' }}
- width={'calc(100% + 16px)'}
- >
- {children}
- </Flexbox>
- </Flexbox>
- );
-};
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/chat/components/topic/default.tsx b/src/app/[variants]/(main)/chat/components/topic/default.tsx
deleted file mode 100644
index 53e137826db..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/default.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import dynamic from 'next/dynamic';
-import React from 'react';
-
-import { DynamicLayoutProps } from '@/types/next';
-import { RouteVariants } from '@/utils/server/routeVariants';
-
-import Desktop from './_layout/Desktop';
-import Mobile from './_layout/Mobile';
-import SkeletonList from './features/SkeletonList';
-import Topic from './features/Topic';
-
-const ConfigSwitcher = dynamic(() => import('./features/ConfigSwitcher'), {
- loading: () => <SkeletonList />,
-});
-
-const Sidebar = async (props: DynamicLayoutProps) => {
- const isMobile = await RouteVariants.getIsMobile(props);
-
- const Layout = isMobile ? Mobile : Desktop;
-
- return (
- <Layout>
- <ConfigSwitcher />
- <Topic />
- </Layout>
- );
-};
-
-Sidebar.displayName = 'ChatTopic';
-
-export default Sidebar;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/ConfigSwitcher.tsx b/src/app/[variants]/(main)/chat/components/topic/features/ConfigSwitcher.tsx
deleted file mode 100644
index 821e4eaa939..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/ConfigSwitcher.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-'use client';
-
-import { memo } from 'react';
-
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-
-import AgentConfig from './AgentConfig';
-import GroupConfig from './GroupConfig';
-
-const ConfigSwitcher = memo(() => {
- const { isAgentEditable: showSystemRole } = useServerConfigStore(featureFlagsSelectors);
- const isInbox = useSessionStore(sessionSelectors.isInboxSession);
- const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);
-
- if (isInbox) return;
- if (isGroupSession) return <GroupConfig />;
- if (showSystemRole) return <AgentConfig />;
- return;
-});
-
-ConfigSwitcher.displayName = 'ConfigSwitcher';
-
-export default ConfigSwitcher;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupMember.tsx b/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupMember.tsx
deleted file mode 100644
index 76633b911dd..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupMember.tsx
+++ /dev/null
@@ -1,264 +0,0 @@
-'use client';
-
-import { ActionIcon, SortableList } from '@lobehub/ui';
-import { Settings, UserMinus } from 'lucide-react';
-import { memo, useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { MemberSelectionModal } from '@/components/MemberSelectionModal';
-import { DEFAULT_AVATAR, DEFAULT_SUPERVISOR_AVATAR } from '@/const/meta';
-import { useChatStore } from '@/store/chat';
-import { chatSelectors } from '@/store/chat/selectors';
-import { useChatGroupStore } from '@/store/chatGroup';
-import { chatGroupSelectors } from '@/store/chatGroup/selectors';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-import { LobeGroupSession } from '@/types/session';
-
-import AgentSettings from '../../../features/AgentSettings';
-import GroupMemberItem from './GroupMemberItem';
-
-interface GroupMemberProps {
- addModalOpen: boolean;
- currentSession?: LobeGroupSession;
- onAddModalOpenChange: (open: boolean) => void;
- sessionId?: string;
-}
-
-/**
- * Group member info in Sidebar
- */
-const GroupMember = memo<GroupMemberProps>(
- ({ currentSession, addModalOpen, onAddModalOpenChange, sessionId }) => {
- const { t } = useTranslation('chat');
-
- const addAgentsToGroup = useChatGroupStore((s) => s.addAgentsToGroup);
- const removeAgentFromGroup = useChatGroupStore((s) => s.removeAgentFromGroup);
- const persistReorder = useChatGroupStore((s) => s.reorderGroupMembers);
- const toggleThread = useChatGroupStore((s) => s.toggleThread);
- const updateGroupConfig = useChatGroupStore((s) => s.updateGroupConfig);
- const togglePortal = useChatStore((s) => s.togglePortal);
- const cancelSupervisorDecision = useChatStore((s) => s.internal_cancelSupervisorDecision);
- const triggerSupervisorDecision = useChatStore((s) => s.internal_triggerSupervisorDecision);
-
- const isSupervisorLoading = useChatStore(chatSelectors.isSupervisorLoading(sessionId || ''));
- const groupConfig = useChatGroupStore(chatGroupSelectors.getGroupConfig(sessionId || ''));
-
- const currentUser = useUserStore((s) => ({
- avatar: userProfileSelectors.userAvatar(s),
- name: userProfileSelectors.nickName(s),
- }));
-
- const [agentSettingsOpen, setAgentSettingsOpen] = useState(false);
- const [selectedAgentId, setSelectedAgentId] = useState<string | undefined>();
-
- const handleAddMembers = async (
- selectedAgents: string[],
- hostConfig?: { model?: string; provider?: string },
- enableSupervisor?: boolean,
- ) => {
- if (!sessionId) {
- console.error('No active group to add members to');
- return;
- }
-
- // Update host config if changed
- if (hostConfig !== undefined || enableSupervisor !== undefined) {
- const newConfig: any = {};
-
- if (enableSupervisor !== undefined) {
- newConfig.enableSupervisor = enableSupervisor;
- }
-
- if (hostConfig) {
- newConfig.orchestratorModel = hostConfig.model;
- newConfig.orchestratorProvider = hostConfig.provider;
- }
-
- if (Object.keys(newConfig).length > 0) {
- await updateGroupConfig(newConfig);
- }
- }
-
- // Add selected agents
- if (selectedAgents.length > 0) {
- await addAgentsToGroup(sessionId, selectedAgents);
- }
-
- onAddModalOpenChange(false);
- };
-
- // TODO: fix type
- // @ts-ignore
- const initialMembers = useMemo(() => currentSession?.members ?? [], [currentSession?.members]);
- const [members, setMembers] = useState<any[]>(initialMembers);
-
- const [removingMemberIds, setRemovingMemberIds] = useState<string[]>([]);
-
- const withRemovingFlag = async (id: string, task: () => Promise<void>) => {
- setRemovingMemberIds((prev) => (prev.includes(id) ? prev : [...prev, id]));
- try {
- await task();
- } finally {
- setRemovingMemberIds((prev) => prev.filter((memberId) => memberId !== id));
- }
- };
-
- useEffect(() => {
- setMembers(initialMembers);
- }, [initialMembers]);
-
- const handleRemoveMember = async (memberId: string) => {
- if (!sessionId) return;
-
- await withRemovingFlag(memberId, () => removeAgentFromGroup(sessionId, memberId));
- };
-
- const handleMemberClick = (agentId: string) => {
- toggleThread(agentId);
- togglePortal(true);
- };
-
- const handleOpenMemberSettings = (agentId: string) => {
- setSelectedAgentId(agentId);
- setAgentSettingsOpen(true);
- };
-
- const handleAgentSettingsClose = () => {
- setAgentSettingsOpen(false);
- setSelectedAgentId(undefined);
- };
-
- const handleStopSupervisor = () => {
- if (!sessionId) return;
- cancelSupervisorDecision(sessionId);
- };
-
- const handleTriggerSupervisor = () => {
- if (!sessionId) return;
- // Manual trigger: topicId stays current (undefined), flag manual=true
- triggerSupervisorDecision(sessionId, undefined, true);
- };
-
- return (
- <>
- <Flexbox gap={2} padding={6}>
- {/* Supervisor - only show if supervisor is enabled */}
- {groupConfig?.enableSupervisor && (
- <GroupMemberItem
- actions={
- <ActionIcon
- danger
- icon={UserMinus}
- loading={removingMemberIds.includes('orchestrator')}
- onClick={(e) => {
- e.stopPropagation();
- void withRemovingFlag('orchestrator', () =>
- updateGroupConfig({ enableSupervisor: false }),
- );
- }}
- size={'small'}
- title={t('groupSidebar.members.removeMember')}
- />
- }
- avatar={DEFAULT_SUPERVISOR_AVATAR}
- generating={isSupervisorLoading}
- generatingTooltip={t('groupSidebar.members.orchestratorThinking')}
- id={'orchestrator'}
- onStopGenerating={handleStopSupervisor}
- onStopGeneratingTooltip={t('groupSidebar.members.stopOrchestrator')}
- onTriggerSupervisor={handleTriggerSupervisor}
- onTriggerSupervisorTooltip={t('groupSidebar.members.triggerOrchestrator')}
- pin
- showActionsOnHover={true}
- title={t('groupSidebar.members.orchestrator')}
- />
- )}
-
- {/* Current User */}
- <GroupMemberItem
- avatar={currentUser.avatar}
- id={'currentUser'}
- pin
- showActionsOnHover={false}
- title={currentUser.name || ''}
- />
-
- {Boolean(members && members.length > 0) && (
- <SortableList
- gap={2}
- items={members}
- onChange={async (items: any[]) => {
- setMembers(items);
- if (!sessionId) return;
- const orderedIds = items.map((m) => m.id);
- persistReorder(sessionId, orderedIds).catch(() => {
- console.error('Failed to persist reorder');
- });
- }}
- renderItem={(item: any) => (
- <GroupMemberItem
- actions={
- <>
- <ActionIcon
- icon={Settings}
- onClick={(e) => {
- e.stopPropagation();
- handleOpenMemberSettings(item.id);
- }}
- size={'small'}
- title={t('groupSidebar.members.memberSettings')}
- />
- <ActionIcon
- danger
- icon={UserMinus}
- loading={removingMemberIds.includes(item.id)}
- onClick={(e) => {
- e.stopPropagation();
- handleRemoveMember(item.id);
- }}
- size={'small'}
- title={t('groupSidebar.members.removeMember')}
- />
- </>
- }
- avatar={item.avatar || DEFAULT_AVATAR}
- background={item.backgroundColor}
- id={item.id}
- onClick={() => handleMemberClick(item.id)}
- title={item.title || t('defaultSession', { ns: 'common' })}
- />
- )}
- style={{ margin: 0 }}
- />
- )}
- </Flexbox>
-
- <MemberSelectionModal
- currentHostConfig={{
- enableSupervisor: groupConfig?.enableSupervisor,
- orchestratorModel: groupConfig?.orchestratorModel,
- orchestratorProvider: groupConfig?.orchestratorProvider,
- }}
- // @ts-ignore
- // TODO: fix type
- existingMembers={currentSession?.members?.map((member: any) => member.id) || []}
- groupId={sessionId}
- mode="add"
- onCancel={() => onAddModalOpenChange(false)}
- onConfirm={handleAddMembers}
- open={addModalOpen}
- />
-
- <AgentSettings
- agentId={selectedAgentId}
- onClose={handleAgentSettingsClose}
- open={agentSettingsOpen}
- />
- </>
- );
- },
-);
-
-export default GroupMember;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupMemberItem.tsx b/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupMemberItem.tsx
deleted file mode 100644
index cecbfc3df08..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupMemberItem.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-'use client';
-
-import { ActionIcon, Avatar, SortableList, Text } from '@lobehub/ui';
-import { LoaderCircle, PinIcon, Play, StopCircle } from 'lucide-react';
-import { ReactNode, memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { DEFAULT_AVATAR } from '@/const/meta';
-
-import { useStyles } from './style';
-
-interface GroupMemberItemProps {
- actions?: ReactNode;
- avatar?: string;
- background?: string;
- generating?: boolean;
- generatingTooltip?: string;
- id: string;
- onClick?: () => void;
- onStopGenerating?: () => void;
- onStopGeneratingTooltip?: string;
- onTriggerSupervisor?: () => void;
- onTriggerSupervisorTooltip?: string;
- pin?: boolean;
- showActionsOnHover?: boolean;
- title: string;
-}
-
-const GroupMemberItem = memo<GroupMemberItemProps>(
- ({
- id,
- title,
- avatar,
- background,
- onClick,
- actions,
- showActionsOnHover = true,
- pin,
- generating,
- generatingTooltip,
- onStopGenerating,
- onStopGeneratingTooltip,
- onTriggerSupervisor,
- onTriggerSupervisorTooltip,
- }) => {
- const { styles } = useStyles();
-
- return (
- <SortableList.Item className={styles.memberItem} id={id} justify={'space-between'}>
- <Flexbox
- align={'center'}
- flex={1}
- gap={4}
- horizontal
- onClick={(e) => {
- e.stopPropagation();
- onClick?.();
- }}
- style={{ overflow: 'hidden' }}
- >
- {pin ? (
- <SortableList.DragHandle
- disabled
- icon={PinIcon}
- style={{
- cursor: 'not-allowed',
- }}
- />
- ) : (
- <SortableList.DragHandle />
- )}
- <Flexbox flex={1} gap={8} horizontal style={{ overflow: 'hidden' }}>
- <Avatar
- avatar={avatar || DEFAULT_AVATAR}
- background={background}
- size={24}
- style={{ flex: 'none' }}
- />
- <Text ellipsis>{title}</Text>
- </Flexbox>
- </Flexbox>
- {actions !== undefined && (
- <Flexbox className={showActionsOnHover ? 'show-on-hover' : undefined} gap={4} horizontal>
- {actions}
- </Flexbox>
- )}
- {generating ? (
- <Flexbox gap={4} horizontal>
- <ActionIcon icon={LoaderCircle} size={'small'} spin title={generatingTooltip} />
- {onStopGenerating && (
- <ActionIcon
- icon={StopCircle}
- onClick={(e) => {
- e.stopPropagation();
- onStopGenerating();
- }}
- size={'small'}
- title={onStopGeneratingTooltip || 'Stop generating'}
- />
- )}
- </Flexbox>
- ) : (
- onTriggerSupervisor && (
- <ActionIcon
- className="show-on-hover"
- icon={Play}
- onClick={(e) => {
- e.stopPropagation();
- onTriggerSupervisor();
- }}
- size={'small'}
- title={onTriggerSupervisorTooltip || 'Trigger supervisor decision'}
- />
- )
- )}
- </SortableList.Item>
- );
- },
-);
-
-export default GroupMemberItem;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/index.tsx b/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/index.tsx
deleted file mode 100644
index 6b9ab30b22c..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/index.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-'use client';
-
-import { ActionIcon, Tabs } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
-import { Edit, UserPlus } from 'lucide-react';
-import { MouseEvent, memo, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useChatGroupStore } from '@/store/chatGroup';
-import { chatGroupSelectors } from '@/store/chatGroup/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/slices/session/selectors';
-import type { LobeGroupSession } from '@/types/session';
-
-import ConfigLayout from '../ConfigLayout';
-import GroupMember from './GroupMember';
-import GroupRole from './GroupRole';
-
-const GroupChatSidebar = memo(() => {
- const [addModalOpen, setAddModalOpen] = useState(false);
- const [editorModalOpen, setEditorModalOpen] = useState(false);
- const [editing, setEditing] = useState(false);
- const [activeTab, setActiveTab] = useState('members');
- const { t } = useTranslation(['chat', 'common']);
-
- const [sessionId] = useSessionStore((s) => [s.activeId]);
- const currentSession = useSessionStore((state) => {
- const session = sessionSelectors.currentSession(state);
- return session?.type === 'group' ? (session as LobeGroupSession) : undefined;
- }, isEqual);
-
- const groupConfig = useChatGroupStore(chatGroupSelectors.getGroupConfig(sessionId || ''));
-
- // Switch to members tab if host tab becomes unavailable
- useEffect(() => {
- if (activeTab === 'host' && !groupConfig?.enableSupervisor) {
- setActiveTab('members');
- }
- }, [activeTab, groupConfig?.enableSupervisor]);
-
- const handleAddMember = (e: MouseEvent) => {
- e.stopPropagation();
- setAddModalOpen(true);
- };
-
- const handleOpenWithEdit = (e: MouseEvent) => {
- e.stopPropagation();
- setEditing(true);
- setEditorModalOpen(true);
- };
-
- const actions =
- activeTab === 'members' ? (
- <ActionIcon
- icon={UserPlus}
- onClick={handleAddMember}
- size={'small'}
- title={t('groupSidebar.members.addMember')}
- />
- ) : activeTab === 'host' ? (
- <ActionIcon
- icon={Edit}
- onClick={handleOpenWithEdit}
- size={'small'}
- title={t('edit', { ns: 'common' })}
- />
- ) : undefined;
-
- return (
- <ConfigLayout
- actions={actions}
- expandedHeight={activeTab === 'members' ? '40vh' : 200}
- headerStyle={{ paddingBlock: 0, paddingLeft: 0 }}
- sessionId={sessionId}
- title={
- <Tabs
- activeKey={activeTab}
- compact
- items={[
- {
- key: 'members',
- label: t('groupSidebar.tabs.members'),
- },
- // Only show host tab if supervisor is enabled
- ...(groupConfig?.enableSupervisor
- ? [
- {
- key: 'host',
- label: t('groupSidebar.tabs.host'),
- },
- ]
- : []),
- ]}
- onChange={(key) => setActiveTab(key)}
- onClick={(e) => {
- e.stopPropagation();
- }}
- size="small"
- variant="rounded"
- />
- }
- >
- {activeTab === 'members' && (
- <GroupMember
- addModalOpen={addModalOpen}
- currentSession={currentSession}
- onAddModalOpenChange={setAddModalOpen}
- sessionId={sessionId}
- />
- )}
- {activeTab === 'host' && (
- <GroupRole
- currentSession={currentSession}
- editing={editing}
- editorModalOpen={editorModalOpen}
- setEditing={setEditing}
- setEditorModalOpen={setEditorModalOpen}
- />
- )}
- </ConfigLayout>
- );
-});
-
-export default GroupChatSidebar;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/SkeletonList.tsx b/src/app/[variants]/(main)/chat/components/topic/features/SkeletonList.tsx
deleted file mode 100644
index b7e701e150f..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/SkeletonList.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-'use client';
-
-import { Skeleton } from 'antd';
-import { createStyles } from 'antd-style';
-import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-const useStyles = createStyles(({ css, prefixCls }) => ({
- container: css`
- display: flex;
- flex-direction: column;
- justify-content: center;
-
- height: 44px;
- padding-block: 8px;
- padding-inline: 12px;
-
- .${prefixCls}-skeleton-content {
- display: flex;
- flex-direction: column;
- }
- `,
-
- paragraph: css`
- > li {
- height: 20px !important;
- }
- `,
-}));
-
-export const Placeholder = memo(() => {
- const { styles } = useStyles();
-
- return (
- <Skeleton
- active
- avatar={false}
- className={styles.container}
- paragraph={{
- className: styles.paragraph,
- rows: 1,
- style: { marginBottom: 0 },
- width: '100%',
- }}
- title={false}
- />
- );
-});
-
-export const SkeletonList = memo(() => (
- <Flexbox style={{ paddingTop: 6 }}>
- {Array.from({ length: 4 }).map((_, i) => (
- <Placeholder key={i} />
- ))}
- </Flexbox>
-));
-
-export default SkeletonList;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/Header.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/Header.tsx
deleted file mode 100644
index fd983f4dade..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/Header.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-'use client';
-
-import { ActionIcon, Dropdown, Icon, type MenuProps } from '@lobehub/ui';
-import { App } from 'antd';
-import type { ItemType } from 'antd/es/menu/interface';
-import { LucideCheck, MoreHorizontal, Search, Trash } from 'lucide-react';
-import { memo, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import SidebarHeader from '@/components/SidebarHeader';
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors } from '@/store/user/selectors';
-import { TopicDisplayMode } from '@/types/topic';
-
-import TopicSearchBar from './TopicSearchBar';
-
-const Header = memo(() => {
- const { t } = useTranslation(['topic', 'common']);
- const [topicLength, removeUnstarredTopic, removeAllTopic] = useChatStore((s) => [
- topicSelectors.currentTopicLength(s),
- s.removeUnstarredTopic,
- s.removeSessionTopics,
- ]);
- const [topicDisplayMode, updatePreference] = useUserStore((s) => [
- preferenceSelectors.topicDisplayMode(s),
- s.updatePreference,
- ]);
- const [showSearch, setShowSearch] = useState(false);
- const { modal } = App.useApp();
-
- const items = useMemo<MenuProps['items']>(
- () => [
- ...(Object.values(TopicDisplayMode).map((mode) => ({
- icon: topicDisplayMode === mode ? <Icon icon={LucideCheck} /> : <div />,
- key: mode,
- label: t(`groupMode.${mode}`),
- onClick: () => {
- updatePreference({ topicDisplayMode: mode });
- },
- })) as ItemType[]),
- {
- type: 'divider',
- },
- {
- icon: <Icon icon={Trash} />,
- key: 'deleteUnstarred',
- label: t('actions.removeUnstarred'),
- onClick: () => {
- modal.confirm({
- cancelText: t('cancel', { ns: 'common' }),
- centered: true,
- okButtonProps: { danger: true },
- okText: t('ok', { ns: 'common' }),
- onOk: removeUnstarredTopic,
- title: t('actions.confirmRemoveUnstarred'),
- });
- },
- },
- {
- danger: true,
- icon: <Icon icon={Trash} />,
- key: 'deleteAll',
- label: t('actions.removeAll'),
- onClick: () => {
- modal.confirm({
- cancelText: t('cancel', { ns: 'common' }),
- centered: true,
- okButtonProps: { danger: true },
- okText: t('ok', { ns: 'common' }),
- onOk: removeAllTopic,
- title: t('actions.confirmRemoveAll'),
- });
- },
- },
- ],
- [topicDisplayMode],
- );
-
- return showSearch ? (
- <Flexbox padding={'12px 16px 4px'}>
- <TopicSearchBar onClear={() => setShowSearch(false)} />
- </Flexbox>
- ) : (
- <SidebarHeader
- actions={
- <>
- <ActionIcon icon={Search} onClick={() => setShowSearch(true)} size={'small'} />
- <Dropdown
- arrow={false}
- menu={{
- items: items,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- },
- }}
- trigger={['click']}
- >
- <ActionIcon icon={MoreHorizontal} size={'small'} />
- </Dropdown>
- </>
- }
- title={`${t('title')} ${topicLength > 1 ? topicLength + 1 : ''}`}
- />
- );
-});
-
-export default Header;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ByTimeMode/GroupItem.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
deleted file mode 100644
index 8f846615762..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { createStyles } from 'antd-style';
-import dayjs from 'dayjs';
-import React, { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { GroupedTopic } from '@/types/topic';
-
-const preformat = (id: string) =>
- id.startsWith('20') ? (id.includes('-') ? dayjs(id).format('MMMM') : id) : undefined;
-
-const useStyles = createStyles(({ css, token, responsive }) => ({
- container: css`
- color: ${token.colorTextQuaternary};
- background: ${token.colorBgContainerSecondary};
- box-shadow: 0 3px 4px -2px ${token.colorBgContainerSecondary};
-
- ${responsive.mobile} {
- background: ${token.colorBgContainer};
- box-shadow: 0 3px 4px -2px ${token.colorBgContainer};
- }
- `,
-}));
-
-const TopicGroupItem = memo<Omit<GroupedTopic, 'children'>>(({ id, title }) => {
- const { t } = useTranslation('topic');
- const { styles } = useStyles();
- const timeTitle = preformat(id) ?? t(`groupTitle.byTime.${id}` as any);
-
- return (
- <Flexbox className={styles.container} paddingBlock={'12px 8px'} paddingInline={12}>
- {title ? title : timeTitle}
- </Flexbox>
- );
-});
-export default TopicGroupItem;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ByTimeMode/index.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ByTimeMode/index.tsx
deleted file mode 100644
index 54ee53e0167..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ByTimeMode/index.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-'use client';
-
-import isEqual from 'fast-deep-equal';
-import React, { memo, useCallback, useMemo, useRef } from 'react';
-import { useTranslation } from 'react-i18next';
-import { GroupedVirtuoso, VirtuosoHandle } from 'react-virtuoso';
-
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
-import { ChatTopic } from '@/types/topic';
-
-import TopicItem from '../TopicItem';
-import TopicGroupItem from './GroupItem';
-
-const ByTimeMode = memo(() => {
- const { t } = useTranslation('topic');
- const virtuosoRef = useRef<VirtuosoHandle>(null);
- const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);
- const groupTopics = useChatStore(topicSelectors.groupedTopicsSelector, isEqual);
-
- const { groups, groupCounts, topics } = useMemo(() => {
- return {
- groupCounts: [1, ...groupTopics.map((group) => group.children.length)],
- groups: [
- { id: 'default' },
- ...groupTopics.map((group) => ({ id: group.id, title: group.title })),
- ],
- topics: [
- { favorite: false, id: 'default', title: t('defaultTitle') } as ChatTopic,
- ...groupTopics.flatMap((group) => group.children),
- ],
- };
- }, [groupTopics]);
-
- const itemContent = useCallback(
- (index: number) => {
- const { id, favorite, title } = topics[index];
-
- return index === 0 ? (
- <TopicItem active={!activeTopicId} fav={favorite} title={title} />
- ) : (
- <TopicItem
- active={activeTopicId === id}
- fav={favorite}
- id={id}
- key={id}
- threadId={activeThreadId}
- title={title}
- />
- );
- },
- [activeTopicId, topics, activeThreadId],
- );
-
- const groupContent = useCallback(
- (index: number) => {
- if (index === 0) return <div style={{ height: 1 }} />;
- const topicGroup = groups[index];
- return <TopicGroupItem {...topicGroup} />;
- },
- [groups],
- );
-
- return (
- <GroupedVirtuoso
- groupContent={groupContent}
- groupCounts={groupCounts}
- itemContent={itemContent}
- ref={virtuosoRef}
- style={{
- minHeight: groupCounts.length === 1 ? '0px' : '200px',
- }}
- />
- );
-});
-
-ByTimeMode.displayName = 'ByTimeMode';
-
-export default ByTimeMode;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/FlatMode/index.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/FlatMode/index.tsx
deleted file mode 100644
index fc932d0319e..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/FlatMode/index.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-'use client';
-
-import isEqual from 'fast-deep-equal';
-import React, { memo, useCallback, useMemo, useRef } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
-
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
-import { ChatTopic } from '@/types/topic';
-
-import TopicItem from '../TopicItem';
-
-const FlatMode = memo(() => {
- const { t } = useTranslation('topic');
- const virtuosoRef = useRef<VirtuosoHandle>(null);
- const [activeTopicId] = useChatStore((s) => [s.activeTopicId]);
- const activeTopicList = useChatStore(topicSelectors.displayTopics, isEqual);
-
- const topics = useMemo(
- () => [
- { favorite: false, id: 'default', title: t('defaultTitle') } as ChatTopic,
- ...(activeTopicList || []),
- ],
- [activeTopicList],
- );
-
- const itemContent = useCallback(
- (index: number, { id, favorite, title }: ChatTopic) =>
- index === 0 ? (
- <TopicItem active={!activeTopicId} fav={favorite} title={title} />
- ) : (
- <TopicItem active={activeTopicId === id} fav={favorite} id={id} key={id} title={title} />
- ),
- [activeTopicId],
- );
-
- const activeIndex = topics.findIndex((topic) => topic.id === activeTopicId);
-
- return (
- <Virtuoso
- // components={{ ScrollSeekPlaceholder: Placeholder }}
- computeItemKey={(_, item) => item.id}
- data={topics}
- defaultItemHeight={44}
- initialTopMostItemIndex={Math.max(activeIndex, 0)}
- itemContent={itemContent}
- overscan={44 * 10}
- ref={virtuosoRef}
- // scrollSeekConfiguration={{
- // enter: (velocity) => Math.abs(velocity) > 350,
- // exit: (velocity) => Math.abs(velocity) < 10,
- // }}
- />
- );
-});
-
-FlatMode.displayName = 'FlatMode';
-
-export default FlatMode;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadItem/Content.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadItem/Content.tsx
deleted file mode 100644
index 8dddae1ab8d..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadItem/Content.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import { ActionIcon, Dropdown, EditableText, Icon, type MenuProps, Text } from '@lobehub/ui';
-import { App } from 'antd';
-import { createStyles } from 'antd-style';
-import { MoreVertical, PencilLine, Trash } from 'lucide-react';
-import { memo, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import BubblesLoading from '@/components/BubblesLoading';
-import { LOADING_FLAT } from '@/const/message';
-import { useIsMobile } from '@/hooks/useIsMobile';
-import { useChatStore } from '@/store/chat';
-
-const useStyles = createStyles(({ css, token }) => ({
- active: css`
- color: ${token.colorText};
- `,
- content: css`
- position: relative;
- overflow: hidden;
- flex: 1;
- `,
- title: css`
- flex: 1;
-
- height: 28px;
-
- line-height: 28px;
- color: ${token.colorTextSecondary};
- text-align: start;
- `,
-}));
-
-interface TopicContentProps {
- active?: boolean;
- id: string;
- showMore?: boolean;
- title: string;
-}
-
-const Content = memo<TopicContentProps>(({ id, title, active, showMore }) => {
- const { t } = useTranslation(['thread', 'common']);
-
- const mobile = useIsMobile();
-
- const [editing, updateThreadTitle, removeThread] = useChatStore((s) => [
- s.threadRenamingId === id,
- s.updateThreadTitle,
- s.removeThread,
- ]);
- const { styles, cx } = useStyles();
-
- const toggleEditing = (visible?: boolean) => {
- useChatStore.setState({ threadRenamingId: visible ? id : '' });
- };
-
- const { modal } = App.useApp();
-
- const items = useMemo<MenuProps['items']>(
- () => [
- {
- icon: <Icon icon={PencilLine} />,
- key: 'rename',
- label: t('rename', { ns: 'common' }),
- onClick: () => {
- toggleEditing(true);
- },
- },
- {
- type: 'divider',
- },
- {
- danger: true,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: () => {
- if (!id) return;
-
- modal.confirm({
- centered: true,
- okButtonProps: { danger: true },
- onOk: async () => {
- await removeThread(id);
- },
- title: t('actions.confirmRemoveThread'),
- });
- },
- },
- ],
- [],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={8}
- horizontal
- justify={'space-between'}
- onDoubleClick={(e) => {
- if (!id) return;
- if (e.altKey) toggleEditing(true);
- }}
- >
- {!editing ? (
- title === LOADING_FLAT ? (
- <Flexbox flex={1} height={28} justify={'center'}>
- <BubblesLoading />
- </Flexbox>
- ) : (
- <Text
- as={'p'}
- className={cx(styles.title, active && styles.active)}
- ellipsis={{ rows: 1, tooltip: { placement: 'left', title } }}
- style={{ margin: 0 }}
- >
- {title}
- </Text>
- )
- ) : (
- <EditableText
- editing={editing}
- onChangeEnd={(v) => {
- if (title !== v) {
- updateThreadTitle(id, v);
- }
- toggleEditing(false);
- }}
- onEditingChange={toggleEditing}
- showEditIcon={false}
- style={{ height: 28 }}
- value={title}
- />
- )}
- {(showMore || mobile) && !editing && (
- <Dropdown
- arrow={false}
- menu={{
- items: items,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- },
- }}
- trigger={['click']}
- >
- <ActionIcon
- className="topic-more"
- icon={MoreVertical}
- onClick={(e) => {
- e.stopPropagation();
- }}
- size={'small'}
- />
- </Dropdown>
- )}
- </Flexbox>
- );
-});
-
-export default Content;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadItem/index.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadItem/index.tsx
deleted file mode 100644
index 8c144580bcd..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/ThreadItem/index.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import { createStyles } from 'antd-style';
-import { memo, useState } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { useChatStore } from '@/store/chat';
-import { useGlobalStore } from '@/store/global';
-
-import Content from './Content';
-
-const useStyles = createStyles(({ css, token, isDarkMode }, index: number) => ({
- active: css`
- background: ${isDarkMode ? token.colorFillSecondary : token.colorFillTertiary};
- transition: background 200ms ${token.motionEaseOut};
-
- &:hover {
- background: ${token.colorFill};
- }
- `,
- container: css`
- margin-inline: 8px;
-
- &::after {
- content: '';
-
- position: absolute;
- inset-block: 50px ${index * 40 + 20}px;
- inset-inline-start: 26px;
-
- width: 18px;
- border-block-end: 2px solid ${token.colorBorderSecondary};
- border-inline-start: 2px solid ${token.colorBorderSecondary};
- border-end-start-radius: 8px;
- }
-
- &.thread-item {
- width: calc(100% - 16px);
- }
- `,
- split: css`
- border-block-end: 1px solid ${token.colorSplit};
- `,
- wrapper: css`
- cursor: pointer;
-
- width: calc(100% - 36px);
- margin-block: 2px;
- padding-block: 4px;
- padding-inline: 8px;
- border-radius: ${token.borderRadius}px;
-
- &:hover {
- background: ${token.colorFillSecondary};
- }
- `,
-}));
-
-export interface ThreadItemProps {
- id: string;
- index: number;
- title: string;
-}
-
-const ThreadItem = memo<ThreadItemProps>(({ title, id, index }) => {
- const { styles, cx } = useStyles(index);
- const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
- const [toggleThread, activeThreadId] = useChatStore((s) => [s.switchThread, s.activeThreadId]);
- const [isHover, setHovering] = useState(false);
-
- const active = id === activeThreadId;
- return (
- <Flexbox className={cx(styles.container, 'thread-item')} horizontal>
- <Flexbox height={36} width={36} />
- <Flexbox
- align={'center'}
- className={cx(styles.wrapper, active && styles.active)}
- distribution={'space-between'}
- flex={1}
- horizontal
- onClick={() => {
- toggleThread(id);
- toggleConfig(false);
- }}
- onMouseEnter={() => {
- setHovering(true);
- }}
- onMouseLeave={() => {
- setHovering(false);
- }}
- >
- {<Content active={active} id={id} showMore={isHover} title={title} />}
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default ThreadItem;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/DefaultContent.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/DefaultContent.tsx
deleted file mode 100644
index b24dec3ce9e..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/DefaultContent.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { Icon, Tag, Text } from '@lobehub/ui';
-import { useTheme } from 'antd-style';
-import { MessageSquareDashed } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-const DefaultContent = memo(() => {
- const { t } = useTranslation('topic');
-
- const theme = useTheme();
-
- return (
- <Flexbox align={'center'} gap={8} horizontal>
- <Flexbox align={'center'} height={24} justify={'center'} width={24}>
- <Icon color={theme.colorTextDescription} icon={MessageSquareDashed} />
- </Flexbox>
- <Text ellipsis={{ rows: 1 }} style={{ margin: 0 }}>
- {t('defaultTitle')}
- </Text>
- <Tag>{t('temp')}</Tag>
- </Flexbox>
- );
-});
-
-export default DefaultContent;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/TopicContent.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/TopicContent.tsx
deleted file mode 100644
index be4f249a3fa..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/TopicContent.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-import { ActionIcon, Dropdown, EditableText, Icon, type MenuProps, Text } from '@lobehub/ui';
-import { App } from 'antd';
-import { createStyles } from 'antd-style';
-import {
- ExternalLink,
- LucideCopy,
- LucideLoader2,
- MoreVertical,
- PencilLine,
- Star,
- Trash,
- Wand2,
-} from 'lucide-react';
-import { memo, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import BubblesLoading from '@/components/BubblesLoading';
-import { LOADING_FLAT } from '@/const/message';
-import { isDesktop } from '@/const/version';
-import { useIsMobile } from '@/hooks/useIsMobile';
-import { useChatStore } from '@/store/chat';
-import { useGlobalStore } from '@/store/global';
-
-const useStyles = createStyles(({ css }) => ({
- content: css`
- position: relative;
- overflow: hidden;
- flex: 1;
- `,
- title: css`
- flex: 1;
- height: 28px;
- line-height: 28px;
- text-align: start;
- `,
-}));
-
-interface TopicContentProps {
- fav?: boolean;
- id: string;
- showMore?: boolean;
- title: string;
-}
-
-const TopicContent = memo<TopicContentProps>(({ id, title, fav, showMore }) => {
- const { t } = useTranslation(['topic', 'common']);
-
- const mobile = useIsMobile();
-
- const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
-
- const [
- editing,
- favoriteTopic,
- updateTopicTitle,
- removeTopic,
- autoRenameTopicTitle,
- duplicateTopic,
- isLoading,
- activeId,
- ] = useChatStore((s) => [
- s.topicRenamingId === id,
- s.favoriteTopic,
- s.updateTopicTitle,
- s.removeTopic,
- s.autoRenameTopicTitle,
- s.duplicateTopic,
- s.topicLoadingIds.includes(id),
- s.activeId,
- ]);
- const { styles, theme } = useStyles();
-
- const toggleEditing = (visible?: boolean) => {
- useChatStore.setState({ topicRenamingId: visible ? id : '' });
- };
-
- const { modal } = App.useApp();
-
- const items = useMemo<MenuProps['items']>(
- () => [
- {
- icon: <Icon icon={Wand2} />,
- key: 'autoRename',
- label: t('actions.autoRename'),
- onClick: () => {
- autoRenameTopicTitle(id);
- },
- },
- {
- icon: <Icon icon={PencilLine} />,
- key: 'rename',
- label: t('rename', { ns: 'common' }),
- onClick: () => {
- toggleEditing(true);
- },
- },
- ...(isDesktop
- ? [
- {
- icon: <Icon icon={ExternalLink} />,
- key: 'openInNewWindow',
- label: t('actions.openInNewWindow'),
- onClick: () => {
- openTopicInNewWindow(activeId, id);
- },
- },
- ]
- : []),
- {
- type: 'divider',
- },
- {
- icon: <Icon icon={LucideCopy} />,
- key: 'duplicate',
- label: t('actions.duplicate'),
- onClick: () => {
- duplicateTopic(id);
- },
- },
- // {
- // icon: <Icon icon={LucideDownload} />,
- // key: 'export',
- // label: t('topic.actions.export'),
- // onClick: () => {
- // configService.exportSingleTopic(sessionId, id);
- // },
- // },
- {
- type: 'divider',
- },
- // {
- // icon: <Icon icon={Share2} />,
- // key: 'share',
- // label: t('share'),
- // },
- {
- danger: true,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: () => {
- if (!id) return;
-
- modal.confirm({
- centered: true,
- okButtonProps: { danger: true },
- onOk: async () => {
- await removeTopic(id);
- },
- title: t('actions.confirmRemoveTopic'),
- });
- },
- },
- ],
- [
- id,
- activeId,
- autoRenameTopicTitle,
- duplicateTopic,
- removeTopic,
- t,
- toggleEditing,
- openTopicInNewWindow,
- ],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={8}
- horizontal
- justify={'space-between'}
- onDoubleClick={(e) => {
- if (!id) return;
- if (e.altKey) toggleEditing(true);
- }}
- >
- <ActionIcon
- color={fav && !isLoading ? theme.colorWarning : undefined}
- fill={fav && !isLoading ? theme.colorWarning : 'transparent'}
- icon={isLoading ? LucideLoader2 : Star}
- onClick={(e) => {
- e.stopPropagation();
- if (!id) return;
- favoriteTopic(id, !fav);
- }}
- size={'small'}
- spin={isLoading}
- />
- {!editing ? (
- title === LOADING_FLAT || (isLoading && !title) ? (
- <Flexbox flex={1} height={28} justify={'center'}>
- <BubblesLoading />
- </Flexbox>
- ) : (
- <Text
- className={styles.title}
- ellipsis={{ rows: 1, tooltip: { placement: 'left', title } }}
- onDoubleClick={() => {
- if (isDesktop) {
- openTopicInNewWindow(activeId, id);
- }
- }}
- style={{ margin: 0 }}
- >
- {title}
- </Text>
- )
- ) : (
- <EditableText
- editing={editing}
- onBlur={(e) => {
- const v = (e.target as HTMLInputElement).value;
- if (title !== v) {
- updateTopicTitle(id, v);
- }
- toggleEditing(false);
- }}
- onChangeEnd={(v) => {
- if (title !== v) {
- updateTopicTitle(id, v);
- }
- toggleEditing(false);
- }}
- onEditingChange={toggleEditing}
- showEditIcon={false}
- style={{ height: 28 }}
- value={title}
- />
- )}
- {(showMore || mobile) && !editing && (
- <Dropdown
- arrow={false}
- menu={{
- items: items,
- onClick: ({ domEvent }) => {
- domEvent.stopPropagation();
- },
- }}
- trigger={['click']}
- >
- <ActionIcon
- className="topic-more"
- icon={MoreVertical}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- size={'small'}
- />
- </Dropdown>
- )}
- </Flexbox>
- );
-});
-
-export default TopicContent;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/index.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/index.tsx
deleted file mode 100644
index a2f7267b60e..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/TopicItem/index.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { Skeleton } from 'antd';
-import { createStyles } from 'antd-style';
-import qs from 'query-string';
-import { Suspense, memo, useState } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import { useChatStore } from '@/store/chat';
-import { useGlobalStore } from '@/store/global';
-import { useSessionStore } from '@/store/session';
-
-import ThreadList from '../ThreadList';
-import DefaultContent from './DefaultContent';
-import TopicContent from './TopicContent';
-
-const useStyles = createStyles(({ css, token, isDarkMode }) => ({
- active: css`
- background: ${isDarkMode ? token.colorFillSecondary : token.colorFillTertiary};
- transition: background 200ms ${token.motionEaseOut};
-
- &:hover {
- background: ${token.colorFill};
- }
- `,
- container: css`
- cursor: pointer;
-
- margin-block: 2px;
- margin-inline: 8px;
- padding: 8px;
- border-radius: ${token.borderRadius}px;
-
- &.topic-item {
- width: calc(100% - 16px);
- }
-
- &:hover {
- background: ${token.colorFillSecondary};
- }
- `,
- split: css`
- border-block-end: 1px solid ${token.colorSplit};
- `,
-}));
-
-export interface ConfigCellProps {
- active?: boolean;
- fav?: boolean;
- id?: string;
- threadId?: string;
- title: string;
-}
-
-const TopicItem = memo<ConfigCellProps>(({ title, active, id, fav, threadId }) => {
- const { styles, cx } = useStyles();
- const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
- const [toggleTopic, editing] = useChatStore((s) => [
- s.switchTopic,
- s.topicRenamingId !== undefined && s.topicRenamingId === id,
- ]);
- const activeId = useSessionStore((s) => s.activeId);
- const [isHover, setHovering] = useState(false);
-
- return (
- <Flexbox style={{ position: 'relative' }}>
- <Flexbox
- align={'center'}
- className={cx(styles.container, 'topic-item', active && !threadId && styles.active)}
- distribution={'space-between'}
- horizontal
- onClick={(e) => {
- // Alt+Click should keep the current topic selection (reserved shortcut)
- if (e.altKey) return;
- // 重命名时不切换话题
- if (editing) return;
- // Ctrl/Cmd+点击在新窗口打开
- if (e.button === 0 && (e.metaKey || e.ctrlKey) && id) {
- const topicUrl = qs.stringifyUrl({
- query: { session: activeId, topic: id },
- url: '/chat',
- });
- window.open(topicUrl, '_blank');
- return;
- }
- toggleTopic(id);
- toggleConfig(false);
- }}
- onMouseEnter={() => {
- setHovering(true);
- }}
- onMouseLeave={() => {
- setHovering(false);
- }}
- >
- {!id ? (
- <DefaultContent />
- ) : (
- <TopicContent fav={fav} id={id} showMore={isHover} title={title} />
- )}
- </Flexbox>
- {active && (
- <Suspense
- fallback={
- <Flexbox gap={8} paddingBlock={8} paddingInline={24} width={'100%'}>
- <Skeleton.Button active size={'small'} style={{ height: 18, width: '100%' }} />
- <Skeleton.Button active size={'small'} style={{ height: 18, width: '100%' }} />
- </Flexbox>
- }
- >
- <ThreadList />
- </Suspense>
- )}
- </Flexbox>
- );
-});
-
-export default TopicItem;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/index.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/index.tsx
deleted file mode 100644
index ef5736ea167..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/TopicListContent/index.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-'use client';
-
-import { GuideCard } from '@lobehub/ui';
-import { useThemeMode } from 'antd-style';
-import React, { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { imageUrl } from '@/const/url';
-import { useFetchTopics } from '@/hooks/useFetchTopics';
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors } from '@/store/user/selectors';
-import { TopicDisplayMode } from '@/types/topic';
-
-import { SkeletonList } from '../../SkeletonList';
-import ByTimeMode from './ByTimeMode';
-import FlatMode from './FlatMode';
-import SearchResult from './SearchResult';
-
-const TopicListContent = memo(() => {
- const { t } = useTranslation('topic');
- const { isDarkMode } = useThemeMode();
- const [topicsInit, topicLength] = useChatStore((s) => [
- s.topicsInit,
- topicSelectors.currentTopicLength(s),
- ]);
- const [isUndefinedTopics, isInSearchMode] = useChatStore((s) => [
- topicSelectors.isUndefinedTopics(s),
- topicSelectors.isInSearchMode(s),
- ]);
-
- const [visible, updateGuideState, topicDisplayMode] = useUserStore((s) => [
- s.preference.guide?.topic,
- s.updateGuideState,
- preferenceSelectors.topicDisplayMode(s),
- ]);
-
- useFetchTopics();
-
- if (isInSearchMode) return <SearchResult />;
-
- // first time loading or has no data
- if (!topicsInit || isUndefinedTopics) return <SkeletonList />;
-
- return (
- <>
- {topicLength === 0 && visible && (
- <Flexbox paddingInline={8}>
- <GuideCard
- alt={t('guide.desc')}
- cover={imageUrl(`empty_topic_${isDarkMode ? 'dark' : 'light'}.webp`)}
- coverProps={{
- priority: true,
- }}
- desc={t('guide.desc')}
- height={120}
- onClose={() => {
- updateGuideState({ topic: false });
- }}
- style={{ flex: 'none', marginBottom: 12 }}
- title={t('guide.title')}
- visible={visible}
- width={200}
- />
- </Flexbox>
- )}
- {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
- </>
- );
-});
-
-TopicListContent.displayName = 'TopicListContent';
-
-export default TopicListContent;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/Topic/index.tsx b/src/app/[variants]/(main)/chat/components/topic/features/Topic/index.tsx
deleted file mode 100644
index 1b47a546c8b..00000000000
--- a/src/app/[variants]/(main)/chat/components/topic/features/Topic/index.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-'use client';
-
-import { Divider } from 'antd';
-import React, { memo } from 'react';
-
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-
-import Header from './Header';
-import TopicListContent from './TopicListContent';
-
-const Topic = memo(() => {
- const isInbox = useSessionStore(sessionSelectors.isInboxSession);
-
- return (
- <>
- {!isInbox && <Divider style={{ margin: 0 }} />}
-
- <Header />
- <TopicListContent />
- </>
- );
-});
-
-Topic.displayName = 'Topic';
-
-export default Topic;
diff --git a/src/app/[variants]/(main)/chat/components/features/ChangelogModal.tsx b/src/app/[variants]/(main)/chat/features/ChangelogModal.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/features/ChangelogModal.tsx
rename to src/app/[variants]/(main)/chat/features/ChangelogModal.tsx
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/AddButton.tsx b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/AddButton.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/AddButton.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/AddButton.tsx
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/OpeningQuestions.tsx b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/OpeningQuestions.tsx
new file mode 100644
index 00000000000..f435f0f060a
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/OpeningQuestions.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { Block } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useConversationStore } from '@/features/Conversation';
+
+// import { useSend } from '../../features/ChatInput/useSend';
+
+const useStyles = createStyles(({ css, token, responsive }) => ({
+ card: css`
+ padding-block: 8px;
+ padding-inline: 16px;
+ border-radius: 48px;
+
+ ${responsive.mobile} {
+ padding-block: 8px;
+ padding-inline: 16px;
+ }
+ `,
+
+ container: css`
+ padding-block: 0;
+ padding-inline: 0;
+ `,
+
+ title: css`
+ color: ${token.colorTextDescription};
+ `,
+}));
+
+interface OpeningQuestionsProps {
+ mobile?: boolean;
+ questions: string[];
+}
+
+const OpeningQuestions = memo<OpeningQuestionsProps>(({ mobile, questions }) => {
+ const { t } = useTranslation('welcome');
+ const [sendMessage] = useConversationStore((s) => [s.sendMessage]);
+
+ const { styles } = useStyles();
+
+ return (
+ <div className={styles.container}>
+ <p className={styles.title}>{t('guide.questions.title')}</p>
+ <Flexbox gap={8} horizontal wrap={'wrap'}>
+ {questions.slice(0, mobile ? 2 : 5).map((question) => {
+ return (
+ <Block
+ className={styles.card}
+ clickable
+ key={question}
+ onClick={() => {
+ sendMessage({ message: question });
+ }}
+ paddingBlock={8}
+ paddingInline={12}
+ variant={'filled'}
+ >
+ {question}
+ </Block>
+ );
+ })}
+ </Flexbox>
+ </div>
+ );
+});
+
+export default OpeningQuestions;
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert.tsx b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert.tsx
new file mode 100644
index 00000000000..b20ca189725
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert.tsx
@@ -0,0 +1,341 @@
+'use client';
+
+import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';
+import { Alert, Button, Icon, Image } from '@lobehub/ui';
+import { Typography } from 'antd';
+import { useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { Loader2, LogIn, SquareArrowOutUpRight, TriangleAlert } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useToolStore } from '@/store/tool';
+import {
+ KlavisServer,
+ KlavisServerStatus,
+ klavisStoreSelectors,
+} from '@/store/tool/slices/klavisStore';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+// Tools that require Market authentication
+const MARKET_AUTH_TOOLS = [
+ {
+ avatar:
+ 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IS0tIFVwbG9hZGVkIHRvOiBTVkcgUmVwbywgd3d3LnN2Z3JlcG8uY29tLCBHZW5lcmF0b3I6IFNWRyBSZXBvIE1peGVyIFRvb2xzIC0tPgo8c3ZnIHdpZHRoPSI4MDBweCIgaGVpZ2h0PSI4MDBweCIgdmlld0JveD0iMCAwIDMyIDMyIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPg0KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xMy4wMTY0IDJDMTAuODE5MyAyIDkuMDM4MjUgMy43MjQ1MyA5LjAzODI1IDUuODUxODVWOC41MTg1MkgxNS45MjM1VjkuMjU5MjZINS45NzgxNEMzLjc4MTA3IDkuMjU5MjYgMiAxMC45ODM4IDIgMTMuMTExMUwyIDE4Ljg4ODlDMiAyMS4wMTYyIDMuNzgxMDcgMjIuNzQwNyA1Ljk3ODE0IDIyLjc0MDdIOC4yNzMyMlYxOS40ODE1QzguMjczMjIgMTcuMzU0MiAxMC4wNTQzIDE1LjYyOTYgMTIuMjUxNCAxNS42Mjk2SDE5LjU5NTZDMjEuNDU0NyAxNS42Mjk2IDIyLjk2MTcgMTQuMTcwNCAyMi45NjE3IDEyLjM3MDRWNS44NTE4NUMyMi45NjE3IDMuNzI0NTMgMjEuMTgwNyAyIDE4Ljk4MzYgMkgxMy4wMTY0Wk0xMi4wOTg0IDYuNzQwNzRDMTIuODU4OSA2Ljc0MDc0IDEzLjQ3NTQgNi4xNDM3OCAxMy40NzU0IDUuNDA3NDFDMTMuNDc1NCA0LjY3MTAzIDEyLjg1ODkgNC4wNzQwNyAxMi4wOTg0IDQuMDc0MDdDMTEuMzM3OCA0LjA3NDA3IDEwLjcyMTMgNC42NzEwMyAxMC43MjEzIDUuNDA3NDFDMTAuNzIxMyA2LjE0Mzc4IDExLjMzNzggNi43NDA3NCAxMi4wOTg0IDYuNzQwNzRaIiBmaWxsPSJ1cmwoI3BhaW50MF9saW5lYXJfODdfODIwNCkiLz4NCjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTguOTgzNCAzMEMyMS4xODA1IDMwIDIyLjk2MTYgMjguMjc1NSAyMi45NjE2IDI2LjE0ODJWMjMuNDgxNUwxNi4wNzYzIDIzLjQ4MTVMMTYuMDc2MyAyMi43NDA4TDI2LjAyMTcgMjIuNzQwOEMyOC4yMTg4IDIyLjc0MDggMjkuOTk5OCAyMS4wMTYyIDI5Ljk5OTggMTguODg4OVYxMy4xMTExQzI5Ljk5OTggMTAuOTgzOCAyOC4yMTg4IDkuMjU5MjggMjYuMDIxNyA5LjI1OTI4TDIzLjcyNjYgOS4yNTkyOFYxMi41MTg1QzIzLjcyNjYgMTQuNjQ1OSAyMS45NDU1IDE2LjM3MDQgMTkuNzQ4NSAxNi4zNzA0TDEyLjQwNDIgMTYuMzcwNEMxMC41NDUxIDE2LjM3MDQgOS4wMzgwOSAxNy44Mjk2IDkuMDM4MDkgMTkuNjI5Nkw5LjAzODA5IDI2LjE0ODJDOS4wMzgwOSAyOC4yNzU1IDEwLjgxOTIgMzAgMTMuMDE2MiAzMEgxOC45ODM0Wk0xOS45MDE1IDI1LjI1OTNDMTkuMTQwOSAyNS4yNTkzIDE4LjUyNDQgMjUuODU2MiAxOC41MjQ0IDI2LjU5MjZDMTguNTI0NCAyNy4zMjkgMTkuMTQwOSAyNy45MjU5IDE5LjkwMTUgMjcuOTI1OUMyMC42NjIgMjcuOTI1OSAyMS4yNzg1IDI3LjMyOSAyMS4yNzg1IDI2LjU5MjZDMjEuMjc4NSAyNS44NTYyIDIwLjY2MiAyNS4yNTkzIDE5LjkwMTUgMjUuMjU5M1oiIGZpbGw9InVybCgjcGFpbnQxX2xpbmVhcl84N184MjA0KSIvPg0KPGRlZnM+DQo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfODdfODIwNCIgeDE9IjEyLjQ4MDkiIHkxPSIyIiB4Mj0iMTIuNDgwOSIgeTI9IjIyLjc0MDciIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4NCjxzdG9wIHN0b3AtY29sb3I9IiMzMjdFQkQiLz4NCjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzE1NjVBNyIvPg0KPC9saW5lYXJHcmFkaWVudD4NCjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQxX2xpbmVhcl84N184MjA0IiB4MT0iMTkuNTE5IiB5MT0iOS4yNTkyOCIgeDI9IjE5LjUxOSIgeTI9IjMwIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+DQo8c3RvcCBzdG9wLWNvbG9yPSIjRkZEQTRCIi8+DQo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGOUM2MDAiLz4NCjwvbGluZWFyR3JhZGllbnQ+DQo8L2RlZnM+DQo8L3N2Zz4=',
+ identifier: 'lobe-cloud-code-interpreter',
+ label: 'Cloud Code Interpreter',
+ },
+];
+
+const POLL_INTERVAL_MS = 1000;
+const POLL_TIMEOUT_MS = 15_000;
+
+interface PendingKlavisTool extends KlavisServerType {
+ authType: 'klavis';
+ server?: KlavisServer;
+}
+
+interface PendingMarketTool {
+ authType: 'market';
+ avatar: string;
+ identifier: string;
+ label: string;
+}
+
+type PendingAuthTool = PendingKlavisTool | PendingMarketTool;
+
+interface KlavisToolAuthItemProps {
+ onAuthComplete: () => void;
+ tool: PendingKlavisTool;
+}
+
+const KlavisToolAuthItem = memo<KlavisToolAuthItemProps>(({ tool, onAuthComplete }) => {
+ const { t } = useTranslation('chat');
+ const theme = useTheme();
+ const [isConnecting, setIsConnecting] = useState(false);
+ const [isWaitingAuth, setIsWaitingAuth] = useState(false);
+
+ const oauthWindowRef = useRef<Window | null>(null);
+ const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const userId = useUserStore(userProfileSelectors.userId);
+ const createKlavisServer = useToolStore((s) => s.createKlavisServer);
+ const refreshKlavisServerTools = useToolStore((s) => s.refreshKlavisServerTools);
+
+ const cleanup = useCallback(() => {
+ if (windowCheckIntervalRef.current) {
+ clearInterval(windowCheckIntervalRef.current);
+ windowCheckIntervalRef.current = null;
+ }
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ if (pollTimeoutRef.current) {
+ clearTimeout(pollTimeoutRef.current);
+ pollTimeoutRef.current = null;
+ }
+ oauthWindowRef.current = null;
+ setIsWaitingAuth(false);
+ }, []);
+
+ useEffect(() => {
+ return () => {
+ cleanup();
+ };
+ }, [cleanup]);
+
+ useEffect(() => {
+ if (tool.server?.status === KlavisServerStatus.CONNECTED && isWaitingAuth) {
+ cleanup();
+ onAuthComplete();
+ }
+ }, [tool.server?.status, isWaitingAuth, cleanup, onAuthComplete]);
+
+ const startFallbackPolling = useCallback(
+ (identifier: string) => {
+ if (pollIntervalRef.current) return;
+
+ pollIntervalRef.current = setInterval(async () => {
+ try {
+ await refreshKlavisServerTools(identifier);
+ } catch (error) {
+ console.error('[Klavis] Failed to check auth status:', error);
+ }
+ }, POLL_INTERVAL_MS);
+
+ pollTimeoutRef.current = setTimeout(() => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ setIsWaitingAuth(false);
+ }, POLL_TIMEOUT_MS);
+ },
+ [refreshKlavisServerTools],
+ );
+
+ const startWindowMonitor = useCallback(
+ (oauthWindow: Window, identifier: string) => {
+ windowCheckIntervalRef.current = setInterval(() => {
+ try {
+ if (oauthWindow.closed) {
+ if (windowCheckIntervalRef.current) {
+ clearInterval(windowCheckIntervalRef.current);
+ windowCheckIntervalRef.current = null;
+ }
+ oauthWindowRef.current = null;
+ refreshKlavisServerTools(identifier);
+ }
+ } catch {
+ if (windowCheckIntervalRef.current) {
+ clearInterval(windowCheckIntervalRef.current);
+ windowCheckIntervalRef.current = null;
+ }
+ startFallbackPolling(identifier);
+ }
+ }, 500);
+ },
+ [refreshKlavisServerTools, startFallbackPolling],
+ );
+
+ const openOAuthWindow = useCallback(
+ (oauthUrl: string, identifier: string) => {
+ cleanup();
+ setIsWaitingAuth(true);
+
+ const oauthWindow = window.open(oauthUrl, '_blank', 'width=600,height=700');
+ if (oauthWindow) {
+ oauthWindowRef.current = oauthWindow;
+ startWindowMonitor(oauthWindow, identifier);
+ } else {
+ startFallbackPolling(identifier);
+ }
+ },
+ [cleanup, startWindowMonitor, startFallbackPolling],
+ );
+
+ const handleAuthorize = async () => {
+ if (!userId) return;
+
+ if (tool.server?.status === KlavisServerStatus.PENDING_AUTH && tool.server.oauthUrl) {
+ openOAuthWindow(tool.server.oauthUrl, tool.server.identifier);
+ return;
+ }
+
+ setIsConnecting(true);
+ try {
+ const newServer = await createKlavisServer({
+ identifier: tool.identifier,
+ serverName: tool.serverName,
+ userId,
+ });
+
+ if (newServer) {
+ if (newServer.isAuthenticated) {
+ await refreshKlavisServerTools(newServer.identifier);
+ onAuthComplete();
+ } else if (newServer.oauthUrl) {
+ openOAuthWindow(newServer.oauthUrl, newServer.identifier);
+ }
+ }
+ } catch (error) {
+ console.error('[ToolAuthAlert] Failed to create server:', error);
+ } finally {
+ setIsConnecting(false);
+ }
+ };
+
+ const renderIcon = () => {
+ if (typeof tool.icon === 'string') {
+ return (
+ <Image alt={tool.label} height={20} src={tool.icon} style={{ flex: 'none' }} width={20} />
+ );
+ }
+ return <Icon fill={theme.colorText} icon={tool.icon} size={20} />;
+ };
+
+ const isLoading = isConnecting || isWaitingAuth;
+
+ return (
+ <Flexbox align="center" gap={12} horizontal justify="space-between">
+ <Flexbox align="center" gap={8} horizontal>
+ {renderIcon()}
+ <span>{tool.label}</span>
+ </Flexbox>
+ <Button
+ disabled={isLoading}
+ icon={isLoading ? <Icon icon={Loader2} spin /> : <Icon icon={SquareArrowOutUpRight} />}
+ onClick={handleAuthorize}
+ size="small"
+ type="primary"
+ >
+ {isLoading ? t('toolAuth.authorizing') : t('toolAuth.authorize')}
+ </Button>
+ </Flexbox>
+ );
+});
+
+KlavisToolAuthItem.displayName = 'KlavisToolAuthItem';
+
+interface MarketToolAuthItemProps {
+ tool: PendingMarketTool;
+}
+
+const MarketToolAuthItem = memo<MarketToolAuthItemProps>(({ tool }) => {
+ const { t } = useTranslation('chat');
+ const { signIn, isLoading } = useMarketAuth();
+
+ const handleSignIn = async () => {
+ try {
+ await signIn();
+ } catch (error) {
+ console.error('[ToolAuthAlert] Market sign in failed:', error);
+ }
+ };
+
+ return (
+ <Flexbox align="center" gap={12} horizontal justify="space-between">
+ <Flexbox align="center" gap={8} horizontal>
+ <Image alt={tool.label} height={20} src={tool.avatar} style={{ flex: 'none' }} width={20} />
+ <span>{tool.label}</span>
+ </Flexbox>
+ <Button
+ disabled={isLoading}
+ icon={isLoading ? <Icon icon={Loader2} spin /> : <Icon icon={LogIn} />}
+ onClick={handleSignIn}
+ size="small"
+ type="primary"
+ >
+ {isLoading ? t('toolAuth.authorizing') : t('toolAuth.signIn')}
+ </Button>
+ </Flexbox>
+ );
+});
+
+MarketToolAuthItem.displayName = 'MarketToolAuthItem';
+
+const ToolAuthAlert = memo(() => {
+ const { t } = useTranslation('chat');
+ const theme = useTheme();
+
+ const plugins = useAgentStore(agentSelectors.currentAgentPlugins, isEqual);
+ const klavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
+ const { isAuthenticated: isMarketAuthenticated } = useMarketAuth();
+
+ // Filter out tools that need authorization
+ const pendingAuthTools = useMemo<PendingAuthTool[]>(() => {
+ const result: PendingAuthTool[] = [];
+
+ for (const pluginId of plugins) {
+ // Check if this is a Klavis tool
+ const klavisType = KLAVIS_SERVER_TYPES.find((t) => t.identifier === pluginId);
+ if (klavisType) {
+ const server = klavisServers.find((s) => s.identifier === pluginId);
+ // Not installed or pending auth
+ if (!server || server.status === KlavisServerStatus.PENDING_AUTH) {
+ result.push({ ...klavisType, authType: 'klavis', server });
+ }
+ continue;
+ }
+
+ // Check if this is a Market auth tool
+ const marketTool = MARKET_AUTH_TOOLS.find((t) => t.identifier === pluginId);
+ if (marketTool && !isMarketAuthenticated) {
+ result.push({ ...marketTool, authType: 'market' });
+ }
+ }
+
+ return result;
+ }, [plugins, klavisServers, isMarketAuthenticated]);
+
+ // Don't render if no pending auth tools
+ if (pendingAuthTools.length === 0) {
+ return null;
+ }
+
+ return (
+ <Alert
+ description={
+ <Flexbox gap={12} style={{ marginTop: 8 }}>
+ {pendingAuthTools.map((tool) =>
+ tool.authType === 'klavis' ? (
+ <KlavisToolAuthItem
+ key={tool.identifier}
+ onAuthComplete={() => {
+ // Component will re-render and tool will be removed from list
+ }}
+ tool={tool}
+ />
+ ) : (
+ <MarketToolAuthItem key={tool.identifier} tool={tool} />
+ ),
+ )}
+ <Typography.Text style={{ color: theme.colorTextSecondary, fontSize: 12 }}>
+ {t('toolAuth.hint')}
+ </Typography.Text>
+ </Flexbox>
+ }
+ message={
+ <Flexbox align="center" gap={6} horizontal>
+ <Icon icon={TriangleAlert} size={18} />
+ {t('toolAuth.title')}
+ </Flexbox>
+ }
+ showIcon={false}
+ style={{ width: '100%' }}
+ type="warning"
+ />
+ );
+});
+
+ToolAuthAlert.displayName = 'ToolAuthAlert';
+
+export default ToolAuthAlert;
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/index.tsx
new file mode 100644
index 00000000000..35ff46f1783
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/index.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import { Avatar, Markdown, Text } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import React, { memo, useMemo } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { useIsMobile } from '@/hooks/useIsMobile';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+
+import AddButton from './AddButton';
+import OpeningQuestions from './OpeningQuestions';
+import ToolAuthAlert from './ToolAuthAlert';
+
+const InboxWelcome = memo(() => {
+ const { t } = useTranslation(['welcome', 'chat']);
+ const mobile = useIsMobile();
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const openingQuestions = useAgentStore(agentSelectors.openingQuestions, isEqual);
+ const fontSize = useUserStore(userGeneralSettingsSelectors.fontSize);
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+
+ const agentSystemRoleMsg = t('agentDefaultMessageWithSystemRole', {
+ name: meta.title || t('defaultAgent', { ns: 'chat' }),
+ ns: 'chat',
+ });
+ const openingMessage = useAgentStore(agentSelectors.openingMessage);
+
+ const message = useMemo(() => {
+ if (openingMessage) return openingMessage;
+ return agentSystemRoleMsg;
+ }, [openingMessage, agentSystemRoleMsg, meta.description]);
+
+ const displayTitle = isInbox ? 'Lobe AI' : meta.title || t('defaultSession', { ns: 'common' });
+
+ return (
+ <>
+ <Flexbox flex={1} />
+ <Flexbox
+ gap={12}
+ style={{
+ paddingBottom: 'max(10vh, 32px)',
+ }}
+ width={'100%'}
+ >
+ <Avatar
+ avatar={isInbox ? DEFAULT_INBOX_AVATAR : meta.avatar || DEFAULT_AVATAR}
+ background={meta.backgroundColor}
+ shape={'square'}
+ size={78}
+ />
+ <Text fontSize={32} weight={'bold'}>
+ {displayTitle}
+ </Text>
+ <Flexbox width={'min(100%, 640px)'}>
+ <Markdown
+ customRender={(dom, context) => {
+ if (context.text.includes('<plus />')) {
+ return (
+ <Trans
+ components={{
+ br: <br />,
+ plus: <AddButton />,
+ }}
+ i18nKey="guide.defaultMessage"
+ ns="welcome"
+ values={{ appName: 'Lobe AI' }}
+ />
+ );
+ }
+ return dom;
+ }}
+ fontSize={fontSize}
+ variant={'chat'}
+ >
+ {isInbox ? t('guide.defaultMessage', { appName: 'Lobe AI' }) : message}
+ </Markdown>
+ </Flexbox>
+ {openingQuestions.length > 0 && (
+ <OpeningQuestions mobile={mobile} questions={openingQuestions} />
+ )}
+ <ToolAuthAlert />
+ </Flexbox>
+ </>
+ );
+});
+
+export default InboxWelcome;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatHydration/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/ChatHydration/index.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatHydration/index.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/ChatHydration/index.tsx
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/MinimapIndicator.tsx b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/MinimapIndicator.tsx
new file mode 100644
index 00000000000..95638009239
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/MinimapIndicator.tsx
@@ -0,0 +1,65 @@
+import { Block, Text } from '@lobehub/ui';
+import { Popover } from 'antd';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useIndicatorStyles } from './styles';
+import type { MinimapIndicatorProps } from './types';
+
+export const MinimapIndicator = memo<MinimapIndicatorProps>(
+ ({ id, width, preview, role, virtuosoIndex, position, activePosition, onJump }) => {
+ const { t } = useTranslation('chat');
+ const { styles, cx } = useIndicatorStyles();
+
+ const isActive = activePosition === position;
+ const senderLabel = role === 'user' ? t('minimap.senderUser') : t('minimap.senderAssistant');
+
+ const popoverContent = preview ? (
+ <>
+ <Text fontSize={12} style={{ marginBottom: 4 }} type={'secondary'} weight={500}>
+ {senderLabel}
+ </Text>
+ <Text as={'p'} fontSize={12}>
+ {preview}
+ </Text>
+ </>
+ ) : undefined;
+
+ return (
+ <Popover
+ arrow={false}
+ content={popoverContent}
+ key={id}
+ mouseEnterDelay={0.1}
+ placement={'left'}
+ styles={{
+ body: {
+ width: 320,
+ },
+ }}
+ >
+ <Block
+ align={'flex-end'}
+ clickable
+ style={{ borderRadius: 4 }}
+ variant={'borderless'}
+ width={'100%'}
+ >
+ <div
+ aria-current={isActive ? 'true' : undefined}
+ aria-label={t('minimap.jumpToMessage', { index: position + 1 })}
+ className={styles.indicator}
+ onClick={() => onJump(virtuosoIndex)}
+ style={{ width }}
+ >
+ <div
+ className={cx(styles.indicatorContent, isActive && styles.indicatorContentActive)}
+ />
+ </div>
+ </Block>
+ </Popover>
+ );
+ },
+);
+
+MinimapIndicator.displayName = 'MinimapIndicator';
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/index.tsx
new file mode 100644
index 00000000000..25a978acdd3
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/index.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { MinimapIndicator } from './MinimapIndicator';
+import { useMinimapStyles } from './styles';
+import { useMinimapData } from './useMinimapData';
+import { MIN_MESSAGES_THRESHOLD } from './utils';
+
+const ChatMinimap = memo(() => {
+ const { t } = useTranslation('chat');
+ const { styles, cx } = useMinimapStyles();
+ const [isHovered, setIsHovered] = useState(false);
+
+ const { indicators, activeIndicatorPosition, handleJump, handleStep } = useMinimapData();
+
+ if (indicators.length <= MIN_MESSAGES_THRESHOLD) return null;
+
+ return (
+ <Flexbox align={'center'} className={styles.container} justify={'center'}>
+ <Flexbox
+ className={styles.rail}
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ role={'group'}
+ >
+ <ActionIcon
+ aria-label={t('minimap.previousMessage')}
+ className={cx(styles.arrow, isHovered && styles.arrowVisible)}
+ icon={ChevronUp}
+ onClick={() => handleStep('prev')}
+ size={14}
+ />
+ <Flexbox className={styles.railContent}>
+ {indicators.map(({ id, width, preview, role, virtuosoIndex }, position) => (
+ <MinimapIndicator
+ activePosition={activeIndicatorPosition}
+ id={id}
+ key={id}
+ onJump={handleJump}
+ position={position}
+ preview={preview}
+ role={role}
+ virtuosoIndex={virtuosoIndex}
+ width={width}
+ />
+ ))}
+ </Flexbox>
+ <ActionIcon
+ aria-label={t('minimap.nextMessage')}
+ className={cx(styles.arrow, isHovered && styles.arrowVisible)}
+ icon={ChevronDown}
+ onClick={() => handleStep('next')}
+ size={14}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+ChatMinimap.displayName = 'ChatMinimap';
+
+export default ChatMinimap;
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/styles.ts b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/styles.ts
new file mode 100644
index 00000000000..c3b65b80a75
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/styles.ts
@@ -0,0 +1,94 @@
+import { createStyles } from 'antd-style';
+
+export const useMinimapStyles = createStyles(({ css, token }) => ({
+ arrow: css`
+ opacity: 0;
+ transition: opacity ${token.motionDurationMid} ease;
+
+ &:hover {
+ color: ${token.colorText};
+ background: ${token.colorFill};
+ }
+
+ &:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px ${token.colorPrimaryBorder};
+ }
+ `,
+ arrowVisible: css`
+ opacity: 1;
+ `,
+ container: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 1;
+ inset-block: 16px 120px;
+ inset-inline-end: 8px;
+
+ width: 32px;
+ `,
+ rail: css`
+ pointer-events: auto;
+
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ align-items: end;
+ justify-content: space-between;
+
+ width: 100%;
+ height: fit-content;
+ margin-block: 0;
+ margin-inline: auto;
+
+ &:hover .arrow {
+ opacity: 1;
+ }
+ `,
+ railContent: css`
+ scrollbar-width: none;
+
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ align-items: end;
+ justify-content: space-between;
+
+ max-height: 50vh;
+
+ /* Hide scrollbar for IE, Edge and Firefox */
+ -ms-overflow-style: none;
+
+ /* Hide scrollbar for Chrome, Safari and Opera */
+ &::-webkit-scrollbar {
+ display: none;
+ }
+ `,
+}));
+
+export const useIndicatorStyles = createStyles(({ css, token }) => ({
+ indicator: css`
+ flex-shrink: 0;
+
+ min-width: 12px;
+ height: 12px;
+ padding-block: 5px;
+ padding-inline: 4px;
+ `,
+ indicatorActive: css`
+ transform: scaleX(1.1);
+ background: ${token.colorPrimary};
+ box-shadow: 0 0 0 1px ${token.colorPrimaryHover};
+ `,
+ indicatorContent: css`
+ width: 100%;
+ height: 100%;
+ border-radius: 3px;
+ background: ${token.colorFillSecondary};
+ `,
+ indicatorContentActive: css`
+ background: ${token.colorPrimary};
+ `,
+}));
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/types.ts b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/types.ts
new file mode 100644
index 00000000000..0988cde6cc9
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/types.ts
@@ -0,0 +1,18 @@
+export interface MinimapIndicator {
+ id: string;
+ preview: string;
+ role: 'user' | 'assistant';
+ virtuosoIndex: number;
+ width: number;
+}
+
+export interface MinimapIndicatorProps {
+ activePosition: number | null;
+ id: string;
+ onJump: (virtuosoIndex: number) => void;
+ position: number;
+ preview: string;
+ role: 'user' | 'assistant';
+ virtuosoIndex: number;
+ width: number;
+}
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/useMinimapData.ts b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/useMinimapData.ts
new file mode 100644
index 00000000000..3ef1f2d3fa1
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/useMinimapData.ts
@@ -0,0 +1,112 @@
+import debug from 'debug';
+import isEqual from 'fast-deep-equal';
+import { useCallback, useMemo } from 'react';
+
+import { conversationSelectors, useConversationStore } from '@/features/Conversation';
+
+import type { MinimapIndicator } from './types';
+import { getIndicatorWidth, getPreviewText } from './utils';
+
+const log = debug('lobe-react:chat-minimap');
+
+export const useMinimapData = () => {
+ const scrollMethods = useConversationStore(conversationSelectors.virtuaScrollMethods);
+ const activeIndex = useConversationStore(conversationSelectors.activeIndex);
+ const messages = useConversationStore(conversationSelectors.displayMessages, isEqual);
+
+ const indicators = useMemo<MinimapIndicator[]>(() => {
+ return messages.reduce<MinimapIndicator[]>((acc, message, virtuosoIndex) => {
+ if (message.role !== 'user' && message.role !== 'assistant') return acc;
+
+ acc.push({
+ id: message.id,
+ preview: getPreviewText(message.content),
+ role: message.role,
+ virtuosoIndex,
+ width: getIndicatorWidth(message.content),
+ });
+
+ return acc;
+ }, []);
+ }, [messages]);
+
+ const indicatorIndexMap = useMemo(() => {
+ const map = new Map<number, number>();
+ indicators.forEach(({ virtuosoIndex }, position) => {
+ map.set(virtuosoIndex, position);
+ });
+ return map;
+ }, [indicators]);
+
+ const activeIndicatorPosition = useMemo(() => {
+ if (activeIndex === null) return null;
+
+ log('> activeIndex', activeIndex);
+ log('> indicatorIndexMap', indicatorIndexMap);
+
+ return indicatorIndexMap.get(activeIndex) ?? null;
+ }, [activeIndex, indicatorIndexMap]);
+
+ const handleJump = useCallback(
+ (virtIndex: number) => {
+ scrollMethods?.scrollToIndex(virtIndex, { align: 'start', smooth: true });
+ },
+ [scrollMethods],
+ );
+
+ const handleStep = useCallback(
+ (direction: 'prev' | 'next') => {
+ if (!scrollMethods || indicators.length === 0) return;
+
+ let targetPosition: number;
+
+ if (activeIndicatorPosition !== null) {
+ log('activeIndicatorPosition', activeIndicatorPosition);
+ // We're on an indicator, move to prev/next
+ const delta = direction === 'prev' ? -1 : 1;
+ targetPosition = Math.min(
+ Math.max(activeIndicatorPosition + delta, 0),
+ Math.max(indicators.length - 1, 0),
+ );
+ } else if (activeIndex !== null) {
+ // We're not on an indicator, find the nearest one in the direction
+ if (direction === 'prev') {
+ let matched = -1;
+ for (let pos = indicators.length - 1; pos >= 0; pos -= 1) {
+ if (indicators[pos].virtuosoIndex < activeIndex) {
+ matched = pos;
+ break;
+ }
+ }
+ targetPosition = matched === -1 ? 0 : matched;
+ } else {
+ let matched = indicators.length - 1;
+ for (const [pos, indicator] of indicators.entries()) {
+ if (indicator.virtuosoIndex > activeIndex) {
+ matched = pos;
+ break;
+ }
+ }
+ targetPosition = matched;
+ }
+ } else {
+ // No active index, go to first/last
+ targetPosition = direction === 'prev' ? indicators.length - 1 : 0;
+ }
+
+ const targetIndicator = indicators[targetPosition];
+
+ if (!targetIndicator) return;
+
+ scrollMethods.scrollToIndex(targetIndicator.virtuosoIndex, { align: 'start', smooth: true });
+ },
+ [activeIndex, activeIndicatorPosition, indicators, scrollMethods],
+ );
+
+ return {
+ activeIndicatorPosition,
+ handleJump,
+ handleStep,
+ indicators,
+ };
+};
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/utils.ts b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/utils.ts
new file mode 100644
index 00000000000..515b38dd75b
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/ChatMinimap/utils.ts
@@ -0,0 +1,25 @@
+import { markdownToTxt } from 'markdown-to-txt';
+
+const MIN_WIDTH = 12;
+const MAX_WIDTH = 24;
+const MAX_CONTENT_LENGTH = 320;
+
+export const getIndicatorWidth = (content: string | undefined): number => {
+ if (!content) return MIN_WIDTH;
+
+ const ratio = Math.min(content.length / MAX_CONTENT_LENGTH, 1);
+
+ return MIN_WIDTH + (MAX_WIDTH - MIN_WIDTH) * ratio;
+};
+
+export const getPreviewText = (content: string | undefined): string => {
+ if (!content) return '';
+
+ const plainText = markdownToTxt(content);
+ const normalized = plainText.replaceAll(/\s+/g, ' ').trim();
+ if (!normalized) return '';
+
+ return normalized.slice(0, 100) + (normalized.length > 100 ? '…' : '');
+};
+
+export const MIN_MESSAGES_THRESHOLD = 3;
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/ConversationArea.tsx b/src/app/[variants]/(main)/chat/features/Conversation/ConversationArea.tsx
new file mode 100644
index 00000000000..d69cbd90fe2
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/ConversationArea.tsx
@@ -0,0 +1,118 @@
+'use client';
+
+import { MemoryManifest } from '@lobechat/builtin-tool-memory';
+import { Suspense, memo, useEffect, useMemo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ChatList, ConversationProvider } from '@/features/Conversation';
+import { useOperationState } from '@/hooks/useOperationState';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { useSessionStore } from '@/store/session';
+import { sessionSelectors } from '@/store/session/selectors';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import WelcomeChatItem from './AgentWelcome';
+import ChatHydration from './ChatHydration';
+import ChatMinimap from './ChatMinimap';
+import MainChatInput from './MainChatInput';
+import MessageFromUrl from './MainChatInput/MessageFromUrl';
+import ThreadHydration from './ThreadHydration';
+import ZenModeToast from './ZenModeToast';
+import { useActionsBarConfig } from './useActionsBarConfig';
+import { useAgentContext } from './useAgentContext';
+
+/**
+ * ConversationArea
+ *
+ * Main conversation area component using the new ConversationStore architecture.
+ * Uses ChatList from @/features/Conversation and MainChatInput for custom features.
+ */
+const Conversation = memo(() => {
+ const context = useAgentContext();
+
+ const enabledPlugins = useAgentStore(agentSelectors.currentAgentPlugins);
+ const [useFetchUserMemory, setActiveMemoryContext] = useUserMemoryStore((s) => [
+ s.useFetchUserMemory,
+ s.setActiveMemoryContext,
+ ]);
+ const [currentSession, activeTopic] = [
+ useSessionStore(sessionSelectors.currentSession),
+ useChatStore(topicSelectors.currentActiveTopic),
+ ];
+
+ const isMemoryPluginEnabled = useMemo(() => {
+ if (!enabledPlugins) return false;
+
+ return enabledPlugins.includes(MemoryManifest.identifier);
+ }, [enabledPlugins]);
+
+ useEffect(() => {
+ if (!isMemoryPluginEnabled) {
+ setActiveMemoryContext(undefined);
+ return;
+ }
+
+ setActiveMemoryContext({
+ session: currentSession,
+ topic: activeTopic,
+ });
+ }, [activeTopic, currentSession, isMemoryPluginEnabled, setActiveMemoryContext]);
+
+ useFetchUserMemory(Boolean(isMemoryPluginEnabled && context.agentId));
+
+ // Get raw dbMessages from ChatStore for this context
+ // ConversationStore will parse them internally to generate displayMessages
+ const chatKey = useMemo(
+ () => messageMapKey(context),
+ [context.agentId, context.topicId, context.threadId],
+ );
+ const replaceMessages = useChatStore((s) => s.replaceMessages);
+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
+
+ // Get operation state from ChatStore for reactive updates
+ const operationState = useOperationState(context);
+
+ // Get actionsBar config with branching support from ChatStore
+ const actionsBarConfig = useActionsBarConfig();
+
+ return (
+ <ConversationProvider
+ actionsBar={actionsBarConfig}
+ context={context}
+ hasInitMessages={!!messages}
+ messages={messages}
+ onMessagesChange={(messages) => {
+ replaceMessages(messages, { context });
+ }}
+ operationState={operationState}
+ >
+ <ZenModeToast />
+ <Flexbox
+ flex={1}
+ style={{
+ overflowX: 'hidden',
+ overflowY: 'auto',
+ position: 'relative',
+ }}
+ width={'100%'}
+ >
+ <ChatList welcome={<WelcomeChatItem />} />
+ </Flexbox>
+ <MainChatInput />
+ <ChatHydration />
+ <ThreadHydration />
+ <ChatMinimap />
+ <Suspense>
+ <MessageFromUrl />
+ </Suspense>
+ </ConversationProvider>
+ );
+});
+
+Conversation.displayName = 'ConversationArea';
+
+export default Conversation;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/useTemplateMatching.ts b/src/app/[variants]/(main)/chat/features/Conversation/GroupWelcome/useTemplateMatching.ts
similarity index 68%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/useTemplateMatching.ts
rename to src/app/[variants]/(main)/chat/features/Conversation/GroupWelcome/useTemplateMatching.ts
index b4a8370eb86..bd850f5e585 100644
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/GroupWelcome/useTemplateMatching.ts
+++ b/src/app/[variants]/(main)/chat/features/Conversation/GroupWelcome/useTemplateMatching.ts
@@ -18,50 +18,31 @@ export const useTemplateMatching = (): TemplateMatch | null => {
sessionSelectors.currentSession,
) as LobeGroupSession | null;
- console.log('groupTemplates', groupTemplates);
- console.log('currentSession', currentSession);
-
return useMemo(() => {
if (!currentSession || currentSession.type !== 'group') {
- console.log('No group session found:', { currentSession });
+ console.warn('No group session found:', { currentSession });
return null;
}
const currentTitle = currentSession.meta?.title || '';
const currentMemberCount = currentSession.members?.length || 0;
- console.log('Current group session:', {
- memberCount: currentMemberCount,
- members: currentSession.members,
- title: currentTitle,
- });
-
// Try to match by title and member count
for (const template of groupTemplates) {
const templateTitle = template.title;
const templateMemberCount = template.members.length;
- console.log('Checking template:', {
- memberCountDiff: Math.abs(templateMemberCount - currentMemberCount),
- templateId: template.id,
- templateMemberCount,
- templateTitle,
- titleMatch: templateTitle.toLowerCase() === currentTitle.toLowerCase(),
- });
-
// Check if titles match (case-insensitive) and member counts are similar (±1)
if (
templateTitle.toLowerCase() === currentTitle.toLowerCase() &&
Math.abs(templateMemberCount - currentMemberCount) <= 1
) {
- console.log('Found exact match for template:', template.id);
+ console.warn('Found exact match for template:', template.id);
// Get template-specific activities from i18n
const templateActivities = (t as any)(`guide.groupActivities.${template.id}`, {
returnObjects: true,
}) as Record<string, { description: string; emoji: string; prompt: string; title: string }>;
- console.log('Template activities:', templateActivities);
-
return {
activities: templateActivities || {},
templateId: template.id,
@@ -70,36 +51,24 @@ export const useTemplateMatching = (): TemplateMatch | null => {
}
// If no exact match, try partial title matching
- console.log('No exact match found, trying partial matching...');
+ console.warn('No exact match found, trying partial matching...');
for (const template of groupTemplates) {
const templateTitle = template.title;
const currentIncludes = currentTitle.toLowerCase().includes(templateTitle.toLowerCase());
const templateIncludes = templateTitle.toLowerCase().includes(currentTitle.toLowerCase());
- console.log('Partial match check:', {
- currentIncludes,
- templateId: template.id,
- templateIncludes,
- templateTitle,
- });
-
if (currentIncludes || templateIncludes) {
- console.log('Found partial match for template:', template.id);
const templateActivities = (t as any)(`guide.groupActivities.${template.id}`, {
returnObjects: true,
}) as Record<string, { description: string; emoji: string; prompt: string; title: string }>;
- console.log('Template activities:', templateActivities);
-
return {
activities: templateActivities || {},
templateId: template.id,
};
}
}
-
- console.log('No template match found, returning null');
return null;
}, [currentSession, groupTemplates, t]);
};
diff --git a/src/app/[variants]/(main)/chat/components/features/ShareButton/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/Header/ShareButton/index.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/features/ShareButton/index.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/Header/ShareButton/index.tsx
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/HistoryLimitTags.tsx b/src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/HistoryLimitTags.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/HistoryLimitTags.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/HistoryLimitTags.tsx
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/KnowledgeTag.tsx b/src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/KnowledgeTag.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/KnowledgeTag.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/KnowledgeTag.tsx
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/MemberCountTag.tsx b/src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/MemberCountTag.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/MemberCountTag.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/MemberCountTag.tsx
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/SearchTags.tsx b/src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/SearchTags.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/SearchTags.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/SearchTags.tsx
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/index.tsx
similarity index 98%
rename from src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/index.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/index.tsx
index 72c98c85212..e6ead97ddc1 100644
--- a/src/app/[variants]/(main)/chat/components/layout/Desktop/ChatHeader/Tags/index.tsx
+++ b/src/app/[variants]/(main)/chat/features/Conversation/Header/Tags/index.tsx
@@ -1,5 +1,5 @@
import { ModelTag } from '@lobehub/icons';
-import { Skeleton } from 'antd';
+import { Skeleton } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/Header/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/Header/index.tsx
new file mode 100644
index 00000000000..7c41b0c5dfe
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/Header/index.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import NavHeader from '@/features/NavHeader';
+
+import WideScreenButton from '../../../../../../../features/WideScreenContainer/WideScreenButton';
+import ShareButton from './ShareButton';
+import Tags from './Tags';
+
+const Header = memo(() => {
+ const theme = useTheme();
+ return (
+ <NavHeader
+ left={
+ <Flexbox style={{ backgroundColor: theme.colorBgContainer }}>
+ <Tags />
+ </Flexbox>
+ }
+ right={
+ <Flexbox horizontal style={{ backgroundColor: theme.colorBgContainer }}>
+ <WideScreenButton />
+ <ShareButton />
+ </Flexbox>
+ }
+ />
+ );
+});
+
+export default Header;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/MessageFromUrl.tsx b/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/MessageFromUrl.tsx
similarity index 52%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/MessageFromUrl.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/MessageFromUrl.tsx
index 240868efce9..27ae1dacc49 100644
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/MessageFromUrl.tsx
+++ b/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/MessageFromUrl.tsx
@@ -3,13 +3,19 @@
import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
-import { useChatStore } from '@/store/chat';
-
-import { useSend } from '../useSend';
-
+import { useConversationStore } from '@/features/Conversation';
+
+/**
+ * MessageFromUrl
+ *
+ * Handles sending messages from URL query parameters.
+ * Uses ConversationStore for input and send operations.
+ */
const MessageFromUrl = () => {
- const updateMessageInput = useChatStore((s) => s.updateMessageInput);
- const { send: sendMessage } = useSend();
+ const [updateInputMessage, sendMessage] = useConversationStore((s) => [
+ s.updateInputMessage,
+ s.sendMessage,
+ ]);
const [searchParams, setSearchParams] = useSearchParams();
useEffect(() => {
@@ -20,9 +26,9 @@ const MessageFromUrl = () => {
params.delete('message');
setSearchParams(params, { replace: true });
- updateMessageInput(message);
- sendMessage();
- }, [searchParams, setSearchParams, updateMessageInput, sendMessage]);
+ updateInputMessage(message);
+ sendMessage({ message });
+ }, [searchParams, setSearchParams, updateInputMessage, sendMessage]);
return null;
};
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/index.tsx
new file mode 100644
index 00000000000..28704ecb0d7
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/index.tsx
@@ -0,0 +1,51 @@
+'use client';
+
+import { memo } from 'react';
+
+import { type ActionKeys } from '@/features/ChatInput';
+import { ChatInput } from '@/features/Conversation';
+import { useChatStore } from '@/store/chat';
+
+import { useSendMenuItems } from './useSendMenuItems';
+
+const leftActions: ActionKeys[] = [
+ 'model',
+ 'search',
+ 'typo',
+ 'fileUpload',
+ 'knowledgeBase',
+ 'tools',
+ '---',
+ ['params', 'history', 'stt', 'clear'],
+ 'mainToken',
+];
+
+const rightActions: ActionKeys[] = [];
+
+/**
+ * MainChatInput
+ *
+ * Custom ChatInput implementation for main chat page.
+ * Uses ChatInput from @/features/Conversation which handles all send logic
+ * including error alerts display.
+ * Only adds MessageFromUrl for desktop mode.
+ */
+const MainChatInput = memo(() => {
+ const sendMenuItems = useSendMenuItems();
+
+ return (
+ <ChatInput
+ leftActions={leftActions}
+ onEditorReady={(instance) => {
+ // Sync to global ChatStore for compatibility with other features
+ useChatStore.setState({ mainInputEditor: instance });
+ }}
+ rightActions={rightActions}
+ sendMenu={{ items: sendMenuItems }}
+ />
+ );
+});
+
+MainChatInput.displayName = 'MainChatInput';
+
+export default MainChatInput;
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/useSendMenuItems.tsx b/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/useSendMenuItems.tsx
new file mode 100644
index 00000000000..92e92f07f91
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/MainChatInput/useSendMenuItems.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { Hotkey, Icon, type MenuProps } from '@lobehub/ui';
+import { BotMessageSquare, LucideCheck, MessageSquarePlus } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useConversationStore, useConversationStoreApi } from '@/features/Conversation';
+import { useAddUserMessageHotkey } from '@/hooks/useHotkeys';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
+import { HotkeyEnum, KeyEnum } from '@/types/hotkey';
+
+/**
+ * useSendMenuItems hook for ConversationStore
+ *
+ * Provides send menu items for:
+ * - Send with Enter / Cmd+Enter toggle
+ * - Add AI Message
+ * - Add User Message
+ */
+export const useSendMenuItems = (): MenuProps['items'] => {
+ const { t } = useTranslation('chat');
+
+ const storeApi = useConversationStoreApi();
+ const editor = useConversationStore((s) => s.editor);
+
+ const [useCmdEnterToSend, updatePreference] = useUserStore((s) => [
+ preferenceSelectors.useCmdEnterToSend(s),
+ s.updatePreference,
+ ]);
+
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
+
+ const handleAddAIMessage = useCallback(() => {
+ const store = storeApi.getState();
+ // Add empty AI message placeholder
+ store.addAIMessage('');
+ // Clear and focus editor
+ editor?.clearContent();
+ editor?.focus();
+ }, [storeApi, editor]);
+
+ const handleAddUserMessage = useCallback(() => {
+ const store = storeApi.getState();
+ const message = store.inputMessage;
+ if (!message.trim()) return;
+
+ store.addUserMessage({ message });
+ // Clear and focus editor
+ editor?.clearContent();
+ editor?.focus();
+ }, [storeApi, editor]);
+
+ useAddUserMessageHotkey(handleAddUserMessage);
+
+ return useMemo(
+ () => [
+ {
+ icon: !useCmdEnterToSend ? <Icon icon={LucideCheck} /> : <div />,
+ key: 'sendWithEnter',
+ label: (
+ <Flexbox align={'center'} gap={4} horizontal>
+ <Trans
+ components={{
+ key: <Hotkey keys={KeyEnum.Enter} variant={'borderless'} />,
+ }}
+ i18nKey={'input.sendWithEnter'}
+ ns={'chat'}
+ />
+ </Flexbox>
+ ),
+ onClick: () => {
+ updatePreference({ useCmdEnterToSend: false });
+ },
+ },
+ {
+ icon: useCmdEnterToSend ? <Icon icon={LucideCheck} /> : <div />,
+ key: 'sendWithCmdEnter',
+ label: (
+ <Flexbox align={'center'} gap={4} horizontal>
+ <Trans
+ components={{
+ key: (
+ <Hotkey keys={[KeyEnum.Mod, KeyEnum.Enter].join('+')} variant={'borderless'} />
+ ),
+ }}
+ i18nKey={'input.sendWithCmdEnter'}
+ ns={'chat'}
+ />
+ </Flexbox>
+ ),
+ onClick: () => {
+ updatePreference({ useCmdEnterToSend: true });
+ },
+ },
+ { type: 'divider' },
+ {
+ icon: <Icon icon={BotMessageSquare} />,
+ key: 'addAi',
+ label: t('input.addAi'),
+ onClick: handleAddAIMessage,
+ },
+ {
+ icon: <Icon icon={MessageSquarePlus} />,
+ key: 'addUser',
+ label: (
+ <Flexbox align={'center'} gap={24} horizontal>
+ {t('input.addUser')}
+ <Hotkey keys={hotkey} />
+ </Flexbox>
+ ),
+ onClick: handleAddUserMessage,
+ },
+ ],
+ [useCmdEnterToSend, updatePreference, hotkey, handleAddAIMessage, handleAddUserMessage],
+ );
+};
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ThreadHydration.tsx b/src/app/[variants]/(main)/chat/features/Conversation/ThreadHydration.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ThreadHydration.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/ThreadHydration.tsx
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ZenModeToast/Toast.tsx b/src/app/[variants]/(main)/chat/features/Conversation/ZenModeToast/Toast.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ZenModeToast/Toast.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/ZenModeToast/Toast.tsx
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ZenModeToast/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/ZenModeToast/index.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ZenModeToast/index.tsx
rename to src/app/[variants]/(main)/chat/features/Conversation/ZenModeToast/index.tsx
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/index.tsx b/src/app/[variants]/(main)/chat/features/Conversation/index.tsx
new file mode 100644
index 00000000000..e0994f01f95
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/index.tsx
@@ -0,0 +1,22 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import ConversationArea from './ConversationArea';
+import ChatHeader from './Header';
+
+const ChatConversation = memo(() => {
+ const showHeader = useGlobalStore(systemStatusSelectors.showChatHeader);
+ return (
+ <Flexbox height={'100%'} style={{ overflow: 'hidden', position: 'relative' }} width={'100%'}>
+ {showHeader && <ChatHeader />}
+ <ConversationArea />
+ </Flexbox>
+ );
+});
+
+ChatConversation.displayName = 'ChatConversation';
+
+export default ChatConversation;
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/useActionsBarConfig.ts b/src/app/[variants]/(main)/chat/features/Conversation/useActionsBarConfig.ts
new file mode 100644
index 00000000000..dce5b223be7
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/useActionsBarConfig.ts
@@ -0,0 +1,63 @@
+'use client';
+
+import { App } from 'antd';
+import { Split } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type {
+ ActionsBarConfig,
+ MessageActionFactory,
+ MessageActionItem,
+} from '@/features/Conversation/types';
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Hook to create a branching action factory function.
+ * The factory function takes a message id and returns the branching action
+ * with proper ChatStore integration.
+ */
+export const useBranchingActionFactory = (): MessageActionFactory => {
+ const { t } = useTranslation('common');
+ const { message } = App.useApp();
+
+ const [topic, openThreadCreator] = useChatStore((s) => [s.activeTopicId, s.openThreadCreator]);
+
+ return useCallback(
+ (id: string): MessageActionItem | null => {
+ return {
+ handleClick: () => {
+ if (!topic) {
+ message.warning(t('branchingRequiresSavedTopic'));
+ return;
+ }
+ openThreadCreator(id);
+ },
+ icon: Split,
+ key: 'branching',
+ label: t('branching'),
+ };
+ },
+ [topic, openThreadCreator],
+ );
+};
+
+/**
+ * Hook to generate actionsBar configuration with branching support.
+ * This creates the complete actionsBar config to be passed to ChatList.
+ */
+export const useActionsBarConfig = (): ActionsBarConfig => {
+ const branchingFactory = useBranchingActionFactory();
+
+ return useMemo(
+ () => ({
+ assistant: {
+ extraBarActions: [branchingFactory],
+ },
+ user: {
+ extraBarActions: [branchingFactory],
+ },
+ }),
+ [branchingFactory],
+ );
+};
diff --git a/src/app/[variants]/(main)/chat/features/Conversation/useAgentContext.ts b/src/app/[variants]/(main)/chat/features/Conversation/useAgentContext.ts
new file mode 100644
index 00000000000..f5e73eefc0a
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Conversation/useAgentContext.ts
@@ -0,0 +1,26 @@
+'use client';
+
+import { ConversationContext } from '@lobechat/types';
+
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Hook to get agent conversation context
+ *
+ * Only for agent chat page (main/thread scope).
+ * Returns context for regular agent conversations.
+ */
+export function useAgentContext(): ConversationContext {
+ const [agentId, topicId, threadId] = useChatStore((s) => [
+ s.activeAgentId,
+ s.activeTopicId ?? null,
+ s.activeThreadId ?? null,
+ ]);
+
+ return {
+ agentId,
+ scope: threadId ? 'thread' : 'main',
+ threadId,
+ topicId,
+ };
+}
diff --git a/src/app/[variants]/(main)/chat/features/PageTitle/index.tsx b/src/app/[variants]/(main)/chat/features/PageTitle/index.tsx
index 855e93cb718..60e97a1d175 100644
--- a/src/app/[variants]/(main)/chat/features/PageTitle/index.tsx
+++ b/src/app/[variants]/(main)/chat/features/PageTitle/index.tsx
@@ -3,13 +3,13 @@
import { memo } from 'react';
import PageTitle from '@/components/PageTitle';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors } from '@/store/session/selectors';
const Title = memo(() => {
- const agentTitle = useSessionStore(sessionMetaSelectors.currentAgentTitle);
+ const agentTitle = useAgentStore(agentSelectors.currentAgentTitle);
const topicTitle = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.title);
return <PageTitle title={[topicTitle, agentTitle].filter(Boolean).join(' · ')} />;
diff --git a/src/app/[variants]/(main)/chat/components/portal/_layout/Desktop.tsx b/src/app/[variants]/(main)/chat/features/Portal/_layout/Desktop.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/portal/_layout/Desktop.tsx
rename to src/app/[variants]/(main)/chat/features/Portal/_layout/Desktop.tsx
diff --git a/src/app/[variants]/(main)/chat/components/portal/_layout/Mobile.tsx b/src/app/[variants]/(main)/chat/features/Portal/_layout/Mobile.tsx
similarity index 97%
rename from src/app/[variants]/(main)/chat/components/portal/_layout/Mobile.tsx
rename to src/app/[variants]/(main)/chat/features/Portal/_layout/Mobile.tsx
index d94a92fc1bd..a52be46eefb 100644
--- a/src/app/[variants]/(main)/chat/components/portal/_layout/Mobile.tsx
+++ b/src/app/[variants]/(main)/chat/features/Portal/_layout/Mobile.tsx
@@ -11,7 +11,7 @@ import { useChatStore } from '@/store/chat';
const useStyles = createStyles(({ css, token }) => ({
container: css`
- background: linear-gradient(${token.colorBgElevated}, ${token.colorBgLayout}) !important;
+ background: linear-gradient(${token.colorBgElevated}, ${token.colorBgContainer}) !important;
`,
}));
diff --git a/src/app/[variants]/(main)/chat/components/portal/features/Body.tsx b/src/app/[variants]/(main)/chat/features/Portal/features/Body.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/portal/features/Body.tsx
rename to src/app/[variants]/(main)/chat/features/Portal/features/Body.tsx
diff --git a/src/app/[variants]/(main)/chat/components/layout/Desktop/Portal.tsx b/src/app/[variants]/(main)/chat/features/Portal/features/Portal.tsx
similarity index 96%
rename from src/app/[variants]/(main)/chat/components/layout/Desktop/Portal.tsx
rename to src/app/[variants]/(main)/chat/features/Portal/features/Portal.tsx
index ece0053b2d4..79f6fd9b180 100644
--- a/src/app/[variants]/(main)/chat/components/layout/Desktop/Portal.tsx
+++ b/src/app/[variants]/(main)/chat/features/Portal/features/Portal.tsx
@@ -25,12 +25,12 @@ const useStyles = createStyles(({ css, token }) => ({
drawer: css`
z-index: 10;
height: 100%;
- background: ${token.colorBgLayout};
+ background: ${token.colorBgContainer};
`,
panel: css`
overflow: hidden;
height: 100%;
- background: ${token.colorBgContainerSecondary};
+ background: ${token.colorBgContainer};
`,
}));
diff --git a/src/app/[variants]/(main)/chat/components/PortalPanel.tsx b/src/app/[variants]/(main)/chat/features/Portal/features/PortalPanel.tsx
similarity index 68%
rename from src/app/[variants]/(main)/chat/components/PortalPanel.tsx
rename to src/app/[variants]/(main)/chat/features/Portal/features/PortalPanel.tsx
index a06abe38970..9080a2ef4e2 100644
--- a/src/app/[variants]/(main)/chat/components/PortalPanel.tsx
+++ b/src/app/[variants]/(main)/chat/features/Portal/features/PortalPanel.tsx
@@ -1,10 +1,9 @@
import { Suspense, lazy, memo } from 'react';
+import DesktopLayout from '@/app/[variants]/(main)/chat/features/Portal/_layout/Desktop';
+import MobileLayout from '@/app/[variants]/(main)/chat/features/Portal/_layout/Mobile';
import Loading from '@/components/Loading/BrandTextLoading';
-import DesktopLayout from './portal/_layout/Desktop';
-import MobileLayout from './portal/_layout/Mobile';
-
const PortalBody = lazy(() => import('@/features/Portal/router'));
interface PortalPanelProps {
@@ -15,7 +14,7 @@ const PortalPanel = memo<PortalPanelProps>(({ mobile }) => {
const Layout = mobile ? MobileLayout : DesktopLayout;
return (
- <Suspense fallback={<Loading />}>
+ <Suspense fallback={<Loading debugId="PortalPanel" />}>
<Layout>
<PortalBody />
</Layout>
diff --git a/src/app/[variants]/(main)/chat/features/Portal/index.tsx b/src/app/[variants]/(main)/chat/features/Portal/index.tsx
new file mode 100644
index 00000000000..6ce8b46db93
--- /dev/null
+++ b/src/app/[variants]/(main)/chat/features/Portal/index.tsx
@@ -0,0 +1,19 @@
+import { Suspense } from 'react';
+
+import Portal from '@/app/[variants]/(main)/chat/features/Portal/features/Portal';
+import PortalPanel from '@/app/[variants]/(main)/chat/features/Portal/features/PortalPanel';
+import Loading from '@/components/Loading/BrandTextLoading';
+
+const ChatPortal = () => {
+ return (
+ <Portal>
+ <Suspense fallback={<Loading debugId={'ChatPortal'} />}>
+ <PortalPanel mobile={false} />
+ </Suspense>
+ </Portal>
+ );
+};
+
+ChatPortal.displayName = 'ChatPortal';
+
+export default ChatPortal;
diff --git a/src/app/[variants]/(main)/chat/components/features/TelemetryNotification.tsx b/src/app/[variants]/(main)/chat/features/TelemetryNotification.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/features/TelemetryNotification.tsx
rename to src/app/[variants]/(main)/chat/features/TelemetryNotification.tsx
diff --git a/src/app/[variants]/(main)/chat/features/TogglePanelButton.tsx b/src/app/[variants]/(main)/chat/features/TogglePanelButton.tsx
deleted file mode 100644
index bfedf3c37ff..00000000000
--- a/src/app/[variants]/(main)/chat/features/TogglePanelButton.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-'use client';
-
-import { ActionIcon, Tooltip } from '@lobehub/ui';
-import { PanelLeftClose, PanelLeftOpen } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { useIsSingleMode } from '@/hooks/useIsSingleMode';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
-import { HotkeyEnum } from '@/types/hotkey';
-
-export const TOOGLE_PANEL_BUTTON_ID = 'toggle-panel-button';
-
-const TogglePanelButton = memo(() => {
- const isSingleMode = useIsSingleMode();
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleLeftPanel));
-
- const { t } = useTranslation(['chat', 'hotkey']);
-
- const showSessionPanel = useGlobalStore(systemStatusSelectors.showSessionPanel);
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
-
- if (isSingleMode) {
- return null
- }
-
- return (
- <Tooltip hotkey={hotkey} title={t('toggleLeftPanel.title', { ns: 'hotkey' })}>
- <ActionIcon
- icon={showSessionPanel ? PanelLeftClose : PanelLeftOpen}
- id={TOOGLE_PANEL_BUTTON_ID}
- onClick={() => {
- updateSystemStatus({
- sessionsWidth: showSessionPanel ? 0 : 320,
- showSessionPanel: !showSessionPanel,
- });
- }}
- size={DESKTOP_HEADER_ICON_SIZE}
- />
- </Tooltip>
- );
-});
-
-export default TogglePanelButton;
diff --git a/src/app/[variants]/(main)/chat/index.tsx b/src/app/[variants]/(main)/chat/index.tsx
index a3813012e04..9bd3eb7a6ae 100644
--- a/src/app/[variants]/(main)/chat/index.tsx
+++ b/src/app/[variants]/(main)/chat/index.tsx
@@ -1,29 +1,32 @@
'use client';
import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
-import { DesktopWorkspace, MobileWorkspace } from './components/WorkspaceLayout';
-import TelemetryNotification from './components/features/TelemetryNotification';
-import PageTitle from './features/PageTitle';
+import MainInterfaceTracker from '@/components/Analytics/MainInterfaceTracker';
-const MobileChatPage = memo(() => {
- return (
- <>
- <PageTitle />
- <MobileWorkspace />
- <TelemetryNotification mobile={true} />
- </>
- );
-});
+import Conversation from './features/Conversation';
+import PageTitle from './features/PageTitle';
+import Portal from './features/Portal';
+import TelemetryNotification from './features/TelemetryNotification';
-const DesktopChatPage = memo(() => {
+const ChatPage = memo(() => {
return (
<>
<PageTitle />
- <DesktopWorkspace />
+ <Flexbox
+ height={'100%'}
+ horizontal
+ style={{ overflow: 'hidden', position: 'relative' }}
+ width={'100%'}
+ >
+ <Conversation />
+ <Portal />
+ </Flexbox>
+ <MainInterfaceTracker />
<TelemetryNotification mobile={false} />
</>
);
});
-export { DesktopChatPage, MobileChatPage };
+export default ChatPage;
diff --git a/src/app/[variants]/(main)/chat/session/features/SkeletonList.tsx b/src/app/[variants]/(main)/chat/session/features/SkeletonList.tsx
deleted file mode 100644
index dc3baa3cd1e..00000000000
--- a/src/app/[variants]/(main)/chat/session/features/SkeletonList.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-'use client';
-
-import { Skeleton } from 'antd';
-import { createStyles } from 'antd-style';
-import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-const useStyles = createStyles(({ css }) => ({
- paragraph: css`
- height: 12px !important;
- margin-block-start: 12px !important;
-
- > li {
- height: 12px !important;
- }
- `,
- title: css`
- height: 14px !important;
- margin-block: 4px 12px !important;
-
- > li {
- height: 14px !important;
- }
- `,
-}));
-
-interface SkeletonListProps {
- count?: number;
-}
-
-const SkeletonList = memo<SkeletonListProps>(({ count = 4 }) => {
- const { styles } = useStyles();
-
- const list = Array.from({ length: count }).fill('');
-
- return (
- <Flexbox gap={8} paddingInline={16}>
- {list.map((_, index) => (
- <Skeleton
- active
- avatar
- key={index}
- paragraph={{ className: styles.paragraph, rows: 1 }}
- title={{ className: styles.title }}
- />
- ))}
- </Flexbox>
- );
-});
-export default SkeletonList;
diff --git a/src/app/[variants]/(main)/chat/session/layout/Desktop/PanelBody.tsx b/src/app/[variants]/(main)/chat/session/layout/Desktop/PanelBody.tsx
deleted file mode 100644
index 41276398ae9..00000000000
--- a/src/app/[variants]/(main)/chat/session/layout/Desktop/PanelBody.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-'use client';
-
-import { ScrollShadow } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { PropsWithChildren, memo } from 'react';
-
-const useStyles = createStyles(
- ({ css }) => css`
- display: flex;
- flex-direction: column;
- gap: 2px;
-
- padding-block: 8px 0;
- padding-inline: 8px;
- `,
-);
-
-const PanelBody = memo<PropsWithChildren>(({ children }) => {
- const { styles } = useStyles();
-
- return (
- <ScrollShadow className={styles} size={8}>
- {children}
- </ScrollShadow>
- );
-});
-
-export default PanelBody;
diff --git a/src/app/[variants]/(main)/chat/session/layout/Desktop/SessionHeader.tsx b/src/app/[variants]/(main)/chat/session/layout/Desktop/SessionHeader.tsx
deleted file mode 100644
index 6085e71b861..00000000000
--- a/src/app/[variants]/(main)/chat/session/layout/Desktop/SessionHeader.tsx
+++ /dev/null
@@ -1,283 +0,0 @@
-'use client';
-
-import { ActionIcon, Dropdown, Icon } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { Bot, MessageSquarePlus, SquarePlus, Users } from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { ProductLogo } from '@/components/Branding';
-import { ChatGroupWizard } from '@/components/ChatGroupWizard';
-import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';
-import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
-import { useActionSWR } from '@/libs/swr';
-import { useChatGroupStore } from '@/store/chatGroup';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/slices/session/selectors';
-import { LobeAgentSession } from '@/types/session';
-
-import TogglePanelButton from '../../../features/TogglePanelButton';
-import SessionSearchBar from '../../features/SessionSearchBar';
-
-export const useStyles = createStyles(({ css, token }) => ({
- logo: css`
- color: ${token.colorText};
- fill: ${token.colorText};
- `,
- top: css`
- position: sticky;
- inset-block-start: 0;
- padding-block-start: 10px;
- `,
-}));
-
-const Header = memo(() => {
- const { styles } = useStyles();
- const { t } = useTranslation('chat');
- const groupTemplates = useGroupTemplates();
- const [createSession, refreshSessions] = useSessionStore((s) => [
- s.createSession,
- s.refreshSessions,
- ]);
- const [createGroup] = useChatGroupStore((s) => [s.createGroup]);
- const { showCreateSession, enableGroupChat } = useServerConfigStore(featureFlagsSelectors);
- const [isGroupWizardOpen, setIsGroupWizardOpen] = useState(false);
-
- // const enableGroupChatInLabs = useUserStore(preferenceSelectors.enableGroupChat);
-
- // We need pass inital member list so we cannot use mutate
- const [isCreatingGroup, setIsCreatingGroup] = useState(false);
-
- const { mutate: mutateAgent, isValidating: isValidatingAgent } = useActionSWR(
- 'session.createSession',
- () => createSession(),
- );
-
- const handleCreateGroupFromTemplate = async (
- templateId: string,
- hostConfig?: { model?: string; provider?: string },
- enableSupervisor?: boolean,
- selectedMemberTitles?: string[],
- ) => {
- // Don't close the modal immediately, keep it open during the process
- setIsCreatingGroup(true);
- try {
- const template = groupTemplates.find((t) => t.id === templateId);
- if (!template) {
- throw new Error(`Template ${templateId} not found`);
- }
-
- // Determine which members to create based on selection
- const membersToCreate =
- typeof selectedMemberTitles === 'undefined'
- ? template.members
- : template.members.filter((m) => selectedMemberTitles.includes(m.title));
-
- // Create assistants for each selected member and get their agent IDs
- const memberAgentIds: string[] = [];
- for (const member of membersToCreate) {
- const sessionId = await createSession(
- {
- config: {
- plugins: member.plugins,
- systemRole: member.systemRole,
- virtual: true,
- },
- meta: {
- avatar: member.avatar,
- backgroundColor: member.backgroundColor,
- description: `${member.title} - ${template.description}`,
- title: member.title,
- },
- },
- false, // Don't switch to each session
- );
-
- // Refresh sessions to ensure we get the latest data
- await refreshSessions();
-
- // Get the agent ID from the created session
- const session = sessionSelectors.getSessionById(sessionId)(useSessionStore.getState());
- if (session && session.type === 'agent') {
- const agentSession = session as LobeAgentSession;
- if (agentSession.config?.id) {
- memberAgentIds.push(agentSession.config.id);
- }
- }
- }
-
- // Wait 1 second delay between member creation and group creation
- await new Promise<void>((resolve) => {
- setTimeout(() => resolve(), 1000);
- });
-
- // Create the group with the agent IDs and host configuration
- console.log('Creating group with hostConfig:', hostConfig);
- console.log(
- 'Mapped config:',
- hostConfig
- ? {
- orchestratorModel: hostConfig.model,
- orchestratorProvider: hostConfig.provider,
- }
- : undefined,
- );
-
- await createGroup(
- {
- config: {
- ...(hostConfig
- ? {
- orchestratorModel: hostConfig.model,
- orchestratorProvider: hostConfig.provider,
- }
- : {}),
- enableSupervisor: enableSupervisor ?? true,
- scene: DEFAULT_CHAT_GROUP_CHAT_CONFIG.scene,
- },
- title: template.title,
- },
- memberAgentIds,
- );
-
- // Close the modal only after all requests are finished successfully
- setIsGroupWizardOpen(false);
- } catch (error) {
- console.error('Failed to create group from template:', error);
- // Keep modal open on error so user can try again
- } finally {
- setIsCreatingGroup(false);
- }
- };
-
- const handleCreateGroupWithMembers = async (
- selectedAgents: string[],
- hostConfig?: { model?: string; provider?: string },
- enableSupervisor?: boolean,
- ) => {
- // Don't close modal immediately for custom group creation either
- setIsCreatingGroup(true);
- try {
- console.log('Creating custom group with hostConfig:', hostConfig);
- console.log(
- 'Mapped config:',
- hostConfig
- ? {
- orchestratorModel: hostConfig.model,
- orchestratorProvider: hostConfig.provider,
- }
- : undefined,
- );
-
- await createGroup(
- {
- config: {
- ...(hostConfig
- ? {
- orchestratorModel: hostConfig.model,
- orchestratorProvider: hostConfig.provider,
- }
- : {}),
- enableSupervisor: enableSupervisor ?? true,
- scene: DEFAULT_CHAT_GROUP_CHAT_CONFIG.scene,
- },
- title: t('defaultGroupChat'),
- },
- selectedAgents,
- );
- // Close modal only after successful creation
- setIsGroupWizardOpen(false);
- } catch (error) {
- console.error('Failed to create group:', error);
- // Keep modal open on error
- } finally {
- setIsCreatingGroup(false);
- }
- };
-
- const handleGroupWizardCancel = () => {
- setIsGroupWizardOpen(false);
- };
-
- return (
- <Flexbox className={styles.top} gap={16} paddingInline={8}>
- <Flexbox align={'flex-start'} horizontal justify={'space-between'}>
- <Flexbox
- align={'center'}
- gap={4}
- horizontal
- style={{
- paddingInlineStart: 4,
- paddingTop: 2,
- }}
- >
- <ProductLogo className={styles.logo} size={36} type={'text'} />
- </Flexbox>
- <Flexbox align={'center'} gap={4} horizontal>
- <TogglePanelButton />
- {showCreateSession &&
- (enableGroupChat ? (
- <Dropdown
- menu={{
- items: [
- {
- icon: <Icon icon={Bot} />,
- key: 'newAgent',
- label: t('newAgent'),
- onClick: () => {
- mutateAgent();
- },
- },
- {
- icon: <Icon icon={Users} />,
- key: 'newGroup',
- label: t('newGroupChat'),
- onClick: () => {
- setIsGroupWizardOpen(true);
- },
- },
- ],
- }}
- trigger={['hover']}
- >
- <ActionIcon
- icon={SquarePlus}
- loading={isValidatingAgent || isCreatingGroup}
- size={DESKTOP_HEADER_ICON_SIZE}
- style={{ flex: 'none' }}
- />
- </Dropdown>
- ) : (
- <ActionIcon
- icon={MessageSquarePlus}
- loading={isValidatingAgent}
- onClick={() => mutateAgent()}
- size={DESKTOP_HEADER_ICON_SIZE}
- style={{ flex: 'none' }}
- title={t('newAgent')}
- tooltipProps={{
- placement: 'bottom',
- }}
- />
- ))}
- </Flexbox>
- </Flexbox>
- <SessionSearchBar />
-
- {enableGroupChat && (
- <ChatGroupWizard
- isCreatingFromTemplate={isCreatingGroup}
- onCancel={handleGroupWizardCancel}
- onCreateCustom={handleCreateGroupWithMembers}
- onCreateFromTemplate={handleCreateGroupFromTemplate}
- open={isGroupWizardOpen}
- />
- )}
- </Flexbox>
- );
-});
-
-export default Header;
diff --git a/src/app/[variants]/(main)/chat/session/layout/Desktop/index.tsx b/src/app/[variants]/(main)/chat/session/layout/Desktop/index.tsx
deleted file mode 100644
index c22a786de25..00000000000
--- a/src/app/[variants]/(main)/chat/session/layout/Desktop/index.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { PropsWithChildren } from 'react';
-
-import PanelBody from './PanelBody';
-import Header from './SessionHeader';
-
-const DesktopLayout = ({ children }: PropsWithChildren) => {
- return (
- <>
- <Header />
- <PanelBody>{children}</PanelBody>
- {/* ↓ cloud slot ↓ */}
-
- {/* ↑ cloud slot ↑ */}
- </>
- );
-};
-
-export default DesktopLayout;
diff --git a/src/app/[variants]/(main)/chat/settings/_layout/Desktop/Header.tsx b/src/app/[variants]/(main)/chat/settings/_layout/Desktop/Header.tsx
deleted file mode 100644
index 85e22f9627b..00000000000
--- a/src/app/[variants]/(main)/chat/settings/_layout/Desktop/Header.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-'use client';
-
-import { ChatHeader, ChatHeaderTitle } from '@lobehub/ui/chat';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
-
-import { pathString } from '@/utils/url';
-
-import HeaderContent from '../../features/HeaderContent';
-
-const Header = memo(() => {
- const { t } = useTranslation('setting');
- const navigate = useNavigate();
-
- return (
- <ChatHeader
- left={<ChatHeaderTitle title={t('header.session')} />}
- onBackClick={() => navigate(pathString('/chat', { search: location.search }))}
- right={<HeaderContent />}
- showBackButton
- />
- );
-});
-
-export default Header;
diff --git a/src/app/[variants]/(main)/chat/settings/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/chat/settings/_layout/Desktop/index.tsx
deleted file mode 100644
index 01ce35f8ccb..00000000000
--- a/src/app/[variants]/(main)/chat/settings/_layout/Desktop/index.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { PropsWithChildren } from 'react';
-
-import SafeSpacing from '@/components/SafeSpacing';
-import { HEADER_HEIGHT } from '@/const/layoutTokens';
-import Footer from '@/features/Setting/Footer';
-import SettingContainer from '@/features/Setting/SettingContainer';
-
-import Header from './Header';
-
-const Layout = ({ children }: PropsWithChildren) => (
- <>
- <Header />
- <SettingContainer addonAfter={<Footer />} addonBefore={<SafeSpacing height={HEADER_HEIGHT} />}>
- {children}
- </SettingContainer>
- </>
-);
-
-Layout.displayName = 'DesktopSessionSettingsLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/chat/settings/features/HeaderContent.tsx b/src/app/[variants]/(main)/chat/settings/features/HeaderContent.tsx
deleted file mode 100644
index 30374c8ac92..00000000000
--- a/src/app/[variants]/(main)/chat/settings/features/HeaderContent.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import { memo } from 'react';
-
-import SmartAgentActionButton from './SmartAgentActionButton';
-
-export const HeaderContent = memo<{ mobile?: boolean; modal?: boolean }>(({ modal }) => {
- return <SmartAgentActionButton modal={modal} />;
-});
-
-export default HeaderContent;
diff --git a/src/app/[variants]/(main)/chat/settings/features/PublishResultModal/index.tsx b/src/app/[variants]/(main)/chat/settings/features/PublishResultModal/index.tsx
deleted file mode 100644
index 3f93ae346dc..00000000000
--- a/src/app/[variants]/(main)/chat/settings/features/PublishResultModal/index.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-'use client';
-
-import { CheckCircleOutlined } from '@ant-design/icons';
-import { Button, Modal, Space } from 'antd';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
-
-interface PublishResultModalProps {
- identifier?: string;
- onCancel: () => void;
- open: boolean;
-}
-
-const PublishResultModal = memo<PublishResultModalProps>(({ identifier, onCancel, open }) => {
- const navigate = useNavigate();
- const { t } = useTranslation('setting');
- const { t: tCommon } = useTranslation('common');
-
- const handleGoToMarket = () => {
- if (identifier) {
- navigate(`/discover/assistant/${identifier}`);
- }
- onCancel();
- };
-
- const successContent = (
- <div style={{ padding: '20px 0', textAlign: 'center' }}>
- <CheckCircleOutlined
- style={{
- color: '#52c41a',
- display: 'block',
- fontSize: '48px',
- marginBottom: '16px',
- }}
- />
- <div style={{ fontSize: '16px', marginBottom: '24px' }}>
- {t('marketPublish.resultModal.message')}
- </div>
- <Space>
- <Button onClick={onCancel}>{tCommon('cancel')}</Button>
- <Button onClick={handleGoToMarket} type="primary">
- {t('marketPublish.resultModal.view')}
- </Button>
- </Space>
- </div>
- );
-
- return (
- <Modal
- centered
- closable={false}
- footer={null}
- onCancel={onCancel}
- open={open}
- title={null}
- width={480}
- >
- {successContent}
- </Modal>
- );
-});
-
-export default PublishResultModal;
diff --git a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishButton.tsx b/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishButton.tsx
deleted file mode 100644
index 30d9b7d3503..00000000000
--- a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishButton.tsx
+++ /dev/null
@@ -1,194 +0,0 @@
-import { ActionIcon, Button } from '@lobehub/ui';
-import { message } from 'antd';
-import { LogIn, Share2, Upload } from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { checkOwnership } from '@/hooks/useAgentOwnershipCheck';
-import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
-import { resolveMarketAuthError } from '@/layout/AuthProvider/MarketAuth/errors';
-import { useServerConfigStore } from '@/store/serverConfig';
-
-import MarketPublishModal, { type MarketPublishAction } from './MarketPublishModal';
-
-interface MarketPublishButtonProps {
- action: MarketPublishAction;
- marketIdentifier?: string;
- modal?: boolean;
-}
-
-const MarketPublishButton = memo<MarketPublishButtonProps>(
- ({ action, marketIdentifier, modal }) => {
- const { t: tSetting } = useTranslation('setting');
- const { t: tMarketAuth } = useTranslation('marketAuth');
- const mobile = useServerConfigStore((s) => s.isMobile);
- const [openState, setOpenState] = useState<{ submit: boolean; upload: boolean }>({
- submit: false,
- upload: false,
- });
- const { isAuthenticated, isLoading, session, signIn } = useMarketAuth();
-
- const buttonCopy = useMemo(() => {
- if (action === 'upload') {
- return {
- authenticated: {
- icon: Upload,
- text: tSetting('marketPublish.upload.button'),
- title: tSetting('marketPublish.upload.tooltip'),
- },
- successMessage: tMarketAuth('messages.success.upload'),
- unauthenticated: {
- icon: LogIn,
- text: tSetting('marketPublish.upload.button'),
- title: tSetting('marketPublish.upload.tooltip'),
- },
- } as const;
- }
-
- const submitText = tSetting('submitAgentModal.tooltips');
-
- return {
- authenticated: {
- icon: Share2,
- text: submitText,
- title: submitText,
- },
- successMessage: tMarketAuth('messages.success.submit'),
- unauthenticated: {
- icon: LogIn,
- text: tSetting('marketPublish.submit.button'),
- title: tSetting('marketPublish.submit.tooltip'),
- },
- } as const;
- }, [action, tMarketAuth, tSetting]);
-
- const openModal = useCallback((target: MarketPublishAction) => {
- setOpenState((prev) => ({ ...prev, [target]: true }));
- }, []);
-
- const closeModal = useCallback((target: MarketPublishAction) => {
- setOpenState((prev) => ({ ...prev, [target]: false }));
- }, []);
-
- const handleButtonClick = useCallback(async () => {
- console.log(
- `[MarketPublishButton][${action}] Button clicked, isAuthenticated:`,
- isAuthenticated,
- );
-
- if (isAuthenticated) {
- console.log(`[MarketPublishButton][${action}] User is authenticated, opening modal`);
- openModal(action);
- return;
- }
-
- console.log(
- `[MarketPublishButton][${action}] User not authenticated, starting authorization`,
- );
- try {
- const accountId = await signIn();
-
- let targetAction: MarketPublishAction = action;
-
- if (marketIdentifier && accountId !== null) {
- let accessToken = session?.accessToken;
-
- if (!accessToken && typeof window !== 'undefined') {
- const storedSession = sessionStorage.getItem('market_auth_session');
- if (storedSession) {
- try {
- const parsed = JSON.parse(storedSession) as { accessToken?: string };
- accessToken = parsed.accessToken;
- } catch (parseError) {
- console.error('[MarketPublishButton] Failed to parse stored session:', parseError);
- }
- }
- }
-
- if (accessToken) {
- try {
- const isOwner = await checkOwnership({
- accessToken,
- accountId,
- marketIdentifier,
- skipCache: true,
- });
-
- targetAction = isOwner ? 'upload' : 'submit';
- } catch (ownershipError) {
- console.error('[MarketPublishButton] Failed to confirm ownership:', ownershipError);
- }
- }
- }
-
- openModal(targetAction);
- } catch (error) {
- console.error(`[MarketPublishButton][${action}] Authorization failed:`, error);
- const normalizedError = resolveMarketAuthError(error);
- message.error({
- content: tMarketAuth(`errors.${normalizedError.code}`),
- key: 'market-auth',
- });
- }
- }, [
- action,
- buttonCopy.successMessage,
- isAuthenticated,
- marketIdentifier,
- openModal,
- session?.accessToken,
- signIn,
- tMarketAuth,
- ]);
-
- const buttonProps = isAuthenticated ? buttonCopy.authenticated : buttonCopy.unauthenticated;
-
- return (
- <>
- {modal ? (
- <Button
- block
- disabled={isLoading}
- icon={buttonProps.icon}
- loading={isLoading}
- onClick={handleButtonClick}
- variant={'filled'}
- >
- {buttonProps.text}
- </Button>
- ) : (
- <ActionIcon
- icon={buttonProps.icon}
- loading={isLoading}
- onClick={handleButtonClick}
- size={HEADER_ICON_SIZE(mobile)}
- title={buttonProps.title}
- />
- )}
-
- {isAuthenticated && (
- <>
- <MarketPublishModal
- action="submit"
- onCancel={() => closeModal('submit')}
- onSuccess={() => closeModal('submit')}
- open={openState.submit}
- />
-
- <MarketPublishModal
- action="upload"
- onCancel={() => closeModal('upload')}
- onSuccess={() => closeModal('upload')}
- open={openState.upload}
- />
- </>
- )}
- </>
- );
- },
-);
-
-MarketPublishButton.displayName = 'MarketPublishButton';
-
-export default MarketPublishButton;
diff --git a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishModal.tsx b/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishModal.tsx
deleted file mode 100644
index 74cfba29328..00000000000
--- a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/MarketPublishModal.tsx
+++ /dev/null
@@ -1,376 +0,0 @@
-'use client';
-
-import { ModalForm, ProFormText } from '@ant-design/pro-components';
-import { AgentItemDetail } from '@lobehub/market-sdk';
-import { type ModalProps } from '@lobehub/ui';
-import { Col, Row, Spin } from 'antd';
-import isEqual from 'fast-deep-equal';
-import { memo, useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { message } from '@/components/AntdStaticMethods';
-import { useTokenCount } from '@/hooks/useTokenCount';
-import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
-import { marketApiService } from '@/services/marketApi';
-import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
-import { useGlobalStore } from '@/store/global';
-import { globalGeneralSelectors } from '@/store/global/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors } from '@/store/session/selectors';
-
-import AgentInfoDescription from '../AgentInfoDescription';
-import PublishResultModal from '../PublishResultModal';
-
-export type MarketPublishAction = 'submit' | 'upload';
-
-interface MarketPublishModalProps extends ModalProps {
- action: MarketPublishAction;
- onSuccess?: () => void;
-}
-
-interface MarketPublishFormValues {
- changelog: string;
- identifier?: string;
-}
-
-const MarketPublishModal = memo<MarketPublishModalProps>(
- ({ action, open, onCancel, onSuccess }) => {
- const { t } = useTranslation('setting');
- const isSubmit = action === 'submit';
- const isUpload = action === 'upload';
-
- const marketAuth = useMarketAuth();
- const { isAuthenticated } = marketAuth;
- const meta = useSessionStore(sessionMetaSelectors.currentAgentMeta, isEqual);
- const updateSessionMeta = useSessionStore((s) => s.updateSessionMeta);
-
- const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);
- const language = useGlobalStore(globalGeneralSelectors.currentLanguage);
- const agentConfig = useAgentStore(agentSelectors.currentAgentConfig);
- const chatConfig = useAgentStore(agentChatConfigSelectors.currentChatConfig);
- const plugins = useAgentStore(agentSelectors.currentAgentPlugins);
- const ttsConfig = useAgentStore(agentSelectors.currentAgentTTS);
- const model = useAgentStore(agentSelectors.currentAgentModel);
- const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
- const knowledgeBases = useAgentStore(agentSelectors.currentAgentKnowledgeBases);
- const files = useAgentStore(agentSelectors.currentAgentFiles);
-
- const [remoteAgentData, setRemoteAgentData] = useState<
- (AgentItemDetail & { description?: string; name?: string; title?: string }) | null
- >(null);
- const [loadingRemoteData, setLoadingRemoteData] = useState(false);
- const [showResultModal, setShowResultModal] = useState(false);
- const [publishResult, setPublishResult] = useState<{ identifier?: string }>({});
-
- const messageKey = isSubmit ? 'submit' : 'upload-version';
- const loadingMessage = isSubmit
- ? t('marketPublish.modal.loading.submit')
- : t('marketPublish.modal.loading.upload');
- const submitButtonText = t('marketPublish.modal.submitButton');
- const modalTitle = isSubmit
- ? t('marketPublish.modal.title.submit')
- : t('marketPublish.modal.title.upload');
-
- useEffect(() => {
- if (!isUpload) return;
- const marketIdentifier = meta?.marketIdentifier;
- const accessToken = marketAuth.getAccessToken();
- if (!open || !isAuthenticated || !accessToken || !marketIdentifier) return;
-
- let cancelled = false;
-
- const run = async () => {
- try {
- setLoadingRemoteData(true);
- marketApiService.setAccessToken(accessToken);
- const data = await marketApiService.getAgentDetail(marketIdentifier);
- if (!cancelled) {
- console.log('data', data);
- setRemoteAgentData(data);
- }
- } catch (error) {
- console.error('Failed to fetch remote agent data:', error);
- if (!cancelled) {
- message.error(t('marketPublish.modal.messages.fetchRemoteFailed'));
- }
- } finally {
- if (!cancelled) {
- setLoadingRemoteData(false);
- }
- }
- };
-
- void run();
-
- return () => {
- cancelled = true;
- };
- }, [isAuthenticated, isUpload, marketAuth, meta?.marketIdentifier, open]);
-
- const tokenUsage = useTokenCount(systemRole);
-
- const handleSubmit = useCallback(
- async (values: MarketPublishFormValues) => {
- const accessToken = marketAuth.getAccessToken();
- if (!isAuthenticated || !accessToken) {
- message.error(t('marketPublish.modal.messages.notAuthenticated'));
- return false;
- }
-
- const changelog = values.changelog?.trim();
- if (!changelog) {
- message.error({ content: t('marketPublish.modal.changelog.required'), key: messageKey });
- return false;
- }
-
- let identifier = meta?.marketIdentifier;
-
- try {
- message.loading({ content: loadingMessage, key: messageKey });
- marketApiService.setAccessToken(accessToken);
-
- if (isSubmit) {
- identifier = values.identifier?.trim();
- if (!identifier) {
- message.error({
- content: t('marketPublish.modal.identifier.required'),
- key: messageKey,
- });
- return false;
- }
-
- try {
- await marketApiService.getAgentDetail(identifier);
- } catch {
- const createPayload: Record<string, unknown> = {
- identifier,
- name: meta?.title || '',
- };
- await marketApiService.createAgent(createPayload as any);
- }
- } else if (!identifier) {
- message.error({
- content: t('marketPublish.modal.messages.missingIdentifier'),
- key: messageKey,
- });
- return false;
- }
-
- const versionPayload = {
- avatar: meta?.avatar,
- changelog,
- config: {
- chatConfig: {
- displayMode: chatConfig?.displayMode,
- enableHistoryCount: chatConfig?.enableHistoryCount,
- historyCount: chatConfig?.historyCount,
- maxTokens: agentConfig?.params?.max_tokens,
- searchMode: chatConfig?.searchMode,
- temperature: agentConfig?.params?.temperature,
- topP: agentConfig?.params?.top_p,
- },
- description: meta?.description,
- locale: language,
- model: {
- model,
- parameters: agentConfig?.params,
- provider,
- },
- plugins:
- plugins?.map((plugin) => {
- if (typeof plugin === 'string') {
- return plugin;
- } else {
- return null;
- }
- }) || [],
- systemRole: systemRole,
- },
- description: meta?.description || '',
- identifier: identifier,
- name: meta?.title || '',
- tags: meta?.tags,
- tokenUsage: tokenUsage,
- };
-
- try {
- await marketApiService.createAgentVersion(versionPayload);
- } catch (versionError) {
- const errorMessage = versionError instanceof Error ? versionError.message : '未知错误';
- message.error({
- content: t('marketPublish.modal.messages.createVersionFailed', {
- message: errorMessage,
- }),
- key: messageKey,
- });
- return false;
- }
-
- if (isSubmit) {
- updateSessionMeta({ marketIdentifier: identifier });
- }
-
- setPublishResult({ identifier });
- setShowResultModal(true);
-
- message.destroy(messageKey);
- onSuccess?.();
- return true;
- } catch (error) {
- console.error('Market publish failed:', error);
- const errorMessage = error instanceof Error ? error.message : '发布失败';
- message.error({
- content: t('marketPublish.modal.messages.publishFailed', { message: errorMessage }),
- key: messageKey,
- });
- return false;
- }
- },
- [
- agentConfig?.params,
- chatConfig?.displayMode,
- chatConfig?.enableHistoryCount,
- chatConfig?.historyCount,
- chatConfig?.searchMode,
- isAuthenticated,
- isSubmit,
- language,
- marketAuth,
- meta?.avatar,
- meta?.description,
- meta?.marketIdentifier,
- meta?.tags,
- meta?.title,
- messageKey,
- loadingMessage,
- model,
- onSuccess,
- plugins,
- provider,
- systemRole,
- tokenUsage,
- updateSessionMeta,
- ],
- );
-
- return (
- <>
- <ModalForm<MarketPublishFormValues>
- modalProps={{
- bodyStyle: { height: '70vh', overflow: 'auto' },
- destroyOnClose: true,
- onCancel,
- style: { minWidth: 750 },
- }}
- onFinish={handleSubmit}
- open={open}
- submitter={{
- resetButtonProps: {
- style: { display: 'none' },
- },
- submitButtonProps: {
- children: submitButtonText,
- },
- }}
- title={modalTitle}
- width="80vw"
- >
- {isSubmit && (
- <ProFormText
- extra={t('marketPublish.modal.identifier.extra')}
- label={t('marketPublish.modal.identifier.label')}
- name="identifier"
- placeholder={t('marketPublish.modal.identifier.placeholder')}
- rules={[
- { message: t('marketPublish.modal.identifier.required'), required: true },
- {
- message: t('marketPublish.modal.identifier.patternError'),
- pattern: /^[\da-z-]+$/,
- },
- { max: 50, message: t('marketPublish.modal.identifier.lengthError'), min: 3 },
- ]}
- />
- )}
-
- <ProFormText
- extra={t('marketPublish.modal.changelog.extra')}
- label={t('marketPublish.modal.changelog.label')}
- name="changelog"
- placeholder={t('marketPublish.modal.changelog.placeholder')}
- rules={[
- { message: t('marketPublish.modal.changelog.required'), required: true },
- { max: 500, message: t('marketPublish.modal.changelog.maxLengthError') },
- ]}
- />
-
- {isUpload ? (
- <Row gutter={24}>
- <Col span={12}>
- <div style={{ border: '1px solid #d9d9d9', borderRadius: '6px', padding: '16px' }}>
- <h3 style={{ marginBottom: '16px', textAlign: 'center' }}>
- {t('marketPublish.modal.comparison.remote')}
- </h3>
- {loadingRemoteData ? (
- <div style={{ padding: '40px', textAlign: 'center' }}>
- <Spin size="large" />
- <div style={{ marginTop: '16px' }}>
- {t('marketPublish.modal.loading.fetchingRemote')}
- </div>
- </div>
- ) : (
- <AgentInfoDescription isRemote={true} meta={remoteAgentData || undefined} />
- )}
- </div>
- </Col>
- <Col span={12}>
- <div style={{ border: '1px solid #d9d9d9', borderRadius: '6px', padding: '16px' }}>
- <h3 style={{ marginBottom: '16px', textAlign: 'center' }}>
- {t('marketPublish.modal.comparison.local')}
- </h3>
- <AgentInfoDescription
- agentConfig={agentConfig}
- chatConfig={chatConfig}
- files={files}
- knowledgeBases={knowledgeBases}
- meta={meta}
- model={model}
- plugins={plugins}
- provider={provider}
- systemRole={systemRole}
- ttsConfig={ttsConfig}
- />
- </div>
- </Col>
- </Row>
- ) : (
- <div style={{ marginTop: 24 }}>
- <AgentInfoDescription
- agentConfig={agentConfig}
- chatConfig={chatConfig}
- files={files}
- knowledgeBases={knowledgeBases}
- meta={meta}
- model={model}
- plugins={plugins}
- provider={provider}
- systemRole={systemRole}
- ttsConfig={ttsConfig}
- />
- </div>
- )}
- </ModalForm>
-
- <PublishResultModal
- identifier={publishResult.identifier}
- onCancel={() => setShowResultModal(false)}
- open={showResultModal}
- />
- </>
- );
- },
-);
-
-MarketPublishModal.displayName = 'MarketPublishModal';
-
-export default MarketPublishModal;
diff --git a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/index.tsx b/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/index.tsx
deleted file mode 100644
index 5240a924c78..00000000000
--- a/src/app/[variants]/(main)/chat/settings/features/SmartAgentActionButton/index.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { Button } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
-import { Loader2 } from 'lucide-react';
-import { memo, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useAgentOwnershipCheck } from '@/hooks/useAgentOwnershipCheck';
-import { useSessionStore } from '@/store/session';
-import { sessionMetaSelectors } from '@/store/session/selectors';
-
-import MarketPublishButton from './MarketPublishButton';
-
-interface SmartAgentActionButtonProps {
- modal?: boolean;
-}
-
-/**
- * 智能Agent操作按钮组件
- * 根据Agent的所有权自动决定显示"提交新Agent"还是"上传新版本"按钮
- */
-const SmartAgentActionButton = memo<SmartAgentActionButtonProps>(({ modal }) => {
- const { t } = useTranslation('setting');
- const meta = useSessionStore(sessionMetaSelectors.currentAgentMeta, isEqual);
- const { isOwnAgent } = useAgentOwnershipCheck(meta?.marketIdentifier);
-
- const buttonType = useMemo(() => {
- if (!meta?.marketIdentifier) {
- return 'submit';
- }
-
- if (isOwnAgent === null) {
- return 'loading';
- }
-
- if (isOwnAgent === true) {
- return 'upload';
- }
-
- return 'submit';
- }, [meta?.marketIdentifier, isOwnAgent]);
-
- switch (buttonType) {
- case 'upload': {
- return (
- <MarketPublishButton
- action="upload"
- marketIdentifier={meta?.marketIdentifier}
- modal={modal}
- />
- );
- }
-
- case 'submit': {
- return (
- <MarketPublishButton
- action="submit"
- marketIdentifier={meta?.marketIdentifier}
- modal={modal}
- />
- );
- }
-
- default: {
- return (
- <Button block={Boolean(modal)} disabled icon={Loader2} loading variant={'filled'}>
- {t('checkingPermissions')}
- </Button>
- );
- }
- }
-});
-
-SmartAgentActionButton.displayName = 'SmartAgentActionButton';
-
-export default SmartAgentActionButton;
diff --git a/src/app/[variants]/(main)/group/_layout/GroupIdSync.tsx b/src/app/[variants]/(main)/group/_layout/GroupIdSync.tsx
new file mode 100644
index 00000000000..f7cb1f02604
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/GroupIdSync.tsx
@@ -0,0 +1,26 @@
+import { useUnmount } from 'ahooks';
+import { useParams } from 'react-router-dom';
+import { createStoreUpdater } from 'zustand-utils';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+
+const GroupIdSync = () => {
+ const useAgentGroupStoreUpdater = createStoreUpdater(useAgentGroupStore);
+ const useChatStoreUpdater = createStoreUpdater(useChatStore);
+ const params = useParams<{ gid?: string }>();
+
+ // Sync groupId to agentGroupStore and chatStore
+ useAgentGroupStoreUpdater('activeGroupId', params.gid);
+ useChatStoreUpdater('activeGroupId', params.gid);
+
+ // Clear activeGroupId when unmounting (leaving group page)
+ useUnmount(() => {
+ useAgentGroupStore.setState({ activeGroupId: undefined });
+ useChatStore.setState({ activeGroupId: undefined, activeTopicId: undefined });
+ });
+
+ return null;
+};
+
+export default GroupIdSync;
diff --git a/src/app/[variants]/(main)/group/_layout/RegisterHotkeys.tsx b/src/app/[variants]/(main)/group/_layout/RegisterHotkeys.tsx
new file mode 100644
index 00000000000..149a31058c0
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/RegisterHotkeys.tsx
@@ -0,0 +1,13 @@
+'use client';
+
+import { memo } from 'react';
+
+import { useRegisterChatHotkeys } from '@/hooks/useHotkeys';
+
+const RegisterHotkeys = memo(() => {
+ useRegisterChatHotkeys();
+
+ return '';
+});
+
+export default RegisterHotkeys;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsx
new file mode 100644
index 00000000000..634c9c9eae2
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/AgentItem.tsx
@@ -0,0 +1,132 @@
+'use client';
+
+import { Avatar } from '@lobehub/ui';
+import { useHover } from 'ahooks';
+import { Checkbox, Typography } from 'antd';
+import { createStyles } from 'antd-style';
+import { X } from 'lucide-react';
+import { memo, useRef } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { DEFAULT_AVATAR } from '@/const/meta';
+
+import { useAgentSelectionStore } from './store';
+
+const { Text } = Typography;
+
+const useStyles = createStyles(({ css, token }) => ({
+ item: css`
+ cursor: pointer;
+
+ margin-block: 1px;
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-radius: ${token.borderRadius}px;
+
+ transition: background 0.2s ease;
+
+ &:hover {
+ background: ${token.colorFillTertiary};
+ }
+ `,
+ removeButton: css`
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ height: 20px;
+ border-radius: 4px;
+
+ color: ${token.colorTextTertiary};
+
+ transition: all 0.2s ease;
+
+ &:hover {
+ color: ${token.colorText};
+ background: ${token.colorFillSecondary};
+ }
+ `,
+ title: css`
+ overflow: hidden;
+ flex: 1;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+export interface AgentItemData {
+ avatar: string | null;
+ backgroundColor: string | null;
+ description: string | null;
+ id: string;
+ title: string | null;
+}
+
+interface AgentItemProps {
+ agent: AgentItemData;
+ defaultTitle: string;
+ showCheckbox?: boolean;
+ showRemove?: boolean;
+}
+
+const AgentItem = memo<AgentItemProps>(({ agent, defaultTitle, showCheckbox, showRemove }) => {
+ const ref = useRef(null);
+ const isHovering = useHover(ref);
+ const { styles } = useStyles();
+
+ const isSelected = useAgentSelectionStore((s) => s.selectedAgentIds.includes(agent.id));
+ const toggleAgent = useAgentSelectionStore((s) => s.toggleAgent);
+ const removeAgent = useAgentSelectionStore((s) => s.removeAgent);
+
+ const title = agent.title || defaultTitle;
+ const avatar = agent.avatar || DEFAULT_AVATAR;
+ const avatarBackground = agent.backgroundColor ?? undefined;
+
+ const handleClick = () => {
+ toggleAgent(agent.id);
+ };
+
+ const handleRemove = (e: { stopPropagation: () => void }) => {
+ e.stopPropagation();
+ removeAgent(agent.id);
+ };
+
+ return (
+ <div
+ className={styles.item}
+ onClick={showCheckbox ? handleClick : undefined}
+ ref={ref}
+ style={{ cursor: showCheckbox ? 'pointer' : 'default' }}
+ >
+ <Flexbox align="center" gap={8} horizontal width="100%">
+ {showCheckbox && (
+ <Checkbox
+ checked={isSelected}
+ onChange={handleClick}
+ onClick={(e) => e.stopPropagation()}
+ />
+ )}
+ <Avatar
+ animation={isHovering}
+ avatar={avatar}
+ background={avatarBackground}
+ shape="circle"
+ size={28}
+ />
+ <Text className={styles.title} ellipsis>
+ {title}
+ </Text>
+ {showRemove && (
+ <div className={styles.removeButton} onClick={handleRemove}>
+ <X size={14} />
+ </div>
+ )}
+ </Flexbox>
+ </div>
+ );
+});
+
+export default AgentItem;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsx
new file mode 100644
index 00000000000..3877e69191e
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/AvailableAgentList.tsx
@@ -0,0 +1,98 @@
+'use client';
+
+import { SearchBar, Skeleton } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { type ChangeEvent, memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import { Virtuoso } from 'react-virtuoso';
+
+import AgentSelectionEmpty from '@/features/AgentSelectionEmpty';
+
+import AgentItem, { type AgentItemData } from './AgentItem';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ user-select: none;
+
+ overflow: hidden;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+
+ padding-block: ${token.paddingSM}px 0;
+ padding-inline: ${token.paddingSM}px;
+ border-inline-end: 1px solid ${token.colorBorderSecondary};
+ `,
+}));
+
+interface AvailableAgentListProps {
+ agents: AgentItemData[];
+ isLoading: boolean;
+}
+
+const AvailableAgentList = memo<AvailableAgentListProps>(({ agents, isLoading }) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const { styles } = useStyles();
+ const [searchTerm, setSearchTerm] = useState('');
+
+ const defaultTitle = useMemo(() => t('defaultSession', { ns: 'common' }), [t]);
+
+ const handleSearchChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
+ setSearchTerm(e.target.value);
+ }, []);
+
+ // Filter agents based on search term (matches title or description)
+ const filteredAgents = useMemo(() => {
+ if (!searchTerm.trim()) return agents;
+
+ const searchLower = searchTerm.toLowerCase();
+ return agents.filter((agent) => {
+ const title = agent.title || '';
+ const description = agent.description || '';
+ return (
+ title.toLowerCase().includes(searchLower) || description.toLowerCase().includes(searchLower)
+ );
+ });
+ }, [agents, searchTerm]);
+
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ <SearchBar
+ allowClear
+ onChange={handleSearchChange}
+ placeholder={t('memberSelection.searchAgents')}
+ value={searchTerm}
+ variant="filled"
+ />
+
+ <Flexbox flex={1} style={{ minHeight: 0 }}>
+ {isLoading ? (
+ <Flexbox gap={8} padding={8}>
+ <Skeleton active paragraph={{ rows: 1 }} title={false} />
+ <Skeleton active paragraph={{ rows: 1 }} title={false} />
+ <Skeleton active paragraph={{ rows: 1 }} title={false} />
+ </Flexbox>
+ ) : filteredAgents.length === 0 ? (
+ <AgentSelectionEmpty
+ search={Boolean(searchTerm)}
+ variant={searchTerm ? 'empty' : 'noAvailable'}
+ />
+ ) : (
+ <Virtuoso
+ itemContent={(index) => {
+ const agent = filteredAgents[index];
+ return (
+ <AgentItem agent={agent} defaultTitle={defaultTitle} key={agent.id} showCheckbox />
+ );
+ }}
+ style={{ flex: 1 }}
+ totalCount={filteredAgents.length}
+ />
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default AvailableAgentList;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/SelectedAgentList.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/SelectedAgentList.tsx
new file mode 100644
index 00000000000..d4ca212a326
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/SelectedAgentList.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { createStyles } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import AgentSelectionEmpty from '@/features/AgentSelectionEmpty';
+
+import AgentItem, { type AgentItemData } from './AgentItem';
+import { useAgentSelectionStore } from './store';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow-y: auto;
+ flex: 1;
+ padding: ${token.paddingSM}px;
+ `,
+ title: css`
+ font-size: 12px;
+ font-weight: 500;
+ color: ${token.colorTextSecondary};
+ `,
+}));
+
+interface SelectedAgentListProps {
+ agents: AgentItemData[];
+}
+
+const SelectedAgentList = memo<SelectedAgentListProps>(({ agents }) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const { styles } = useStyles();
+
+ const selectedAgentIds = useAgentSelectionStore((s) => s.selectedAgentIds);
+
+ const defaultTitle = useMemo(() => t('defaultSession', { ns: 'common' }), [t]);
+
+ // Get selected agents data
+ const selectedAgents = useMemo(() => {
+ return selectedAgentIds
+ .map((id) => agents.find((a) => a.id === id))
+ .filter((a): a is AgentItemData => a !== undefined);
+ }, [agents, selectedAgentIds]);
+
+ if (selectedAgents.length === 0) {
+ return (
+ <Flexbox className={styles.container} flex={1}>
+ <AgentSelectionEmpty variant="noSelected" />
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox className={styles.container} gap={4}>
+ <div className={styles.title}>
+ {t('memberSelection.selectedAgents', { count: selectedAgents.length })}
+ </div>
+ <Flexbox>
+ {selectedAgents.map((agent) => (
+ <AgentItem agent={agent} defaultTitle={defaultTitle} key={agent.id} showRemove />
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default SelectedAgentList;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx
new file mode 100644
index 00000000000..016b0ddc815
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/index.tsx
@@ -0,0 +1,122 @@
+'use client';
+
+import { Modal } from '@lobehub/ui';
+import { Button } from 'antd';
+import { createStyles } from 'antd-style';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import useSWR from 'swr';
+
+import { agentService } from '@/services/agent';
+
+import type { AgentItemData } from './AgentItem';
+import AvailableAgentList from './AvailableAgentList';
+import SelectedAgentList from './SelectedAgentList';
+import { useAgentSelectionStore } from './store';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ display: flex;
+ flex-direction: row;
+
+ height: 500px;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: ${token.borderRadius}px;
+ `,
+ rightColumn: css`
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ `,
+}));
+
+export interface AddGroupMemberModalProps {
+ existingMembers?: string[];
+ groupId: string;
+ onCancel: () => void;
+ onConfirm: (selectedAgents: string[]) => void | Promise<void>;
+ open: boolean;
+}
+
+const AddGroupMemberModal = memo<AddGroupMemberModalProps>(
+ ({ existingMembers = [], onCancel, onConfirm, open }) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const { styles } = useStyles();
+
+ const selectedAgentIds = useAgentSelectionStore((s) => s.selectedAgentIds);
+ const clearSelection = useAgentSelectionStore((s) => s.clearSelection);
+
+ // Fetch agents from the new API (non-virtual agents only)
+ const { data: allAgents = [], isLoading: isLoadingAgents } = useSWR(
+ open ? 'queryAgents' : null,
+ () => agentService.queryAgents(),
+ );
+
+ // Filter out existing members
+ const availableAgents = useMemo<AgentItemData[]>(() => {
+ return allAgents.filter((agent) => !existingMembers.includes(agent.id));
+ }, [allAgents, existingMembers]);
+
+ // Clear selection when modal closes
+ useEffect(() => {
+ if (!open) {
+ clearSelection();
+ }
+ }, [open, clearSelection]);
+
+ const [isAdding, setIsAdding] = useState(false);
+
+ const handleConfirm = async () => {
+ try {
+ setIsAdding(true);
+ await onConfirm(selectedAgentIds);
+ clearSelection();
+ } catch (error) {
+ console.error('Failed to add members:', error);
+ } finally {
+ setIsAdding(false);
+ }
+ };
+
+ const handleCancel = () => {
+ clearSelection();
+ onCancel();
+ };
+
+ const isConfirmDisabled = selectedAgentIds.length === 0 || isAdding;
+
+ return (
+ <Modal
+ allowFullscreen
+ footer={
+ <Flexbox gap={8} horizontal justify="end">
+ <Button onClick={handleCancel}>{t('cancel', { ns: 'common' })}</Button>
+ <Button
+ disabled={isConfirmDisabled}
+ loading={isAdding}
+ onClick={handleConfirm}
+ type="primary"
+ >
+ {t('memberSelection.addMember')} ({selectedAgentIds.length})
+ </Button>
+ </Flexbox>
+ }
+ onCancel={handleCancel}
+ open={open}
+ title={t('memberSelection.addMember')}
+ width={800}
+ >
+ <Flexbox className={styles.container} horizontal>
+ {/* Left Column - Available Agents */}
+ <AvailableAgentList agents={availableAgents} isLoading={isLoadingAgents} />
+
+ {/* Right Column - Selected Agents */}
+ <SelectedAgentList agents={allAgents} />
+ </Flexbox>
+ </Modal>
+ );
+ },
+);
+
+export default AddGroupMemberModal;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/store.ts b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/store.ts
new file mode 100644
index 00000000000..200bd807867
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/AddGroupMemberModal/store.ts
@@ -0,0 +1,45 @@
+import { create } from 'zustand';
+
+interface AgentSelectionState {
+ // Actions
+ clearSelection: () => void;
+ isSelected: (agentId: string) => boolean;
+ removeAgent: (agentId: string) => void;
+ // State
+ selectedAgentIds: string[];
+ setSelectedAgents: (agentIds: string[]) => void;
+ toggleAgent: (agentId: string) => void;
+}
+
+export const useAgentSelectionStore = create<AgentSelectionState>((set, get) => ({
+ clearSelection: () => {
+ set({ selectedAgentIds: [] });
+ },
+
+ isSelected: (agentId) => {
+ return get().selectedAgentIds.includes(agentId);
+ },
+
+ removeAgent: (agentId) => {
+ set((state) => ({
+ selectedAgentIds: state.selectedAgentIds.filter((id) => id !== agentId),
+ }));
+ },
+
+ selectedAgentIds: [],
+
+ setSelectedAgents: (agentIds) => {
+ set({ selectedAgentIds: agentIds });
+ },
+
+ toggleAgent: (agentId) => {
+ set((state) => {
+ const isCurrentlySelected = state.selectedAgentIds.includes(agentId);
+ if (isCurrentlySelected) {
+ return { selectedAgentIds: state.selectedAgentIds.filter((id) => id !== agentId) };
+ } else {
+ return { selectedAgentIds: [...state.selectedAgentIds, agentId] };
+ }
+ });
+ },
+}));
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Body.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Body.tsx
new file mode 100644
index 00000000000..9af31dd9d8a
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Body.tsx
@@ -0,0 +1,24 @@
+import { Accordion } from '@lobehub/ui';
+import React, { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import Members from './Members';
+import Topic from './Topic';
+
+export enum ChatSidebarKey {
+ Members = 'members',
+ Topic = 'topic',
+}
+
+const Body = memo(() => {
+ return (
+ <Flexbox paddingInline={4}>
+ <Accordion defaultExpandedKeys={[ChatSidebarKey.Members, ChatSidebarKey.Topic]} gap={8}>
+ <Members itemKey={ChatSidebarKey.Members} />
+ <Topic itemKey={ChatSidebarKey.Topic} />
+ </Accordion>
+ </Flexbox>
+ );
+});
+
+export default Body;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/AgentProfilePopup.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/AgentProfilePopup.tsx
new file mode 100644
index 00000000000..e7c36b36b81
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/AgentProfilePopup.tsx
@@ -0,0 +1,187 @@
+'use client';
+
+import type { AgentItem } from '@lobechat/types';
+import { Avatar, Text, Tooltip } from '@lobehub/ui';
+import { Popover } from 'antd';
+import { createStyles } from 'antd-style';
+import { PropsWithChildren, memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Center, Flexbox } from 'react-layout-kit';
+
+import { DEFAULT_AVATAR } from '@/const/meta';
+import ModelSelect from '@/features/ModelSelect';
+import { useAgentGroupStore } from '@/store/agentGroup';
+
+const useStyles = createStyles(({ css, token }) => ({
+ banner: css`
+ position: relative;
+ overflow: hidden;
+ height: 60px;
+ `,
+ bannerInner: css`
+ filter: blur(44px);
+ `,
+ chatButton: css`
+ width: 100%;
+ `,
+ container: css`
+ overflow: hidden;
+ width: 280px;
+ background: ${token.colorBgElevated};
+ `,
+ description: css`
+ overflow: hidden;
+
+ max-height: 80px;
+
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${token.colorTextSecondary};
+ text-overflow: ellipsis;
+ `,
+ header: css`
+ position: relative;
+ margin-block-start: -24px;
+ padding-inline: 16px;
+ `,
+ modelLabel: css`
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+ name: css`
+ font-size: 16px;
+ font-weight: 600;
+ color: ${token.colorText};
+ `,
+ section: css`
+ padding-block: 12px;
+ padding-inline: 16px;
+ `,
+ sectionTitle: css`
+ margin-block-end: 8px;
+
+ font-size: 11px;
+ font-weight: 600;
+ color: ${token.colorTextTertiary};
+ text-transform: uppercase;
+ `,
+}));
+
+interface AgentProfilePopupProps extends PropsWithChildren {
+ agent: AgentItem;
+ groupId: string;
+ onChat: () => void;
+}
+
+const AgentProfilePopup = memo<AgentProfilePopupProps>(({ agent, groupId, children }) => {
+ const { t } = useTranslation('chat');
+ const { styles, theme } = useStyles();
+ const [open, setOpen] = useState(false);
+ const [loading, setLoading] = useState(false);
+
+ const updateMemberAgentConfig = useAgentGroupStore((s) => s.updateMemberAgentConfig);
+
+ const handleModelChange = async (props: { model: string; provider: string }) => {
+ setLoading(true);
+ try {
+ await updateMemberAgentConfig(groupId, agent.id, {
+ model: props.model,
+ provider: props.provider,
+ });
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ // const handleChat = () => {
+ // setOpen(false);
+ // onChat();
+ // };
+
+ const content = (
+ <Flexbox className={styles.container}>
+ {/* Banner */}
+ <Center
+ className={styles.banner}
+ style={{
+ background: theme.colorFillTertiary,
+ }}
+ >
+ <Avatar
+ avatar={agent.avatar || DEFAULT_AVATAR}
+ background={agent.backgroundColor ?? undefined}
+ className={styles.bannerInner}
+ emojiScaleWithBackground
+ shape={'square'}
+ size={400}
+ />
+ </Center>
+
+ {/* Header with Avatar */}
+ <Flexbox className={styles.header} gap={8}>
+ <Avatar
+ avatar={agent.avatar || DEFAULT_AVATAR}
+ background={agent.backgroundColor ?? undefined}
+ emojiScaleWithBackground
+ shape={'square'}
+ size={48}
+ style={{
+ border: `2px solid ${theme.colorBgElevated}`,
+ }}
+ />
+ <Flexbox gap={2}>
+ <Text className={styles.name} ellipsis>
+ {agent.title || t('defaultSession', { ns: 'common' })}
+ </Text>
+ {agent.description && (
+ <Tooltip title={agent.description}>
+ <Text className={styles.description} ellipsis={{ rows: 2 }}>
+ {agent.description}
+ </Text>
+ </Tooltip>
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ {/* Model Section */}
+ <Flexbox className={styles.section} gap={4}>
+ <div className={styles.sectionTitle}>{t('groupSidebar.agentProfile.model')}</div>
+ <ModelSelect
+ loading={loading}
+ onChange={handleModelChange}
+ value={{ model: agent.model!, provider: agent.provider! }}
+ />
+ </Flexbox>
+
+ {/* Actions */}
+ {/*<Flexbox className={styles.section} style={{ paddingBlockStart: 0 }}>*/}
+ {/* <Button*/}
+ {/* className={styles.chatButton}*/}
+ {/* icon={<MessageSquare size={14} />}*/}
+ {/* onClick={handleChat}*/}
+ {/* type="primary"*/}
+ {/* >*/}
+ {/* {t('groupSidebar.agentProfile.chat')}*/}
+ {/* </Button>*/}
+ {/*</Flexbox>*/}
+ </Flexbox>
+ );
+
+ return (
+ <Popover
+ arrow={false}
+ content={content}
+ onOpenChange={setOpen}
+ open={open}
+ placement="right"
+ styles={{
+ body: { overflow: 'hidden', padding: 0 },
+ }}
+ trigger={['click']}
+ >
+ {children}
+ </Popover>
+ );
+});
+
+export default AgentProfilePopup;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
new file mode 100644
index 00000000000..c14027e2bf2
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { UserMinus } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { DEFAULT_AVATAR } from '@/const/meta';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import UserAvatar from '@/features/User/UserAvatar';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
+
+import AddGroupMemberModal from '../AddGroupMemberModal';
+import AgentProfilePopup from './AgentProfilePopup';
+import GroupMemberItem from './GroupMemberItem';
+
+interface GroupMemberProps {
+ addModalOpen: boolean;
+ groupId?: string;
+ onAddModalOpenChange: (open: boolean) => void;
+}
+
+/**
+ * Group member info in Sidebar
+ */
+const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange, groupId }) => {
+ const { t } = useTranslation('chat');
+ const [nickname, username] = useUserStore((s) => [
+ userProfileSelectors.nickName(s),
+ userProfileSelectors.username(s),
+ ]);
+ const addAgentsToGroup = useAgentGroupStore((s) => s.addAgentsToGroup);
+ const removeAgentFromGroup = useAgentGroupStore((s) => s.removeAgentFromGroup);
+ const toggleThread = useAgentGroupStore((s) => s.toggleThread);
+ const togglePortal = useChatStore((s) => s.togglePortal);
+
+ // Get members from store (excluding supervisor)
+ const groupMembers = useAgentGroupStore(agentGroupSelectors.getGroupMembers(groupId || ''));
+
+ // const [agentSettingsOpen, setAgentSettingsOpen] = useState(false);
+ // const [selectedAgentId, setSelectedAgentId] = useState<string | undefined>();
+
+ const handleAddMembers = async (selectedAgents: string[]) => {
+ if (!groupId) {
+ console.error('No active group to add members to');
+ return;
+ }
+
+ if (selectedAgents.length > 0) {
+ await addAgentsToGroup(groupId, selectedAgents);
+ }
+
+ onAddModalOpenChange(false);
+ };
+
+ const [removingMemberIds, setRemovingMemberIds] = useState<string[]>([]);
+
+ const withRemovingFlag = async (id: string, task: () => Promise<void>) => {
+ setRemovingMemberIds((prev) => (prev.includes(id) ? prev : [...prev, id]));
+ try {
+ await task();
+ } finally {
+ setRemovingMemberIds((prev) => prev.filter((memberId) => memberId !== id));
+ }
+ };
+
+ const handleRemoveMember = async (memberId: string) => {
+ if (!groupId) return;
+
+ await withRemovingFlag(memberId, () => removeAgentFromGroup(groupId, memberId));
+ };
+
+ const handleMemberClick = (agentId: string) => {
+ toggleThread(agentId);
+ togglePortal(true);
+ };
+
+ return (
+ <>
+ <Flexbox gap={2}>
+ {/* User */}
+ <NavItem icon={<UserAvatar size={24} />} title={nickname || username || 'User'} />
+ {groupId &&
+ groupMembers.map((item) => (
+ <AgentProfilePopup
+ agent={item}
+ groupId={groupId}
+ key={item.id}
+ onChat={() => handleMemberClick(item.id)}
+ >
+ <div>
+ <GroupMemberItem
+ actions={
+ <ActionIcon
+ danger
+ icon={UserMinus}
+ loading={removingMemberIds.includes(item.id)}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleRemoveMember(item.id);
+ }}
+ size={'small'}
+ title={t('groupSidebar.members.removeMember')}
+ />
+ }
+ avatar={item.avatar || DEFAULT_AVATAR}
+ background={item.backgroundColor ?? undefined}
+ title={item.title || t('defaultSession', { ns: 'common' })}
+ />
+ </div>
+ </AgentProfilePopup>
+ ))}
+ </Flexbox>
+
+ {groupId && (
+ <AddGroupMemberModal
+ existingMembers={groupMembers.map((member) => member.id)}
+ groupId={groupId}
+ onCancel={() => onAddModalOpenChange(false)}
+ onConfirm={handleAddMembers}
+ open={addModalOpen}
+ />
+ )}
+ </>
+ );
+});
+
+export default GroupMember;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMemberItem.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMemberItem.tsx
new file mode 100644
index 00000000000..e8bec5ac17d
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupMemberItem.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { Avatar } from '@lobehub/ui';
+import { ReactNode, memo } from 'react';
+
+import { DEFAULT_AVATAR } from '@/const/meta';
+import NavItem from '@/features/NavPanel/components/NavItem';
+
+interface GroupMemberItemProps {
+ actions?: ReactNode;
+ avatar?: string;
+ background?: string;
+ onClick?: () => void;
+ title: string;
+}
+
+const GroupMemberItem = memo<GroupMemberItemProps>(({ title, avatar, background, actions }) => {
+ return (
+ <NavItem
+ actions={actions}
+ icon={
+ <Avatar
+ avatar={avatar || DEFAULT_AVATAR}
+ background={background}
+ emojiScaleWithBackground
+ size={24}
+ style={{ flex: 'none' }}
+ />
+ }
+ title={title}
+ />
+ );
+});
+
+export default GroupMemberItem;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupRole.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupRole.tsx
similarity index 83%
rename from src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupRole.tsx
rename to src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupRole.tsx
index 109637781c6..147b72fb142 100644
--- a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/GroupRole.tsx
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/GroupRole.tsx
@@ -6,9 +6,8 @@ import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import GroupInfo from '@/features/GroupInfo';
-import { useChatGroupStore } from '@/store/chatGroup';
-import { chatGroupSelectors } from '@/store/chatGroup/selectors';
-import { useSessionStore } from '@/store/session';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { LobeSession } from '@/types/session';
import { useStyles } from './style';
@@ -26,9 +25,9 @@ const GroupRole = memo<GroupRoleProps>(
const { styles } = useStyles();
const { t } = useTranslation('chat');
- const activeGroupId = useSessionStore((s) => s.activeId);
- const updateGroupConfig = useChatGroupStore((s) => s.updateGroupConfig);
- const groupConfig = useChatGroupStore(chatGroupSelectors.currentGroupConfig);
+ const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
+ const updateGroupConfig = useAgentGroupStore((s) => s.updateGroupConfig);
+ const groupConfig = useAgentGroupStore(agentGroupSelectors.currentGroupConfig);
const handleSystemPromptChange = async (value: string) => {
if (!activeGroupId) return;
@@ -49,7 +48,7 @@ const GroupRole = memo<GroupRoleProps>(
};
return (
- <Flexbox height={200} onClick={handleOpen} padding={16}>
+ <Flexbox height={200} onClick={handleOpen} paddingInline={8}>
<EditableMessage
classNames={{ markdown: styles.prompt }}
editing={editing}
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/Header/Avatar.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/Header/Avatar.tsx
new file mode 100644
index 00000000000..070c5fbce17
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/Header/Avatar.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { Block, GroupAvatar } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { DEFAULT_AVATAR } from '@/const/meta';
+import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+const HeaderAvatar = memo<{ size?: number }>(() => {
+ const groupMeta = useAgentGroupStore(agentGroupSelectors.currentGroupMeta);
+ const currentGroup = useAgentGroupStore(agentGroupSelectors.currentGroup);
+ const agents = currentGroup?.agents || [];
+
+ const currentUser = useUserStore((s) => ({
+ avatar: userProfileSelectors.userAvatar(s),
+ name: userProfileSelectors.displayUserName(s) || userProfileSelectors.nickName(s) || 'You',
+ }));
+
+ const openChatSettings = useOpenChatSettings();
+
+ return (
+ <Block
+ clickable
+ flex={'none'}
+ height={32}
+ onClick={(e) => {
+ e.stopPropagation();
+ openChatSettings();
+ }}
+ padding={2}
+ style={{
+ overflow: 'hidden',
+ }}
+ variant={'borderless'}
+ width={32}
+ >
+ <GroupAvatar
+ avatarShape={'square'}
+ avatars={[
+ {
+ avatar: currentUser.avatar || DEFAULT_AVATAR,
+ },
+ ...agents.map((agent) => ({
+ avatar: agent.avatar || DEFAULT_AVATAR,
+ background: agent.backgroundColor || undefined,
+ })),
+ ]}
+ cornerShape={'square'}
+ size={28}
+ title={groupMeta.title || undefined}
+ />
+ </Block>
+ );
+});
+
+export default HeaderAvatar;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/Header/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/Header/index.tsx
new file mode 100644
index 00000000000..b6e7c469d71
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/Header/index.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import Avatar from './Avatar';
+
+const HeaderInfo = memo(() => {
+ const { t } = useTranslation('chat');
+ const groupMeta = useAgentGroupStore(agentGroupSelectors.currentGroupMeta);
+
+ const displayTitle = groupMeta.title || t('untitledGroup');
+
+ return (
+ <Flexbox
+ align={'center'}
+ flex={1}
+ gap={8}
+ horizontal
+ style={{
+ overflow: 'hidden',
+ }}
+ >
+ <Avatar />
+ <Text ellipsis weight={500}>
+ {displayTitle}
+ </Text>
+ </Flexbox>
+ );
+});
+
+export default HeaderInfo;
diff --git a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/style.ts b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/style.ts
similarity index 78%
rename from src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/style.ts
rename to src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/style.ts
index d6498362aea..92ca52f06e4 100644
--- a/src/app/[variants]/(main)/chat/components/topic/features/GroupConfig/style.ts
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/GroupConfig/style.ts
@@ -10,8 +10,10 @@ export const useStyles = createStyles(({ css, token }) => ({
align-items: center;
width: 100%;
- padding-block: 8px;
- padding-inline: 8px 12px;
+ min-height: 36px;
+ max-height: 36px;
+ padding-block: 0 !important;
+ padding-inline: 4px !important;
border-radius: ${token.borderRadius}px;
transition: all 0.2s ease;
@@ -21,7 +23,7 @@ export const useStyles = createStyles(({ css, token }) => ({
}
&:hover {
- background: ${token.colorFillSecondary};
+ background: ${token.colorFillTertiary};
.show-on-hover {
opacity: 1;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/AddTopicButon.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/AddTopicButon.tsx
new file mode 100644
index 00000000000..408af8b5787
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/AddTopicButon.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { MessageSquarePlusIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+import { HotkeyEnum } from '@/types/hotkey';
+
+const AddTopicButon = memo(() => {
+ const { t } = useTranslation('topic');
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.SaveTopic));
+ const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
+ const router = useQueryRoute();
+ const hasTopic = useChatStore((s) => !!s.activeTopicId);
+
+ if (!hasTopic || !activeGroupId) return null;
+
+ return (
+ <ActionIcon
+ icon={MessageSquarePlusIcon}
+ onClick={() => {
+ useChatStore.setState({ activeTopicId: undefined });
+ router.push(urlJoin('/group', activeGroupId), { query: { thread: null, topic: null } });
+ }}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ title={t('actions.addNewTopic')}
+ tooltipProps={{
+ hotkey,
+ placement: 'bottom',
+ }}
+ />
+ );
+});
+
+export default AddTopicButon;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
new file mode 100644
index 00000000000..64d5a7d765a
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
@@ -0,0 +1,45 @@
+import { Popover } from 'antd';
+import React, { PropsWithChildren, Suspense, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+import { useNavigate } from 'react-router-dom';
+
+import List from '@/app/[variants]/(main)/home/_layout/Body/Agent/List';
+import { AgentModalProvider } from '@/app/[variants]/(main)/home/_layout/Body/Agent/ModalProvider';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+
+const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
+ const navigate = useNavigate();
+ return (
+ <Popover
+ arrow={false}
+ content={
+ <Suspense fallback={<SkeletonList rows={6} />}>
+ <AgentModalProvider>
+ <Flexbox
+ gap={4}
+ padding={8}
+ style={{
+ maxHeight: '50vh',
+ overflowY: 'auto',
+ }}
+ >
+ <List onMoreClick={() => navigate('/')} />
+ </Flexbox>
+ </AgentModalProvider>
+ </Suspense>
+ }
+ placement={'bottomLeft'}
+ styles={{
+ body: {
+ padding: 0,
+ width: 240,
+ },
+ }}
+ trigger={['click']}
+ >
+ {children}
+ </Popover>
+ );
+});
+
+export default SwitchPanel;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Agent/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Agent/index.tsx
new file mode 100644
index 00000000000..b08611898bc
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Agent/index.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { ActionIcon, Block, GroupAvatar, Text } from '@lobehub/ui';
+import { ChevronsUpDownIcon } from 'lucide-react';
+import React, { PropsWithChildren, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DEFAULT_AVATAR } from '@/const/meta';
+import { SkeletonItem } from '@/features/NavPanel/components/SkeletonList';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import SwitchPanel from './SwitchPanel';
+
+const Agent = memo<PropsWithChildren>(() => {
+ const { t } = useTranslation(['chat', 'common']);
+
+ const [isGroupsInit, groupMeta, agents] = useAgentGroupStore((s) => [
+ agentGroupSelectors.isGroupsInit(s),
+ agentGroupSelectors.currentGroupMeta(s),
+ agentGroupSelectors.currentGroupAgents(s),
+ ]);
+
+ const displayTitle = groupMeta?.title || t('untitledGroup', { ns: 'chat' });
+
+ if (isGroupsInit) return <SkeletonItem height={32} padding={0} />;
+
+ return (
+ <SwitchPanel>
+ <Block
+ align={'center'}
+ clickable
+ gap={8}
+ horizontal
+ padding={2}
+ style={{
+ minWidth: 32,
+ overflow: 'hidden',
+ }}
+ variant={'borderless'}
+ >
+ <GroupAvatar
+ avatarShape={'square'}
+ avatars={agents.map((agent) => ({
+ avatar: agent.avatar || DEFAULT_AVATAR,
+ background: agent.backgroundColor || undefined,
+ style: { borderRadius: 3 },
+ }))}
+ cornerShape={'square'}
+ size={28}
+ title={groupMeta?.title || undefined}
+ />
+ <Text ellipsis weight={500}>
+ {displayTitle}
+ </Text>
+ <ActionIcon
+ icon={ChevronsUpDownIcon}
+ size={{
+ blockSize: 28,
+ size: 16,
+ }}
+ style={{
+ width: 24,
+ }}
+ />
+ </Block>
+ </SwitchPanel>
+ );
+});
+
+export default Agent;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
new file mode 100644
index 00000000000..13b657bb8c1
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/Nav.tsx
@@ -0,0 +1,50 @@
+'use client';
+
+import { BotPromptIcon } from '@lobehub/ui/icons';
+import { SearchIcon } from 'lucide-react';
+import { usePathname } from 'next/navigation';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import { useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useGlobalStore } from '@/store/global';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+
+const Nav = memo(() => {
+ const { t } = useTranslation('chat');
+ const params = useParams();
+ const groupId = params.gid;
+ const pathname = usePathname();
+ const isProfileActive = pathname.includes('/profile');
+ const router = useQueryRoute();
+ const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
+ const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
+
+ return (
+ <Flexbox gap={1} paddingInline={4}>
+ {isAgentEditable && (
+ <NavItem
+ active={isProfileActive}
+ icon={BotPromptIcon}
+ onClick={() => {
+ router.push(urlJoin('/group', groupId!, 'profile'));
+ }}
+ title={t('tab.groupProfile')}
+ />
+ )}
+ <NavItem
+ icon={SearchIcon}
+ onClick={() => {
+ toggleCommandMenu(true);
+ }}
+ title={t('tab.search')}
+ />
+ </Flexbox>
+ );
+});
+
+export default Nav;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Header/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/index.tsx
new file mode 100644
index 00000000000..b32ab421c30
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Header/index.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { PropsWithChildren, memo } from 'react';
+
+import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
+
+import AddTopicButon from './AddTopicButon';
+import Agent from './Agent';
+import Nav from './Nav';
+
+const HeaderInfo = memo<PropsWithChildren>(() => {
+ return (
+ <>
+ <SideBarHeaderLayout left={<Agent />} right={<AddTopicButon />} />
+ <Nav />
+ </>
+ );
+});
+
+export default HeaderInfo;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Members/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Members/index.tsx
new file mode 100644
index 00000000000..d8e1aa93f10
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Members/index.tsx
@@ -0,0 +1,62 @@
+'use client';
+
+import { AccordionItem, ActionIcon, Text } from '@lobehub/ui';
+import { UserPlus } from 'lucide-react';
+import { MouseEvent, memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import GroupMember from '../GroupConfig/GroupMember';
+
+interface MembersProps {
+ itemKey: string;
+}
+
+const Members = memo<MembersProps>(({ itemKey }) => {
+ const { t } = useTranslation('chat');
+ const [addModalOpen, setAddModalOpen] = useState(false);
+
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const membersCount = useAgentGroupStore(
+ agentGroupSelectors.getGroupAgentCount(activeGroupId || ''),
+ );
+
+ const handleAddMember = (e: MouseEvent) => {
+ e.stopPropagation();
+ setAddModalOpen(true);
+ };
+
+ return (
+ <AccordionItem
+ action={
+ <ActionIcon
+ icon={UserPlus}
+ onClick={handleAddMember}
+ size={'small'}
+ title={t('groupSidebar.members.addMember')}
+ />
+ }
+ itemKey={itemKey}
+ paddingBlock={4}
+ paddingInline={'8px 4px'}
+ title={
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {`${t('groupSidebar.tabs.members')} ${membersCount}`}
+ </Text>
+ }
+ >
+ <Flexbox gap={1} paddingBlock={1}>
+ <GroupMember
+ addModalOpen={addModalOpen}
+ groupId={activeGroupId}
+ onAddModalOpenChange={setAddModalOpen}
+ />
+ </Flexbox>
+ </AccordionItem>
+ );
+});
+
+export default Members;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/Actions.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/Actions.tsx
new file mode 100644
index 00000000000..d07e82e2ab2
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/Actions.tsx
@@ -0,0 +1,26 @@
+import { ActionIcon, Dropdown } from '@lobehub/ui';
+import { MoreHorizontal } from 'lucide-react';
+import { memo } from 'react';
+
+import { useTopicActionsDropdownMenu } from './useDropdownMenu';
+
+const Actions = memo(() => {
+ const dropdownMenu = useTopicActionsDropdownMenu();
+
+ return (
+ <Dropdown
+ arrow={false}
+ menu={{
+ items: dropdownMenu,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ },
+ }}
+ trigger={['click']}
+ >
+ <ActionIcon icon={MoreHorizontal} size={'small'} />
+ </Dropdown>
+ );
+});
+
+export default Actions;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
new file mode 100644
index 00000000000..63bf5b1180d
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
@@ -0,0 +1,182 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback, useEffect, useRef } from 'react';
+import { Flexbox } from 'react-layout-kit';
+import { VList, VListHandle } from 'virtua';
+
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import TopicEmpty from '@/features/TopicEmpty';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import TopicItem from '../List/Item';
+
+const ITEM_HEIGHT = 44; // Each topic item height
+
+interface ContentProps {
+ open: boolean;
+ searchKeyword: string;
+}
+
+const Content = memo<ContentProps>(({ open, searchKeyword }) => {
+ const virtuaRef = useRef<VListHandle>(null);
+ const fetchedCountRef = useRef(-1);
+ const initializedRef = useRef(false);
+
+ const [
+ activeTopicId,
+ activeThreadId,
+ hasMore,
+ isLoadingMore,
+ isExpandingPageSize,
+ loadMoreTopics,
+ activeAgentId,
+ useSearchTopics,
+ ] = useChatStore((s) => [
+ s.activeTopicId,
+ s.activeThreadId,
+ topicSelectors.hasMoreTopics(s),
+ topicSelectors.isLoadingMoreTopics(s),
+ topicSelectors.isExpandingPageSize(s),
+ s.loadMoreTopics,
+ s.activeAgentId,
+ s.useSearchTopics,
+ ]);
+
+ // Use server-side search if there's a keyword
+ const trimmedKeyword = searchKeyword.trim();
+ const isSearching = trimmedKeyword.length > 0;
+
+ // Set searching state and trigger search
+ useEffect(() => {
+ if (isSearching) {
+ useChatStore.setState({ isSearchingTopic: true });
+ } else {
+ // Reset search results when clearing search
+ useChatStore.setState({ isSearchingTopic: false, searchTopics: [] });
+ }
+ }, [isSearching]);
+
+ // Only search when there's a keyword (pass undefined to disable SWR)
+ // Note: searchTopics uses sessionId in the service, but agentId in the hook
+ useSearchTopics(isSearching ? trimmedKeyword : undefined, {
+ agentId: activeAgentId,
+ groupId: undefined,
+ });
+
+ const searchResults = useChatStore(topicSelectors.searchTopics, isEqual);
+ const allTopicList = useChatStore(topicSelectors.displayTopics, isEqual);
+ const isSearchingTopic = useChatStore(topicSelectors.isSearchingTopic);
+
+ // Use search results if searching, otherwise use regular list
+ const activeTopicList = isSearching ? searchResults : allTopicList;
+ const count = activeTopicList?.length || 0;
+
+ // Initial load: calculate how many items needed to fill viewport
+ useEffect(() => {
+ if (!open || initializedRef.current || isLoadingMore || isSearching) return;
+
+ const timer = setTimeout(() => {
+ const ref = virtuaRef.current;
+ if (!ref) return;
+
+ const viewportSize = ref.viewportSize;
+ const itemsNeeded = Math.ceil(viewportSize / ITEM_HEIGHT) + 3;
+
+ // Mark as initialized
+ initializedRef.current = true;
+
+ // Calculate how many pages we need to load to fill screen
+ if (count < itemsNeeded && hasMore) {
+ fetchedCountRef.current = count;
+
+ // Calculate pages needed and load once
+ const itemsToLoad = itemsNeeded - count;
+ const pagesNeeded = Math.ceil(itemsToLoad / 20); // Assume 20 items per page
+
+ // Load the required pages
+ const loadPages = async () => {
+ for (let i = 0; i < pagesNeeded && hasMore; i++) {
+ await loadMoreTopics();
+ }
+ };
+ loadPages();
+ }
+ }, 100);
+
+ return () => clearTimeout(timer);
+ }, [open, count, hasMore, loadMoreTopics, isLoadingMore]);
+
+ // Reset initialized flag when drawer closes
+ useEffect(() => {
+ if (!open) {
+ initializedRef.current = false;
+ }
+ }, [open]);
+
+ // Handle scroll - use findItemIndex (official pattern)
+ const handleScroll = useCallback(async () => {
+ // Don't load more when searching
+ if (isSearching) return;
+
+ const ref = virtuaRef.current;
+ if (!ref || !hasMore) return;
+
+ // Use findItemIndex to detect scroll position
+ const bottomVisibleIndex = ref.findItemIndex(ref.scrollOffset + ref.viewportSize);
+
+ // When scrolled near the end (within 5 items), load more
+ if (fetchedCountRef.current < count && bottomVisibleIndex + 5 > count) {
+ fetchedCountRef.current = count;
+ await loadMoreTopics();
+ }
+ }, [hasMore, loadMoreTopics, count, isSearching]);
+
+ const showLoading = (isLoadingMore || isExpandingPageSize) && !isSearching;
+ const showSearchLoading = isSearching && isSearchingTopic;
+
+ // Show empty state when no topics
+ if (count === 0 && !showLoading && !showSearchLoading) {
+ return <TopicEmpty search={Boolean(searchKeyword)} />;
+ }
+
+ // Show loading when searching
+ if (showSearchLoading) {
+ return (
+ <Flexbox gap={1} paddingBlock={1} paddingInline={4}>
+ <SkeletonList rows={5} />
+ </Flexbox>
+ );
+ }
+
+ return (
+ <VList
+ bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
+ onScroll={handleScroll}
+ ref={virtuaRef}
+ style={{ height: '100%' }}
+ >
+ {activeTopicList?.map((topic) => (
+ <Flexbox gap={1} key={topic.id} padding={'4px 8px'}>
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ threadId={activeThreadId}
+ title={topic.title}
+ />
+ </Flexbox>
+ ))}
+ {showLoading && (
+ <Flexbox padding={'4px 8px'}>
+ <SkeletonList rows={3} />
+ </Flexbox>
+ )}
+ </VList>
+ );
+});
+
+Content.displayName = 'AllTopicsDrawerContent';
+
+export default Content;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
new file mode 100644
index 00000000000..f825e5ee937
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { SearchBar } from '@lobehub/ui';
+import dynamic from 'next/dynamic';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+
+const Content = dynamic(() => import('./Content'), {
+ loading: () => (
+ <Flexbox gap={1} paddingBlock={1} paddingInline={4}>
+ <SkeletonList rows={3} />
+ </Flexbox>
+ ),
+ ssr: false,
+});
+
+interface AllTopicsDrawerProps {
+ onClose: () => void;
+ open: boolean;
+}
+
+const AllTopicsDrawer = memo<AllTopicsDrawerProps>(({ open, onClose }) => {
+ const { t } = useTranslation('topic');
+ const [searchKeyword, setSearchKeyword] = useState('');
+
+ return (
+ <SideBarDrawer
+ onClose={onClose}
+ open={open}
+ subHeader={
+ <Flexbox paddingBlock={'0 8px'} paddingInline={8}>
+ <SearchBar
+ allowClear
+ defaultValue={searchKeyword}
+ onInputChange={(keyword) => {
+ if (!keyword) setSearchKeyword('');
+ }}
+ onSearch={(keyword) => setSearchKeyword(keyword)}
+ placeholder={t('searchPlaceholder')}
+ />
+ </Flexbox>
+ }
+ title={t('title')}
+ >
+ <Content open={open} searchKeyword={searchKeyword} />
+ </SideBarDrawer>
+ );
+});
+
+AllTopicsDrawer.displayName = 'AllTopicsDrawer';
+
+export default AllTopicsDrawer;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/Actions.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/Actions.tsx
new file mode 100644
index 00000000000..97e77c89bf9
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/Actions.tsx
@@ -0,0 +1,26 @@
+import { ActionIcon, Dropdown, type MenuProps } from '@lobehub/ui';
+import { MoreHorizontalIcon } from 'lucide-react';
+import { memo } from 'react';
+
+interface ActionProps {
+ dropdownMenu: MenuProps['items'];
+}
+
+const Actions = memo<ActionProps>(({ dropdownMenu }) => {
+ return (
+ <Dropdown
+ arrow={false}
+ menu={{
+ items: dropdownMenu,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ },
+ }}
+ trigger={['click']}
+ >
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} />
+ </Dropdown>
+ );
+});
+
+export default Actions;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/Editing.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/Editing.tsx
new file mode 100644
index 00000000000..c9af4d443f7
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/Editing.tsx
@@ -0,0 +1,87 @@
+import { Input } from '@lobehub/ui';
+import { Popover } from 'antd';
+import { memo, useCallback, useState } from 'react';
+
+import { useChatStore } from '@/store/chat';
+
+interface EditingProps {
+ id: string;
+ title: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {
+ const [newTitle, setNewTitle] = useState(title);
+ const [editing, updateTopicTitle] = useChatStore((s) => [
+ s.topicRenamingId === id,
+ s.updateTopicTitle,
+ ]);
+
+ const handleUpdate = useCallback(async () => {
+ if (newTitle && title !== newTitle) {
+ try {
+ // Set loading state
+ useChatStore.setState(
+ {
+ topicLoadingIds: [...useChatStore.getState().topicLoadingIds, id],
+ },
+ false,
+ 'setTopicUpdating',
+ );
+ await updateTopicTitle(id, newTitle);
+ } finally {
+ // Clear loading state
+ useChatStore.setState(
+ {
+ topicLoadingIds: useChatStore
+ .getState()
+ .topicLoadingIds.filter((loadingId) => loadingId !== id),
+ },
+ false,
+ 'clearTopicUpdating',
+ );
+ }
+ }
+ toggleEditing(false);
+ }, [newTitle, title, id, updateTopicTitle, toggleEditing]);
+
+ return (
+ <Popover
+ arrow={false}
+ content={
+ <Input
+ autoFocus
+ defaultValue={title}
+ onBlur={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ onChange={(e) => setNewTitle(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ onPressEnter={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ />
+ }
+ destroyOnHidden
+ onOpenChange={(open) => {
+ if (!open) handleUpdate();
+ toggleEditing(open);
+ }}
+ open={editing}
+ placement={'bottomLeft'}
+ styles={{
+ body: {
+ padding: 4,
+ width: 320,
+ },
+ }}
+ trigger={['click']}
+ >
+ <div />
+ </Popover>
+ );
+});
+
+export default Editing;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
new file mode 100644
index 00000000000..157ca9529f2
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -0,0 +1,141 @@
+import { ActionIcon, Dropdown, Icon, Tag , Skeleton } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { MessageSquareDashed, Star } from 'lucide-react';
+import { Suspense, memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { isDesktop } from '@/const/version';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+import ThreadList from '../../TopicListContent/ThreadList';
+import { useTopicNavigation } from '../../hooks/useTopicNavigation';
+import Actions from './Actions';
+import Editing from './Editing';
+import { useTopicItemDropdownMenu } from './useDropdownMenu';
+
+interface TopicItemProps {
+ active?: boolean;
+ fav?: boolean;
+ id?: string;
+ threadId?: string;
+ title: string;
+}
+
+const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId }) => {
+ const { t } = useTranslation('topic');
+
+ const theme = useTheme();
+ const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+
+ const [editing, isLoading] = useChatStore((s) => [
+ id ? s.topicRenamingId === id : false,
+ id ? s.topicLoadingIds.includes(id) : false,
+ ]);
+
+ const [favoriteTopic] = useChatStore((s) => [s.favoriteTopic]);
+
+ const { navigateToTopic, isInAgentSubRoute } = useTopicNavigation();
+
+ const toggleEditing = useCallback(
+ (visible?: boolean) => {
+ useChatStore.setState({ topicRenamingId: visible && id ? id : '' });
+ },
+ [id],
+ );
+
+ const handleClick = useCallback(() => {
+ if (editing) return;
+ navigateToTopic(id);
+ }, [editing, id, navigateToTopic]);
+
+ const handleDoubleClick = useCallback(() => {
+ if (!id || !activeAgentId) return;
+ if (isDesktop) {
+ openTopicInNewWindow(activeAgentId, id);
+ }
+ }, [id, activeAgentId, openTopicInNewWindow]);
+
+ const dropdownMenu = useTopicItemDropdownMenu({
+ id,
+ toggleEditing,
+ });
+
+ // For default topic (no id)
+ if (!id) {
+ return (
+ <NavItem
+ active={active && !isInAgentSubRoute}
+ icon={<Icon color={theme.colorTextDescription} icon={MessageSquareDashed} size={'small'} />}
+ loading={isLoading}
+ onClick={handleClick}
+ title={
+ <Flexbox align={'center'} flex={1} gap={6} horizontal>
+ {t('defaultTitle')}
+ <Tag
+ size={'small'}
+ style={{
+ color: theme.colorTextDescription,
+ fontSize: 10,
+ }}
+ >
+ {t('temp')}
+ </Tag>
+ </Flexbox>
+ }
+ />
+ );
+ }
+
+ return (
+ <Flexbox style={{ position: 'relative' }}>
+ <Dropdown
+ menu={{
+ items: dropdownMenu,
+ }}
+ trigger={['contextMenu']}
+ >
+ <NavItem
+ actions={<Actions dropdownMenu={dropdownMenu} />}
+ active={active && !threadId && !isInAgentSubRoute}
+ disabled={editing}
+ icon={
+ <ActionIcon
+ color={fav ? theme.colorWarning : undefined}
+ fill={fav ? theme.colorWarning : 'transparent'}
+ icon={Star}
+ onClick={(e) => {
+ e.stopPropagation();
+ favoriteTopic(id, !fav);
+ }}
+ size={'small'}
+ />
+ }
+ loading={isLoading}
+ onClick={handleClick}
+ onDoubleClick={handleDoubleClick}
+ title={title}
+ />
+ </Dropdown>
+ <Editing id={id} title={title} toggleEditing={toggleEditing} />
+ {active && (
+ <Suspense
+ fallback={
+ <Flexbox gap={8} paddingBlock={8} paddingInline={24} width={'100%'}>
+ <Skeleton.Button active size={'small'} style={{ height: 18, width: '100%' }} />
+ <Skeleton.Button active size={'small'} style={{ height: 18, width: '100%' }} />
+ </Flexbox>
+ }
+ >
+ <ThreadList />
+ </Suspense>
+ )}
+ </Flexbox>
+ );
+});
+
+export default TopicItem;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
new file mode 100644
index 00000000000..14a6a93da7b
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -0,0 +1,107 @@
+import { Icon, type MenuProps } from '@lobehub/ui';
+import { App } from 'antd';
+import { ExternalLink, LucideCopy, PencilLine, Trash, Wand2 } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isDesktop } from '@/const/version';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+interface TopicItemDropdownMenuProps {
+ id?: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+export const useTopicItemDropdownMenu = ({
+ id,
+ toggleEditing,
+}: TopicItemDropdownMenuProps): MenuProps['items'] => {
+ const { t } = useTranslation(['topic', 'common']);
+ const { modal } = App.useApp();
+
+ const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+
+ const [autoRenameTopicTitle, duplicateTopic, removeTopic] = useChatStore((s) => [
+ s.autoRenameTopicTitle,
+ s.duplicateTopic,
+ s.removeTopic,
+ ]);
+
+ return useMemo(() => {
+ if (!id) return [];
+
+ return [
+ {
+ icon: <Icon icon={Wand2} />,
+ key: 'autoRename',
+ label: t('actions.autoRename'),
+ onClick: () => {
+ autoRenameTopicTitle(id);
+ },
+ },
+ {
+ icon: <Icon icon={PencilLine} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: () => {
+ toggleEditing(true);
+ },
+ },
+ ...(isDesktop
+ ? [
+ {
+ icon: <Icon icon={ExternalLink} />,
+ key: 'openInNewWindow',
+ label: t('actions.openInNewWindow'),
+ onClick: () => {
+ if (activeAgentId) openTopicInNewWindow(activeAgentId, id);
+ },
+ },
+ ]
+ : []),
+ {
+ type: 'divider' as const,
+ },
+ {
+ icon: <Icon icon={LucideCopy} />,
+ key: 'duplicate',
+ label: t('actions.duplicate'),
+ onClick: () => {
+ duplicateTopic(id);
+ },
+ },
+ {
+ type: 'divider' as const,
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: () => {
+ modal.confirm({
+ centered: true,
+ okButtonProps: { danger: true },
+ onOk: async () => {
+ await removeTopic(id);
+ },
+ title: t('actions.confirmRemoveTopic'),
+ });
+ },
+ },
+ ].filter(Boolean) as MenuProps['items'];
+ }, [
+ id,
+ activeAgentId,
+ autoRenameTopicTitle,
+ duplicateTopic,
+ removeTopic,
+ openTopicInNewWindow,
+ toggleEditing,
+ t,
+ modal,
+ ]);
+};
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/index.tsx
new file mode 100644
index 00000000000..1946b378e9d
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/index.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useFetchTopics } from '@/hooks/useFetchTopics';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+import { TopicDisplayMode } from '@/types/topic';
+
+import AllTopicsDrawer from '../AllTopicsDrawer';
+import ByTimeMode from '../TopicListContent/ByTimeMode';
+import FlatMode from '../TopicListContent/FlatMode';
+
+const TopicList = memo(() => {
+ const { t } = useTranslation('topic');
+ const router = useQueryRoute();
+ const topicLength = useChatStore((s) => topicSelectors.currentTopicLength(s));
+ const isUndefinedTopics = useChatStore((s) => topicSelectors.isUndefinedTopics(s));
+ const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
+ const [allTopicsDrawerOpen, closeAllTopicsDrawer] = useChatStore((s) => [
+ s.allTopicsDrawerOpen,
+ s.closeAllTopicsDrawer,
+ ]);
+
+ const [topicDisplayMode] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s)]);
+
+ useFetchTopics();
+
+ // Show skeleton when current session's topic data is not yet loaded
+ if (isUndefinedTopics) return <SkeletonList />;
+
+ return (
+ <>
+ {topicLength === 0 && activeGroupId && (
+ <EmptyNavItem
+ onClick={() => {
+ router.push(urlJoin('/group', activeGroupId));
+ }}
+ title={t('actions.addNewTopic')}
+ />
+ )}
+ {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ <AllTopicsDrawer onClose={closeAllTopicsDrawer} open={allTopicsDrawerOpen} />
+ </>
+ );
+});
+
+export default TopicList;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
new file mode 100644
index 00000000000..083214c93fc
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
@@ -0,0 +1,57 @@
+import { AccordionItem, Icon, Text } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import { HashIcon } from 'lucide-react';
+import React, { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { GroupedTopic } from '@/types/topic';
+
+import TopicItem from '../../List/Item';
+
+const preformat = (id: string) =>
+ id.startsWith('20') ? (id.includes('-') ? dayjs(id).format('MMMM') : id) : undefined;
+
+interface GroupItemProps {
+ activeThreadId?: string;
+ activeTopicId?: string;
+ group: GroupedTopic;
+}
+
+const GroupItem = memo<GroupItemProps>(({ group, activeTopicId, activeThreadId }) => {
+ const { t } = useTranslation('topic');
+ const { id, title, children } = group;
+
+ const timeTitle = useMemo(() => preformat(id) ?? t(`groupTitle.byTime.${id}` as any), [id, t]);
+
+ return (
+ <AccordionItem
+ itemKey={id}
+ paddingBlock={4}
+ paddingInline={'8px 4px'}
+ title={
+ <Flexbox align="center" gap={6} height={24} horizontal style={{ overflow: 'hidden' }}>
+ <Icon icon={HashIcon} style={{ opacity: 0.5 }} />
+ <Text ellipsis fontSize={12} style={{ flex: 1 }} type={'secondary'} weight={500}>
+ {title || timeTitle}
+ </Text>
+ </Flexbox>
+ }
+ >
+ <Flexbox gap={1} paddingBlock={1}>
+ {children.map((topic) => (
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ key={topic.id}
+ threadId={activeThreadId}
+ title={topic.title}
+ />
+ ))}
+ </Flexbox>
+ </AccordionItem>
+ );
+});
+
+export default GroupItem;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
new file mode 100644
index 00000000000..87262ba2d7c
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { Accordion } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { MoreHorizontal } from 'lucide-react';
+import React, { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import GroupItem from './GroupItem';
+
+const ByTimeMode = memo(() => {
+ const { t } = useTranslation('topic');
+ const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+
+ const [hasMore, isExpandingPageSize, openAllTopicsDrawer] = useChatStore((s) => [
+ topicSelectors.hasMoreTopics(s),
+ topicSelectors.isExpandingPageSize(s),
+ s.openAllTopicsDrawer,
+ ]);
+ const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);
+ const groupTopics = useChatStore(topicSelectors.groupedTopicsForSidebar(topicPageSize), isEqual);
+
+ const [topicGroupKeys, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.topicGroupKeys(s),
+ s.updateSystemStatus,
+ ]);
+
+ const expandedKeys = useMemo(() => {
+ return topicGroupKeys || groupTopics.map((group) => group.id);
+ }, [topicGroupKeys, groupTopics]);
+
+ return (
+ <Flexbox gap={2}>
+ {/* Grouped topics */}
+ <Accordion
+ expandedKeys={expandedKeys}
+ gap={2}
+ onExpandedChange={(keys) => updateSystemStatus({ expandTopicGroupKeys: keys as any })}
+ >
+ {groupTopics.map((group) => (
+ <GroupItem
+ activeThreadId={activeThreadId}
+ activeTopicId={activeTopicId}
+ group={group}
+ key={group.id}
+ />
+ ))}
+ </Accordion>
+ {isExpandingPageSize && <SkeletonList rows={3} />}
+ {hasMore && !isExpandingPageSize && (
+ <NavItem icon={MoreHorizontal} onClick={openAllTopicsDrawer} title={t('loadMore')} />
+ )}
+ </Flexbox>
+ );
+});
+
+ByTimeMode.displayName = 'ByTimeMode';
+
+export default ByTimeMode;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
new file mode 100644
index 00000000000..c847ef7bd7c
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { MoreHorizontal } from 'lucide-react';
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import TopicItem from '../../List/Item';
+
+const FlatMode = memo(() => {
+ const { t } = useTranslation('topic');
+ const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+
+ const [activeTopicId, activeThreadId, hasMore, isExpandingPageSize, openAllTopicsDrawer] =
+ useChatStore((s) => [
+ s.activeTopicId,
+ s.activeThreadId,
+ topicSelectors.hasMoreTopics(s),
+ topicSelectors.isExpandingPageSize(s),
+ s.openAllTopicsDrawer,
+ ]);
+
+ const activeTopicList = useChatStore(
+ topicSelectors.displayTopicsForSidebar(topicPageSize),
+ isEqual,
+ );
+
+ return (
+ <Flexbox gap={1}>
+ {activeTopicList?.map((topic) => (
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ key={topic.id}
+ threadId={activeThreadId}
+ title={topic.title}
+ />
+ ))}
+ {isExpandingPageSize && <SkeletonList rows={3} />}
+ {hasMore && !isExpandingPageSize && (
+ <NavItem icon={MoreHorizontal} onClick={openAllTopicsDrawer} title={t('loadMore')} />
+ )}
+ </Flexbox>
+ );
+});
+
+FlatMode.displayName = 'FlatMode';
+
+export default FlatMode;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx
new file mode 100644
index 00000000000..88653feabb1
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import { Text } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Center } from 'react-layout-kit';
+
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import TopicItem from '../../List/Item';
+
+const SearchResult = memo(() => {
+ const { t } = useTranslation('topic');
+ const [activeTopicId, isSearchingTopic] = useChatStore((s) => [
+ s.activeTopicId,
+ topicSelectors.isSearchingTopic(s),
+ ]);
+ const topics = useChatStore(topicSelectors.searchTopics, isEqual);
+
+ if (isSearchingTopic) return <SkeletonList />;
+
+ if (topics.length === 0)
+ return (
+ <Center paddingBlock={12}>
+ <Text type={'secondary'}>{t('searchResultEmpty')}</Text>
+ </Center>
+ );
+
+ return (
+ <>
+ {topics.map((topic) => (
+ <TopicItem
+ active={activeTopicId === topic.id}
+ fav={topic.favorite}
+ id={topic.id}
+ key={topic.id}
+ title={topic.title}
+ />
+ ))}
+ </>
+ );
+});
+
+SearchResult.displayName = 'SearchResult';
+
+export default SearchResult;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
new file mode 100644
index 00000000000..97e77c89bf9
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
@@ -0,0 +1,26 @@
+import { ActionIcon, Dropdown, type MenuProps } from '@lobehub/ui';
+import { MoreHorizontalIcon } from 'lucide-react';
+import { memo } from 'react';
+
+interface ActionProps {
+ dropdownMenu: MenuProps['items'];
+}
+
+const Actions = memo<ActionProps>(({ dropdownMenu }) => {
+ return (
+ <Dropdown
+ arrow={false}
+ menu={{
+ items: dropdownMenu,
+ onClick: ({ domEvent }) => {
+ domEvent.stopPropagation();
+ },
+ }}
+ trigger={['click']}
+ >
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} />
+ </Dropdown>
+ );
+});
+
+export default Actions;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx
new file mode 100644
index 00000000000..ff665e84074
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx
@@ -0,0 +1,66 @@
+import { Input } from '@lobehub/ui';
+import { Popover } from 'antd';
+import { memo, useCallback, useState } from 'react';
+
+import { useChatStore } from '@/store/chat';
+
+interface EditingProps {
+ id: string;
+ title: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {
+ const [newTitle, setNewTitle] = useState(title);
+ const [editing, updateThreadTitle] = useChatStore((s) => [
+ s.threadRenamingId === id,
+ s.updateThreadTitle,
+ ]);
+
+ const handleUpdate = useCallback(async () => {
+ if (newTitle && title !== newTitle) {
+ await updateThreadTitle(id, newTitle);
+ }
+ toggleEditing(false);
+ }, [newTitle, title, id, updateThreadTitle, toggleEditing]);
+
+ return (
+ <Popover
+ arrow={false}
+ content={
+ <Input
+ autoFocus
+ defaultValue={title}
+ onBlur={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ onChange={(e) => setNewTitle(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ onPressEnter={() => {
+ handleUpdate();
+ toggleEditing(false);
+ }}
+ />
+ }
+ destroyOnHidden
+ onOpenChange={(open) => {
+ if (!open) handleUpdate();
+ toggleEditing(open);
+ }}
+ open={editing}
+ placement={'bottomLeft'}
+ styles={{
+ body: {
+ padding: 4,
+ width: 320,
+ },
+ }}
+ trigger={['click']}
+ >
+ <div />
+ </Popover>
+ );
+});
+
+export default Editing;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
new file mode 100644
index 00000000000..1454db297d5
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
@@ -0,0 +1,70 @@
+import { Dropdown, Icon } from '@lobehub/ui';
+import { TreeDownRightIcon } from '@lobehub/ui/icons';
+import { useTheme } from 'antd-style';
+import { memo, useCallback } from 'react';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useChatStore } from '@/store/chat';
+
+import { useThreadNavigation } from '../../../hooks/useThreadNavigation';
+import Actions from './Actions';
+import Editing from './Editing';
+import { useThreadItemDropdownMenu } from './useDropdownMenu';
+
+export interface ThreadItemProps {
+ id: string;
+ index: number;
+ title: string;
+}
+
+const ThreadItem = memo<ThreadItemProps>(({ title, id }) => {
+ const theme = useTheme();
+ const [editing, activeThreadId] = useChatStore((s) => [
+ s.threadRenamingId === id,
+ s.activeThreadId,
+ ]);
+
+ const { navigateToThread, isInAgentSubRoute } = useThreadNavigation();
+
+ const toggleEditing = useCallback(
+ (visible?: boolean) => {
+ useChatStore.setState({ threadRenamingId: visible ? id : '' });
+ },
+ [id],
+ );
+
+ const handleClick = useCallback(() => {
+ if (editing) return;
+ navigateToThread(id);
+ }, [editing, id, navigateToThread]);
+
+ const dropdownMenu = useThreadItemDropdownMenu({
+ id,
+ toggleEditing,
+ });
+
+ const active = id === activeThreadId;
+
+ return (
+ <>
+ <Dropdown
+ menu={{
+ items: dropdownMenu,
+ }}
+ trigger={['contextMenu']}
+ >
+ <NavItem
+ actions={<Actions dropdownMenu={dropdownMenu} />}
+ active={active && !isInAgentSubRoute}
+ disabled={editing}
+ icon={<Icon color={theme.colorTextDescription} icon={TreeDownRightIcon} size={'small'} />}
+ onClick={handleClick}
+ title={title}
+ />
+ </Dropdown>
+ <Editing id={id} title={title} toggleEditing={toggleEditing} />
+ </>
+ );
+});
+
+export default ThreadItem;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
new file mode 100644
index 00000000000..76e817a25ff
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
@@ -0,0 +1,54 @@
+import { Icon, type MenuProps } from '@lobehub/ui';
+import { App } from 'antd';
+import { PencilLine, Trash } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+
+interface ThreadItemDropdownMenuProps {
+ id: string;
+ toggleEditing: (visible?: boolean) => void;
+}
+
+export const useThreadItemDropdownMenu = ({
+ id,
+ toggleEditing,
+}: ThreadItemDropdownMenuProps): MenuProps['items'] => {
+ const { t } = useTranslation(['thread', 'common']);
+ const { modal } = App.useApp();
+
+ const [removeThread] = useChatStore((s) => [s.removeThread]);
+
+ return useMemo(() => {
+ return [
+ {
+ icon: <Icon icon={PencilLine} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: () => {
+ toggleEditing(true);
+ },
+ },
+ {
+ type: 'divider' as const,
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: () => {
+ modal.confirm({
+ centered: true,
+ okButtonProps: { danger: true },
+ onOk: async () => {
+ await removeThread(id);
+ },
+ title: t('actions.confirmRemoveThread'),
+ });
+ },
+ },
+ ].filter(Boolean) as MenuProps['items'];
+ }, [id, removeThread, toggleEditing, t, modal]);
+};
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx
new file mode 100644
index 00000000000..6db2180c240
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx
@@ -0,0 +1,29 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { useFetchThreads } from '@/hooks/useFetchThreads';
+import { useChatStore } from '@/store/chat';
+import { threadSelectors } from '@/store/chat/selectors';
+
+import ThreadItem from './ThreadItem';
+
+const ThreadList = memo(() => {
+ const [id] = useChatStore((s) => [s.activeTopicId]);
+ const threads = useChatStore(threadSelectors.getThreadsByTopic(id));
+
+ useFetchThreads(id);
+
+ if (!threads || threads.length === 0) return;
+
+ return (
+ <Flexbox gap={1} paddingBlock={1}>
+ {threads?.map((item, index) => (
+ <ThreadItem id={item.id} index={index} key={item.id} title={item.title} />
+ ))}
+ </Flexbox>
+ );
+});
+
+ThreadList.displayName = 'ThreadList';
+
+export default ThreadList;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/index.tsx
new file mode 100644
index 00000000000..6def1c6e6cf
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicListContent/index.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import React, { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useFetchTopics } from '@/hooks/useFetchTopics';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+import { TopicDisplayMode } from '@/types/topic';
+
+import ByTimeMode from './ByTimeMode';
+import FlatMode from './FlatMode';
+import SearchResult from './SearchResult';
+
+const TopicListContent = memo(() => {
+ const { t } = useTranslation('topic');
+ const router = useQueryRoute();
+ const topicLength = useChatStore((s) => topicSelectors.currentTopicLength(s));
+ const [isUndefinedTopics, isInSearchMode] = useChatStore((s) => [
+ topicSelectors.isUndefinedTopics(s),
+ topicSelectors.isInSearchMode(s),
+ ]);
+ const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
+ const [topicDisplayMode] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s)]);
+
+ useFetchTopics();
+
+ if (isInSearchMode) return <SearchResult />;
+
+ // Show skeleton when current session's topic data is not yet loaded
+ if (isUndefinedTopics) return <SkeletonList />;
+
+ return (
+ <>
+ {topicLength === 0 && activeGroupId && (
+ <EmptyNavItem
+ onClick={() => {
+ router.push(urlJoin('/group', activeGroupId));
+ }}
+ title={t('actions.addNewTopic')}
+ />
+ )}
+ {topicDisplayMode === TopicDisplayMode.ByTime ? <ByTimeMode /> : <FlatMode />}
+ </>
+ );
+});
+
+TopicListContent.displayName = 'TopicListContent';
+
+export default TopicListContent;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicSearchBar/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicSearchBar/index.tsx
new file mode 100644
index 00000000000..27784d8156c
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/TopicSearchBar/index.tsx
@@ -0,0 +1,59 @@
+'use client';
+
+import { SearchBar } from '@lobehub/ui';
+import { useUnmount } from 'ahooks';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { useServerConfigStore } from '@/store/serverConfig';
+
+const TopicSearchBar = memo<{ onClear?: () => void }>(({ onClear }) => {
+ const { t } = useTranslation('topic');
+
+ const [tempValue, setTempValue] = useState('');
+ const [searchKeyword, setSearchKeywords] = useState('');
+ const mobile = useServerConfigStore((s) => s.isMobile);
+ const [activeAgentId, useSearchTopics] = useChatStore((s) => [
+ s.activeAgentId,
+ s.useSearchTopics,
+ ]);
+
+ useSearchTopics(searchKeyword, { agentId: activeAgentId });
+
+ useUnmount(() => {
+ useChatStore.setState({ inSearchingMode: false, isSearchingTopic: false });
+ });
+
+ const startSearchTopic = () => {
+ if (tempValue === searchKeyword) return;
+
+ setSearchKeywords(tempValue);
+ useChatStore.setState({ inSearchingMode: !!tempValue, isSearchingTopic: !!tempValue });
+ };
+
+ return (
+ <SearchBar
+ autoFocus
+ onBlur={() => {
+ if (tempValue === '') {
+ onClear?.();
+
+ return;
+ }
+
+ startSearchTopic();
+ }}
+ onChange={(e) => {
+ setTempValue(e.target.value);
+ }}
+ onPressEnter={startSearchTopic}
+ placeholder={t('searchPlaceholder')}
+ spotlight={!mobile}
+ value={tempValue}
+ variant={'filled'}
+ />
+ );
+});
+
+export default TopicSearchBar;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
new file mode 100644
index 00000000000..b78c1cb1a34
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
@@ -0,0 +1,49 @@
+import { usePathname } from 'next/navigation';
+import { useCallback } from 'react';
+import { useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+/**
+ * Hook to handle thread navigation with automatic route detection
+ * If in agent sub-route (e.g., /agent/:aid/profile), navigate back to chat first
+ */
+export const useThreadNavigation = () => {
+ const pathname = usePathname();
+ const params = useParams();
+ const router = useQueryRoute();
+ const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
+ const switchThread = useChatStore((s) => s.switchThread);
+
+ const isInAgentSubRoute = useCallback(() => {
+ if (!params.aid) return false;
+ const agentBasePath = `/agent/${params.aid}`;
+ // If pathname has more segments after /agent/:aid, it's a sub-route
+ return (
+ pathname.startsWith(agentBasePath) &&
+ pathname !== agentBasePath &&
+ pathname !== `${agentBasePath}/`
+ );
+ }, [pathname, params.aid]);
+
+ const navigateToThread = useCallback(
+ (threadId: string) => {
+ // If in agent sub-route, navigate back to agent chat first
+ if (isInAgentSubRoute() && params.aid) {
+ router.push(urlJoin('/agent', params.aid as string));
+ }
+
+ switchThread(threadId);
+ toggleConfig(false);
+ },
+ [params.aid, router, switchThread, toggleConfig, isInAgentSubRoute],
+ );
+
+ return {
+ isInAgentSubRoute: isInAgentSubRoute(),
+ navigateToThread,
+ };
+};
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
new file mode 100644
index 00000000000..16acaede85a
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
@@ -0,0 +1,49 @@
+import { usePathname } from 'next/navigation';
+import { useCallback } from 'react';
+import { useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+/**
+ * Hook to handle topic navigation with automatic route detection
+ * If in agent sub-route (e.g., /agent/:aid/profile), navigate back to chat first
+ */
+export const useTopicNavigation = () => {
+ const pathname = usePathname();
+ const params = useParams();
+ const router = useQueryRoute();
+ const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
+ const switchTopic = useChatStore((s) => s.switchTopic);
+
+ const isInAgentSubRoute = useCallback(() => {
+ if (!params.aid) return false;
+ const agentBasePath = `/agent/${params.aid}`;
+ // If pathname has more segments after /agent/:aid, it's a sub-route
+ return (
+ pathname.startsWith(agentBasePath) &&
+ pathname !== agentBasePath &&
+ pathname !== `${agentBasePath}/`
+ );
+ }, [pathname, params.aid]);
+
+ const navigateToTopic = useCallback(
+ (topicId?: string) => {
+ // If in agent sub-route, navigate back to agent chat first
+ if (isInAgentSubRoute() && params.aid) {
+ router.push(urlJoin('/agent', params.aid as string));
+ }
+
+ switchTopic(topicId);
+ toggleConfig(false);
+ },
+ [params.aid, router, switchTopic, toggleConfig, isInAgentSubRoute],
+ );
+
+ return {
+ isInAgentSubRoute: isInAgentSubRoute(),
+ navigateToTopic,
+ };
+};
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/index.tsx
new file mode 100644
index 00000000000..cbe84bbe07a
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/index.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { AccordionItem, Dropdown, Text } from '@lobehub/ui';
+import React, { Suspense, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import Actions from './Actions';
+import List from './List';
+import { useTopicActionsDropdownMenu } from './useDropdownMenu';
+
+interface TopicProps {
+ itemKey: string;
+}
+
+const Topic = memo<TopicProps>(({ itemKey }) => {
+ const { t } = useTranslation(['topic', 'common']);
+ const [topicCount] = useChatStore((s) => [topicSelectors.currentTopicCount(s)]);
+ const dropdownMenu = useTopicActionsDropdownMenu();
+
+ return (
+ <AccordionItem
+ action={<Actions />}
+ headerWrapper={(header) => (
+ <Dropdown
+ menu={{
+ items: dropdownMenu,
+ }}
+ trigger={['contextMenu']}
+ >
+ {header}
+ </Dropdown>
+ )}
+ itemKey={itemKey}
+ paddingBlock={4}
+ paddingInline={'8px 4px'}
+ title={
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {`${t('title')} ${topicCount > 0 ? topicCount : ''}`}
+ </Text>
+ }
+ >
+ <Suspense fallback={<SkeletonList />}>
+ <Flexbox gap={1} paddingBlock={1}>
+ <List />
+ </Flexbox>
+ </Suspense>
+ </AccordionItem>
+ );
+});
+
+export default Topic;
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
new file mode 100644
index 00000000000..beef73fc002
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -0,0 +1,109 @@
+import { Icon, type MenuProps } from '@lobehub/ui';
+import { App } from 'antd';
+import { Hash, LucideCheck, Trash } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+import { TopicDisplayMode } from '@/types/topic';
+
+export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {
+ const { t } = useTranslation(['topic', 'common']);
+ const { modal } = App.useApp();
+
+ const [removeUnstarredTopic, removeAllTopic] = useChatStore((s) => [
+ s.removeUnstarredTopic,
+ s.removeSessionTopics,
+ ]);
+
+ const [topicDisplayMode, updatePreference] = useUserStore((s) => [
+ preferenceSelectors.topicDisplayMode(s),
+ s.updatePreference,
+ ]);
+
+ const [topicPageSize, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.topicPageSize(s),
+ s.updateSystemStatus,
+ ]);
+
+ return useMemo(() => {
+ const displayModeItems = Object.values(TopicDisplayMode).map((mode) => ({
+ icon: topicDisplayMode === mode ? <Icon icon={LucideCheck} /> : <div />,
+ key: mode,
+ label: t(`groupMode.${mode}`),
+ onClick: () => {
+ updatePreference({ topicDisplayMode: mode });
+ },
+ }));
+
+ const pageSizeOptions = [20, 40, 60, 100];
+ const pageSizeItems = pageSizeOptions.map((size) => ({
+ icon: topicPageSize === size ? <Icon icon={LucideCheck} /> : <div />,
+ key: `pageSize-${size}`,
+ label: `${size} 个条目`,
+ onClick: () => {
+ updateSystemStatus({ topicPageSize: size });
+ },
+ }));
+
+ return [
+ ...displayModeItems,
+ {
+ type: 'divider' as const,
+ },
+ {
+ children: pageSizeItems,
+ icon: <Icon icon={Hash} />,
+ key: 'displayItems',
+ label: t('displayItems'),
+ },
+ {
+ type: 'divider' as const,
+ },
+ {
+ icon: <Icon icon={Trash} />,
+ key: 'deleteUnstarred',
+ label: t('actions.removeUnstarred'),
+ onClick: () => {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ centered: true,
+ okButtonProps: { danger: true },
+ okText: t('ok', { ns: 'common' }),
+ onOk: removeUnstarredTopic,
+ title: t('actions.confirmRemoveUnstarred'),
+ });
+ },
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'deleteAll',
+ label: t('actions.removeAll'),
+ onClick: () => {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ centered: true,
+ okButtonProps: { danger: true },
+ okText: t('ok', { ns: 'common' }),
+ onOk: removeAllTopic,
+ title: t('actions.confirmRemoveAll'),
+ });
+ },
+ },
+ ].filter(Boolean) as MenuProps['items'];
+ }, [
+ topicDisplayMode,
+ topicPageSize,
+ updatePreference,
+ updateSystemStatus,
+ removeUnstarredTopic,
+ removeAllTopic,
+ t,
+ modal,
+ ]);
+};
diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/index.tsx
new file mode 100644
index 00000000000..72736d62ca7
--- /dev/null
+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/index.tsx
@@ -0,0 +1,19 @@
+import React, { memo } from 'react';
+
+import { NavPanelPortal } from '@/features/NavPanel';
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import Body from './Body';
+import Header from './Header';
+
+const Sidebar = memo(() => {
+ return (
+ <NavPanelPortal navKey="group">
+ <SideBarLayout body={<Body />} header={<Header />} />
+ </NavPanelPortal>
+ );
+});
+
+Sidebar.displayName = 'ChatSidebar';
+
+export default Sidebar;
diff --git a/src/app/[variants]/(main)/chat/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/group/_layout/index.tsx
similarity index 51%
rename from src/app/[variants]/(main)/chat/_layout/Desktop/index.tsx
rename to src/app/[variants]/(main)/group/_layout/index.tsx
index 870b563cd7e..ed686a6f886 100644
--- a/src/app/[variants]/(main)/chat/_layout/Desktop/index.tsx
+++ b/src/app/[variants]/(main)/group/_layout/index.tsx
@@ -1,35 +1,43 @@
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
import { Outlet } from 'react-router-dom';
import { isDesktop } from '@/const/version';
import ProtocolUrlHandler from '@/features/ProtocolUrlHandler';
+import { useInitGroupConfig } from '@/hooks/useInitGroupConfig';
+import GroupIdSync from './GroupIdSync';
import RegisterHotkeys from './RegisterHotkeys';
-import SessionPanel from './SessionPanel';
-import Workspace from './Workspace';
+import Sidebar from './Sidebar';
+
+const Layout = memo(() => {
+ const theme = useTheme();
+ useInitGroupConfig();
-const Layout = () => {
return (
<>
+ <Sidebar />
<Flexbox
+ flex={1}
height={'100%'}
- horizontal
- style={{ maxWidth: '100%', overflow: 'hidden', position: 'relative' }}
- width={'100%'}
+ style={{
+ background: theme.colorBgContainer,
+ overflow: 'hidden',
+ position: 'relative',
+ }}
>
- <SessionPanel />
- <Workspace>
- <Outlet />
- </Workspace>
+ <Outlet />
</Flexbox>
{/* ↓ cloud slot ↓ */}
{/* ↑ cloud slot ↑ */}
<RegisterHotkeys />
{isDesktop && <ProtocolUrlHandler />}
+ <GroupIdSync />
</>
);
-};
+});
Layout.displayName = 'DesktopChatLayout';
diff --git a/src/app/[variants]/(main)/group/features/ChangelogModal.tsx b/src/app/[variants]/(main)/group/features/ChangelogModal.tsx
new file mode 100644
index 00000000000..b4c63dffd08
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/ChangelogModal.tsx
@@ -0,0 +1,11 @@
+import ChangelogModal from '@/features/ChangelogModal';
+import { ChangelogService } from '@/server/services/changelog';
+
+const Changelog = async () => {
+ const service = new ChangelogService();
+ const id = await service.getLatestChangelogId();
+
+ return <ChangelogModal currentId={id} />;
+};
+
+export default Changelog;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/AddButton.tsx b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/AddButton.tsx
new file mode 100644
index 00000000000..87107f48f77
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/AddButton.tsx
@@ -0,0 +1,32 @@
+import { Button } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { useActionSWR } from '@/libs/swr';
+import { useSessionStore } from '@/store/session';
+
+const AddButton = memo(() => {
+ const createSession = useSessionStore((s) => s.createSession);
+ const { mutate, isValidating } = useActionSWR(['session.createSession', undefined], () => {
+ return createSession({ group: undefined });
+ });
+
+ return (
+ <Button
+ loading={isValidating}
+ onClick={() => mutate()}
+ style={{
+ alignItems: 'center',
+ borderRadius: 4,
+ height: '20px',
+ justifyContent: 'center',
+ padding: '0 1px',
+ width: '20px',
+ }}
+ variant={'filled'}
+ >
+ +
+ </Button>
+ );
+});
+
+export default AddButton;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/OpeningQuestions.tsx b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
similarity index 87%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/OpeningQuestions.tsx
rename to src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
index dfa509b22f4..5d5684395f5 100644
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/WelcomeChatItem/AgentWelcome/OpeningQuestions.tsx
+++ b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
@@ -8,14 +8,13 @@ import { Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
-import { useSend } from '../../../ChatInput/useSend';
+// import { useSend } from '../../features/ChatInput/useSend';
const useStyles = createStyles(({ css, token, responsive }) => ({
card: css`
padding-block: 8px;
padding-inline: 16px;
border-radius: 48px;
- background: ${token.colorBgContainer};
${responsive.mobile} {
padding-block: 8px;
@@ -43,7 +42,7 @@ const OpeningQuestions = memo<OpeningQuestionsProps>(({ mobile, questions }) =>
const [updateMessageInput] = useChatStore((s) => [s.updateMessageInput]);
const { styles } = useStyles();
- const { send: sendMessage } = useSend();
+ // const { send: sendMessage } = useSend();
return (
<div className={styles.container}>
@@ -57,11 +56,11 @@ const OpeningQuestions = memo<OpeningQuestionsProps>(({ mobile, questions }) =>
key={question}
onClick={() => {
updateMessageInput(question);
- sendMessage({ isWelcomeQuestion: true });
+ // sendMessage({ isWelcomeQuestion: true });
}}
paddingBlock={8}
paddingInline={12}
- variant={'outlined'}
+ variant={'filled'}
>
{question}
</Block>
diff --git a/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/ToolAuthAlert.tsx b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/ToolAuthAlert.tsx
new file mode 100644
index 00000000000..6c6b7c66aad
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/ToolAuthAlert.tsx
@@ -0,0 +1,2 @@
+// Re-export from chat version to avoid code duplication
+export { default } from '@/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert';
diff --git a/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/index.tsx
new file mode 100644
index 00000000000..4676378fb8b
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/index.tsx
@@ -0,0 +1,104 @@
+'use client';
+
+import { Markdown, Text } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import React, { memo, useMemo } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import SupervisorAvatar from '@/app/[variants]/(main)/group/features/GroupAvatar';
+import { useIsMobile } from '@/hooks/useIsMobile';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { agentGroupSelectors, useAgentGroupStore } from '@/store/agentGroup';
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+
+import AddButton from './AddButton';
+import OpeningQuestions from './OpeningQuestions';
+import ToolAuthAlert from './ToolAuthAlert';
+
+const InboxWelcome = memo(() => {
+ const { t } = useTranslation(['welcome', 'chat']);
+ const mobile = useIsMobile();
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const fontSize = useUserStore(userGeneralSettingsSelectors.fontSize);
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const [groupMeta] = useAgentGroupStore((s) => [agentGroupSelectors.currentGroupMeta(s)]);
+
+ // Use group config for opening message and questions
+ const groupOpeningMessage = useAgentGroupStore(agentGroupSelectors.currentGroupOpeningMessage);
+ const groupOpeningQuestions = useAgentGroupStore(
+ agentGroupSelectors.currentGroupOpeningQuestions,
+ isEqual,
+ );
+
+ const agentSystemRoleMsg = t('agentDefaultMessageWithSystemRole', {
+ name: meta.title || t('defaultAgent', { ns: 'chat' }),
+ ns: 'chat',
+ });
+
+ // Get agent opening message and questions (always call hooks)
+ const agentOpeningMessage = useAgentStore(agentSelectors.openingMessage);
+ const agentOpeningQuestions = useAgentStore(agentSelectors.openingQuestions, isEqual);
+
+ // Prefer group opening message/questions over agent's
+ const openingMessage = groupOpeningMessage || agentOpeningMessage;
+ const openingQuestions =
+ groupOpeningQuestions.length > 0 ? groupOpeningQuestions : agentOpeningQuestions;
+
+ const message = useMemo(() => {
+ if (openingMessage) return openingMessage;
+ return agentSystemRoleMsg;
+ }, [openingMessage, agentSystemRoleMsg, meta.description]);
+
+ const displayTitle = groupMeta.title;
+
+ return (
+ <>
+ <Flexbox flex={1} />
+ <Flexbox
+ gap={12}
+ style={{
+ paddingBottom: 'max(10vh, 32px)',
+ }}
+ width={'100%'}
+ >
+ <SupervisorAvatar size={78} />
+ <Text fontSize={32} weight={'bold'}>
+ {displayTitle}
+ </Text>
+ <Flexbox width={'min(100%, 640px)'}>
+ <Markdown
+ customRender={(dom, context) => {
+ if (context.text.includes('<plus />')) {
+ return (
+ <Trans
+ components={{
+ br: <br />,
+ plus: <AddButton />,
+ }}
+ i18nKey="guide.defaultMessage"
+ ns="welcome"
+ values={{ appName: 'Lobe AI' }}
+ />
+ );
+ }
+ return dom;
+ }}
+ fontSize={fontSize}
+ variant={'chat'}
+ >
+ {isInbox ? t('guide.defaultMessage', { appName: 'Lobe AI' }) : message}
+ </Markdown>
+ </Flexbox>
+ {openingQuestions.length > 0 && (
+ <OpeningQuestions mobile={mobile} questions={openingQuestions} />
+ )}
+ <ToolAuthAlert />
+ </Flexbox>
+ </>
+ );
+});
+
+export default InboxWelcome;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/ChatHydration/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/ChatHydration/index.tsx
new file mode 100644
index 00000000000..000986714cf
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/ChatHydration/index.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { memo, useLayoutEffect } from 'react';
+import { createStoreUpdater } from 'zustand-utils';
+
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useChatStore } from '@/store/chat';
+
+// sync outside state to useChatStore
+const ChatHydration = memo(() => {
+ const useStoreUpdater = createStoreUpdater(useChatStore);
+
+ // two-way bindings the topic params to chat store
+ const [topic, setTopic] = useQueryState('topic', { history: 'replace', throttleMs: 500 });
+ const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });
+ useStoreUpdater('activeTopicId', topic!);
+ useStoreUpdater('activeThreadId', thread!);
+
+ useLayoutEffect(() => {
+ const unsubscribeTopic = useChatStore.subscribe(
+ (s) => s.activeTopicId,
+ (state) => {
+ setTopic(!state ? null : state);
+ },
+ );
+ const unsubscribeThread = useChatStore.subscribe(
+ (s) => s.activeThreadId,
+ (state) => {
+ setThread(!state ? null : state);
+ },
+ );
+
+ return () => {
+ unsubscribeTopic();
+ unsubscribeThread();
+ };
+ }, [setTopic, setThread]); // ✅ 现在 setValue 是稳定的,可以安全地添加到依赖数组
+
+ return null;
+});
+
+export default ChatHydration;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/Thread.tsx b/src/app/[variants]/(main)/group/features/Conversation/ChatItem/Thread.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/Thread.tsx
rename to src/app/[variants]/(main)/group/features/Conversation/ChatItem/Thread.tsx
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/ThreadItem.tsx b/src/app/[variants]/(main)/group/features/Conversation/ChatItem/ThreadItem.tsx
similarity index 100%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatList/ChatItem/ThreadItem.tsx
rename to src/app/[variants]/(main)/group/features/Conversation/ChatItem/ThreadItem.tsx
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatMinimap/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/ChatMinimap/index.tsx
similarity index 88%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatMinimap/index.tsx
rename to src/app/[variants]/(main)/group/features/Conversation/ChatMinimap/index.tsx
index 8c31264549a..62348cc0b7f 100644
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatMinimap/index.tsx
+++ b/src/app/[variants]/(main)/group/features/Conversation/ChatMinimap/index.tsx
@@ -7,18 +7,11 @@ import debug from 'debug';
import isEqual from 'fast-deep-equal';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { markdownToTxt } from 'markdown-to-txt';
-import { memo, useCallback, useMemo, useState, useSyncExternalStore } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
-import {
- getVirtuaActiveIndex,
- getVirtuaGlobalRef,
- subscribeVirtuaActiveIndex,
- subscribeVirtuaGlobalRef,
-} from '@/features/ChatList/components/VirtualizedList/VirtuosoContext';
-import { useChatStore } from '@/store/chat';
-import { displayMessageSelectors } from '@/store/chat/selectors';
+import { conversationSelectors, useConversationStore } from '@/features/Conversation';
const log = debug('lobe-react:chat-minimap');
@@ -199,13 +192,10 @@ const ChatMinimap = memo(() => {
const { t } = useTranslation('chat');
const { styles, cx } = useStyles();
const [isHovered, setIsHovered] = useState(false);
- const virtuaRef = useSyncExternalStore(subscribeVirtuaGlobalRef, getVirtuaGlobalRef, () => null);
- const activeIndex = useSyncExternalStore(
- subscribeVirtuaActiveIndex,
- getVirtuaActiveIndex,
- () => null,
- );
- const messages = useChatStore(displayMessageSelectors.mainAIChats, isEqual);
+
+ const scrollMethods = useConversationStore(conversationSelectors.virtuaScrollMethods);
+ const activeIndex = useConversationStore(conversationSelectors.activeIndex);
+ const messages = useConversationStore(conversationSelectors.displayMessages, isEqual);
const theme = useTheme();
@@ -244,20 +234,14 @@ const ChatMinimap = memo(() => {
const handleJump = useCallback(
(virtIndex: number) => {
- virtuaRef?.current?.scrollToIndex(virtIndex, {
- align: 'start',
- // The current index detection will be off by 1, so we need to add 1 here
- offset: 6,
- smooth: true,
- });
+ scrollMethods?.scrollToIndex(virtIndex, { align: 'start', smooth: true });
},
- [virtuaRef],
+ [scrollMethods],
);
const handleStep = useCallback(
(direction: 'prev' | 'next') => {
- const ref = virtuaRef?.current;
- if (!ref || indicators.length === 0) return;
+ if (!scrollMethods || indicators.length === 0) return;
let targetPosition: number;
@@ -299,13 +283,9 @@ const ChatMinimap = memo(() => {
if (!targetIndicator) return;
- ref.scrollToIndex(targetIndicator.virtuosoIndex, {
- align: 'start',
- offset: 6,
- smooth: true,
- });
+ scrollMethods.scrollToIndex(targetIndicator.virtuosoIndex, { align: 'start', smooth: true });
},
- [activeIndex, activeIndicatorPosition, indicators, virtuaRef],
+ [activeIndex, activeIndicatorPosition, indicators, scrollMethods],
);
if (indicators.length <= MIN_MESSAGES) return null;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/ConversationArea.tsx b/src/app/[variants]/(main)/group/features/Conversation/ConversationArea.tsx
new file mode 100644
index 00000000000..efb1fab709b
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/ConversationArea.tsx
@@ -0,0 +1,140 @@
+'use client';
+
+import { MemoryManifest } from '@lobechat/builtin-tool-memory';
+import { Suspense, memo, useEffect, useMemo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ChatList, ConversationProvider } from '@/features/Conversation';
+import { useOperationState } from '@/hooks/useOperationState';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import WelcomeChatItem from './AgentWelcome';
+import ChatHydration from './ChatHydration';
+import ChatMinimap from './ChatMinimap';
+import MainChatInput from './MainChatInput';
+import MessageFromUrl from './MainChatInput/MessageFromUrl';
+import ThreadHydration from './ThreadHydration';
+import ZenModeToast from './ZenModeToast';
+import { useActionsBarConfig } from './useActionsBarConfig';
+import { useGroupContext } from './useGroupContext';
+
+// import { useGroupHooks } from './useGroupHooks';
+
+interface ConversationAreaProps {
+ mobile?: boolean;
+}
+
+/**
+ * ConversationArea
+ *
+ * Main conversation area component using the new ConversationStore architecture.
+ * Uses ChatList from @/features/Conversation and MainChatInput for custom features.
+ */
+const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {
+ const context = useGroupContext();
+
+ const enabledPlugins = useAgentStore(agentSelectors.currentAgentPlugins);
+ const [useFetchUserMemory, setActiveMemoryContext] = useUserMemoryStore((s) => [
+ s.useFetchUserMemory,
+ s.setActiveMemoryContext,
+ ]);
+ const [currentGroup, activeTopic] = [
+ useAgentGroupStore(agentGroupSelectors.currentGroup),
+ useChatStore(topicSelectors.currentActiveTopic),
+ ];
+
+ const isMemoryPluginEnabled = useMemo(() => {
+ if (!enabledPlugins) return false;
+
+ return enabledPlugins.includes(MemoryManifest.identifier);
+ }, [enabledPlugins]);
+
+ useEffect(() => {
+ if (!isMemoryPluginEnabled) {
+ setActiveMemoryContext(undefined);
+ return;
+ }
+
+ // Convert group to session format for MemorySearchSource compatibility
+ setActiveMemoryContext({
+ session: currentGroup
+ ? {
+ meta: {
+ description: currentGroup.description,
+ title: currentGroup.title,
+ },
+ }
+ : undefined,
+ topic: activeTopic,
+ });
+ }, [activeTopic, currentGroup, isMemoryPluginEnabled, setActiveMemoryContext]);
+
+ useFetchUserMemory(Boolean(isMemoryPluginEnabled && context.agentId));
+
+ // Get raw dbMessages from ChatStore for this context
+ // ConversationStore will parse them internally to generate displayMessages
+ const chatKey = useMemo(
+ () => messageMapKey(context),
+ [context.agentId, context.topicId, context.threadId],
+ );
+ const replaceMessages = useChatStore((s) => s.replaceMessages);
+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
+
+ // Get operation state from ChatStore for reactive updates
+ const operationState = useOperationState(context);
+
+ // Get actionsBar config with branching support from ChatStore
+ const actionsBarConfig = useActionsBarConfig();
+
+ // Get group-specific hooks for send logic
+ // const groupHooks = useGroupHooks(context);
+
+ return (
+ <ConversationProvider
+ actionsBar={actionsBarConfig}
+ context={context}
+ hasInitMessages={!!messages}
+ // hooks={groupHooks}
+ messages={messages}
+ onMessagesChange={(messages) => {
+ replaceMessages(messages, { context });
+ }}
+ operationState={operationState}
+ >
+ <ZenModeToast />
+ <Flexbox
+ flex={1}
+ style={{
+ overflowX: 'hidden',
+ overflowY: 'auto',
+ position: 'relative',
+ }}
+ width={'100%'}
+ >
+ <ChatList welcome={<WelcomeChatItem />} />
+ </Flexbox>
+ <MainChatInput />
+ <ChatHydration />
+ <ThreadHydration />
+ {!mobile && (
+ <>
+ <ChatMinimap />
+ <Suspense>
+ <MessageFromUrl />
+ </Suspense>
+ </>
+ )}
+ </ConversationProvider>
+ );
+});
+
+Conversation.displayName = 'ConversationArea';
+
+export default Conversation;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/GroupWelcome/useTemplateMatching.ts b/src/app/[variants]/(main)/group/features/Conversation/GroupWelcome/useTemplateMatching.ts
new file mode 100644
index 00000000000..6902b9bf446
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/GroupWelcome/useTemplateMatching.ts
@@ -0,0 +1,72 @@
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+interface TemplateMatch {
+ activities: Record<string, { description: string; emoji: string; prompt: string; title: string }>;
+ templateId: string;
+}
+
+export const useTemplateMatching = (): TemplateMatch | null => {
+ const { t } = useTranslation('welcome');
+ const groupTemplates = useGroupTemplates();
+ const currentGroup = useAgentGroupStore(agentGroupSelectors.currentGroup);
+ const currentGroupAgents = useAgentGroupStore(agentGroupSelectors.currentGroupAgents);
+
+ return useMemo(() => {
+ if (!currentGroup) {
+ console.warn('No group found:', { currentGroup });
+ return null;
+ }
+
+ const currentTitle = currentGroup.title || '';
+ const currentMemberCount = currentGroupAgents?.length || 0;
+
+ // Try to match by title and member count
+ for (const template of groupTemplates) {
+ const templateTitle = template.title;
+ const templateMemberCount = template.members.length;
+
+ // Check if titles match (case-insensitive) and member counts are similar (±1)
+ if (
+ templateTitle.toLowerCase() === currentTitle.toLowerCase() &&
+ Math.abs(templateMemberCount - currentMemberCount) <= 1
+ ) {
+ console.warn('Found exact match for template:', template.id);
+ // Get template-specific activities from i18n
+ const templateActivities = (t as any)(`guide.groupActivities.${template.id}`, {
+ returnObjects: true,
+ }) as Record<string, { description: string; emoji: string; prompt: string; title: string }>;
+
+ return {
+ activities: templateActivities || {},
+ templateId: template.id,
+ };
+ }
+ }
+
+ // If no exact match, try partial title matching
+ console.warn('No exact match found, trying partial matching...');
+ for (const template of groupTemplates) {
+ const templateTitle = template.title;
+
+ const currentIncludes = currentTitle.toLowerCase().includes(templateTitle.toLowerCase());
+ const templateIncludes = templateTitle.toLowerCase().includes(currentTitle.toLowerCase());
+
+ if (currentIncludes || templateIncludes) {
+ const templateActivities = (t as any)(`guide.groupActivities.${template.id}`, {
+ returnObjects: true,
+ }) as Record<string, { description: string; emoji: string; prompt: string; title: string }>;
+
+ return {
+ activities: templateActivities || {},
+ templateId: template.id,
+ };
+ }
+ }
+ return null;
+ }, [currentGroup, currentGroupAgents, groupTemplates, t]);
+};
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/ShareButton/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/ShareButton/index.tsx
new file mode 100644
index 00000000000..244b3c56f1d
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/ShareButton/index.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { Share2 } from 'lucide-react';
+import dynamic from 'next/dynamic';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DESKTOP_HEADER_ICON_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useWorkspaceModal } from '@/hooks/useWorkspaceModal';
+
+const ShareModal = dynamic(() => import('@/features/ShareModal'));
+
+interface ShareButtonProps {
+ mobile?: boolean;
+ open?: boolean;
+ setOpen?: (open: boolean) => void;
+}
+
+const ShareButton = memo<ShareButtonProps>(({ mobile, setOpen, open }) => {
+ const [isModalOpen, setIsModalOpen] = useWorkspaceModal(open, setOpen);
+ const { t } = useTranslation('common');
+
+ return (
+ <>
+ <ActionIcon
+ icon={Share2}
+ onClick={() => setIsModalOpen(true)}
+ size={mobile ? MOBILE_HEADER_ICON_SIZE : DESKTOP_HEADER_ICON_SIZE}
+ title={t('share')}
+ tooltipProps={{
+ placement: 'bottom',
+ }}
+ />
+ <ShareModal onCancel={() => setIsModalOpen(false)} open={isModalOpen} />
+ </>
+ );
+});
+
+export default ShareButton;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/HistoryLimitTags.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/HistoryLimitTags.tsx
new file mode 100644
index 00000000000..2068f42efe5
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/HistoryLimitTags.tsx
@@ -0,0 +1,26 @@
+import { Icon, Tag, Tooltip } from '@lobehub/ui';
+import { HistoryIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useAgentStore } from '@/store/agent';
+import { agentChatConfigSelectors } from '@/store/agent/selectors';
+
+const SearchTag = memo(() => {
+ const { t } = useTranslation('chat');
+ const historyCount = useAgentStore(agentChatConfigSelectors.historyCount);
+
+ return (
+ <Tooltip title={t('history.title', { count: historyCount })}>
+ <Flexbox height={22}>
+ <Tag>
+ <Icon icon={HistoryIcon} />
+ <span>{historyCount}</span>
+ </Tag>
+ </Flexbox>
+ </Tooltip>
+ );
+});
+
+export default SearchTag;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/KnowledgeTag.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/KnowledgeTag.tsx
new file mode 100644
index 00000000000..21369477e1a
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/KnowledgeTag.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { Dropdown, Icon, type MenuProps, Tag } from '@lobehub/ui';
+import { LibraryBig } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import KnowledgeIcon from '@/components/KnowledgeIcon';
+import { oneLineEllipsis } from '@/styles';
+import { KnowledgeItem } from '@/types/knowledgeBase';
+
+export interface PluginTagProps {
+ data: KnowledgeItem[];
+}
+
+const PluginTag = memo<PluginTagProps>(({ data }) => {
+ if (data.length === 0) return null;
+
+ const items: MenuProps['items'] = data.map((item) => ({
+ icon: <KnowledgeIcon fileType={item.fileType} name={item.name} type={item.type} />,
+ key: item.id,
+ label: <Flexbox style={{ paddingInlineStart: 8 }}>{item.name}</Flexbox>,
+ }));
+
+ const count = data.length;
+
+ return (
+ <Dropdown menu={{ items }}>
+ <div>
+ <Tag>
+ {<Icon icon={LibraryBig} />}
+ <div className={oneLineEllipsis} style={{ maxWidth: 140 }}>
+ {data[0].name}
+ </div>
+ {count > 1 && <div>({data.length - 1}+)</div>}
+ </Tag>
+ </div>
+ </Dropdown>
+ );
+});
+
+export default PluginTag;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/MemberCountTag.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/MemberCountTag.tsx
new file mode 100644
index 00000000000..b39ef5afaca
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/MemberCountTag.tsx
@@ -0,0 +1,30 @@
+import { Icon, Tag, Tooltip } from '@lobehub/ui';
+import { Users } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+const MemberCountTag = memo(() => {
+ const { t } = useTranslation('chat');
+ const currentGroupAgents = useAgentGroupStore(agentGroupSelectors.currentGroupAgents);
+
+ const memberCount = currentGroupAgents?.length ?? 0;
+
+ if (memberCount <= 0) return null;
+
+ return (
+ <Tooltip title={t('group.memberTooltip', { count: memberCount })}>
+ <Flexbox height={22}>
+ <Tag>
+ <Icon icon={Users} />
+ <span>{memberCount}</span>
+ </Tag>
+ </Flexbox>
+ </Tooltip>
+ );
+});
+
+export default MemberCountTag;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/SearchTags.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/SearchTags.tsx
new file mode 100644
index 00000000000..26dc629bf57
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/SearchTags.tsx
@@ -0,0 +1,20 @@
+import { Icon, Tag } from '@lobehub/ui';
+import { Globe } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+const SearchTag = memo(() => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <Flexbox height={22}>
+ <Tag>
+ {<Icon icon={Globe} />}
+ <div>{t('search.title')}</div>
+ </Tag>
+ </Flexbox>
+ );
+});
+
+export default SearchTag;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/index.tsx
new file mode 100644
index 00000000000..db310a6f548
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/Tags/index.tsx
@@ -0,0 +1,18 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import MemberCountTag from './MemberCountTag';
+
+/**
+ * TitleTags for Group context - always shows MemberCountTag
+ * since we're always in a group session here
+ */
+const TitleTags = memo(() => {
+ return (
+ <Flexbox align={'center'} gap={12} horizontal>
+ <MemberCountTag />
+ </Flexbox>
+ );
+});
+
+export default TitleTags;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/Header/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/Header/index.tsx
new file mode 100644
index 00000000000..b47278bf613
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/Header/index.tsx
@@ -0,0 +1,26 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import NavHeader from '@/features/NavHeader';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+
+import ShareButton from './ShareButton';
+
+const Header = memo(() => {
+ const theme = useTheme();
+ return (
+ <NavHeader
+ right={
+ <Flexbox horizontal style={{ backgroundColor: theme.colorBgContainer }}>
+ <WideScreenButton />
+ <ShareButton />
+ </Flexbox>
+ }
+ />
+ );
+});
+
+export default Header;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/GroupChat.tsx b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
similarity index 79%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/GroupChat.tsx
rename to src/app/[variants]/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
index b86aec0139e..f7a5410ab03 100644
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/GroupChat.tsx
+++ b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
@@ -2,20 +2,20 @@
import { SlashOptions } from '@lobehub/editor';
import { Alert, Avatar, GroupAvatar } from '@lobehub/ui';
-import { isEqual } from 'lodash';
+import { isEqual } from 'es-toolkit/compat';
import { Suspense, memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { DEFAULT_AVATAR } from '@/const/meta';
import { type ActionKeys, ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';
-import WideScreenContainer from '@/features/ChatList/components/WideScreenContainer';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { useChatStore } from '@/store/chat';
import { aiChatSelectors } from '@/store/chat/selectors';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-import { useSendGroupMessage } from '../useSend';
+// import { useSendGroupMessage } from '../ChatInput/useSend';
import MessageFromUrl from './MessageFromUrl';
import { useSendMenuItems } from './useSendMenuItems';
@@ -30,17 +30,17 @@ const leftActions: ActionKeys[] = [
const dmLeftActions: ActionKeys[] = ['typo', 'fileUpload', 'knowledgeBase', '---', ['stt']];
-const rightActions: ActionKeys[] = ['saveTopic'];
+const rightActions: ActionKeys[] = [];
/**
* Message Editor for Group Chat along with DM Portal
*/
const Desktop = memo((props: { targetMemberId?: string }) => {
const { t } = useTranslation('chat');
- const { send, generating, disabled, stop } = useSendGroupMessage();
+ // const { send, generating, disabled, stop } = useSendGroupMessage();
const isDMPortal = !!props.targetMemberId;
- const currentGroupMemebers = useSessionStore(sessionSelectors.currentGroupAgents, isEqual);
+ const currentGroupMembers = useAgentGroupStore(agentGroupSelectors.currentGroupAgents, isEqual);
const [mainInputSendErrorMsg, clearSendMessageError] = useChatStore((s) => [
aiChatSelectors.isCurrentSendMessageError(s),
@@ -48,13 +48,13 @@ const Desktop = memo((props: { targetMemberId?: string }) => {
]);
const mentionItems: SlashOptions['items'] = useMemo(() => {
- if (!currentGroupMemebers) return [];
+ if (!currentGroupMembers) return [];
return [
{
icon: (
<GroupAvatar
avatars={
- currentGroupMemebers?.map((member) => ({
+ currentGroupMembers?.map((member) => ({
avatar: member.avatar || DEFAULT_AVATAR,
background: member.backgroundColor || undefined,
})) || []
@@ -66,7 +66,7 @@ const Desktop = memo((props: { targetMemberId?: string }) => {
label: t('memberSelection.allMembers'),
metadata: { id: 'ALL_MEMBERS' },
},
- ...currentGroupMemebers.map((member) => ({
+ ...currentGroupMembers.map((member) => ({
icon: (
<Avatar
avatar={member.avatar}
@@ -79,7 +79,7 @@ const Desktop = memo((props: { targetMemberId?: string }) => {
metadata: { id: member.id },
})),
];
- }, [currentGroupMemebers]);
+ }, [currentGroupMembers]);
const sendMenuItems = useSendMenuItems();
@@ -95,10 +95,10 @@ const Desktop = memo((props: { targetMemberId?: string }) => {
useChatStore.setState({ inputMessage: content });
}}
onSend={() => {
- send({ targetMemberId: props.targetMemberId });
+ // send({ targetMemberId: props.targetMemberId });
}}
rightActions={isDMPortal ? [] : rightActions}
- sendButtonProps={{ disabled, generating, onStop: stop }}
+ // sendButtonProps={{ disabled, generating, onStop: stop }}
sendMenu={{
items: sendMenuItems,
}}
diff --git a/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
new file mode 100644
index 00000000000..27ae1dacc49
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { useEffect } from 'react';
+import { useSearchParams } from 'react-router-dom';
+
+import { useConversationStore } from '@/features/Conversation';
+
+/**
+ * MessageFromUrl
+ *
+ * Handles sending messages from URL query parameters.
+ * Uses ConversationStore for input and send operations.
+ */
+const MessageFromUrl = () => {
+ const [updateInputMessage, sendMessage] = useConversationStore((s) => [
+ s.updateInputMessage,
+ s.sendMessage,
+ ]);
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ useEffect(() => {
+ const message = searchParams.get('message');
+ if (!message) return;
+
+ const params = new URLSearchParams(searchParams.toString());
+ params.delete('message');
+ setSearchParams(params, { replace: true });
+
+ updateInputMessage(message);
+ sendMessage({ message });
+ }, [searchParams, setSearchParams, updateInputMessage, sendMessage]);
+
+ return null;
+};
+
+export default MessageFromUrl;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/index.tsx
new file mode 100644
index 00000000000..38970539aa1
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/index.tsx
@@ -0,0 +1,51 @@
+'use client';
+
+import { memo } from 'react';
+
+import { type ActionKeys } from '@/features/ChatInput';
+import { ChatInput } from '@/features/Conversation';
+import { useChatStore } from '@/store/chat';
+
+import { useSendMenuItems } from './useSendMenuItems';
+
+const leftActions: ActionKeys[] = [
+ 'model',
+ 'search',
+ 'typo',
+ 'fileUpload',
+ 'knowledgeBase',
+ 'tools',
+ '---',
+ 'clear',
+ 'mainToken',
+];
+
+const rightActions: ActionKeys[] = [];
+
+/**
+ * MainChatInput
+ *
+ * Custom ChatInput implementation for main chat page.
+ * Uses ChatInput from @/features/Conversation which handles all send logic
+ * including error alerts display.
+ * Only adds MessageFromUrl for desktop mode.
+ */
+const MainChatInput = memo(() => {
+ const sendMenuItems = useSendMenuItems();
+
+ return (
+ <ChatInput
+ leftActions={leftActions}
+ onEditorReady={(instance) => {
+ // Sync to global ChatStore for compatibility with other features
+ useChatStore.setState({ mainInputEditor: instance });
+ }}
+ rightActions={rightActions}
+ sendMenu={{ items: sendMenuItems }}
+ />
+ );
+});
+
+MainChatInput.displayName = 'MainChatInput';
+
+export default MainChatInput;
diff --git a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/useSendMenuItems.tsx b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
similarity index 67%
rename from src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/useSendMenuItems.tsx
rename to src/app/[variants]/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
index 76181126c73..d4f517a90f1 100644
--- a/src/app/[variants]/(main)/chat/components/conversation/features/ChatInput/Desktop/useSendMenuItems.tsx
+++ b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
@@ -2,19 +2,29 @@
import { Hotkey, Icon, type MenuProps } from '@lobehub/ui';
import { BotMessageSquare, LucideCheck, MessageSquarePlus } from 'lucide-react';
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
+import { useConversationStore, useConversationStoreApi } from '@/features/Conversation';
import { useUserStore } from '@/store/user';
import { preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
import { HotkeyEnum, KeyEnum } from '@/types/hotkey';
-import { useSend } from '../useSend';
-
+/**
+ * useSendMenuItems hook for ConversationStore
+ *
+ * Provides send menu items for:
+ * - Send with Enter / Cmd+Enter toggle
+ * - Add AI Message
+ * - Add User Message
+ */
export const useSendMenuItems = (): MenuProps['items'] => {
const { t } = useTranslation('chat');
- const { send } = useSend();
+
+ const storeApi = useConversationStoreApi();
+ const editor = useConversationStore((s) => s.editor);
+
const [useCmdEnterToSend, updatePreference] = useUserStore((s) => [
preferenceSelectors.useCmdEnterToSend(s),
s.updatePreference,
@@ -22,6 +32,26 @@ export const useSendMenuItems = (): MenuProps['items'] => {
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
+ const handleAddAIMessage = useCallback(() => {
+ const store = storeApi.getState();
+ // Add empty AI message placeholder
+ store.addAIMessage('');
+ // Clear and focus editor
+ editor?.clearContent();
+ editor?.focus();
+ }, [storeApi, editor]);
+
+ const handleAddUserMessage = useCallback(() => {
+ const store = storeApi.getState();
+ const message = store.inputMessage;
+ if (!message.trim()) return;
+
+ store.addUserMessage({ message });
+ // Clear and focus editor
+ editor?.clearContent();
+ editor?.focus();
+ }, [storeApi, editor]);
+
return useMemo(
() => [
{
@@ -64,16 +94,12 @@ export const useSendMenuItems = (): MenuProps['items'] => {
},
{ type: 'divider' },
{
- // disabled,
icon: <Icon icon={BotMessageSquare} />,
key: 'addAi',
label: t('input.addAi'),
- onClick: () => {
- send({ onlyAddAIMessage: true });
- },
+ onClick: handleAddAIMessage,
},
{
- // disabled,
icon: <Icon icon={MessageSquarePlus} />,
key: 'addUser',
label: (
@@ -82,11 +108,9 @@ export const useSendMenuItems = (): MenuProps['items'] => {
<Hotkey keys={hotkey} />
</Flexbox>
),
- onClick: () => {
- send({ onlyAddUserMessage: true });
- },
+ onClick: handleAddUserMessage,
},
],
- [useCmdEnterToSend, send, updatePreference, hotkey],
+ [useCmdEnterToSend, updatePreference, hotkey, handleAddAIMessage, handleAddUserMessage],
);
};
diff --git a/src/app/[variants]/(main)/group/features/Conversation/ThreadHydration.tsx b/src/app/[variants]/(main)/group/features/Conversation/ThreadHydration.tsx
new file mode 100644
index 00000000000..6c1ed91e7e2
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/ThreadHydration.tsx
@@ -0,0 +1,45 @@
+'use client';
+
+import { memo, useEffect, useLayoutEffect } from 'react';
+import { createStoreUpdater } from 'zustand-utils';
+
+import { useFetchThreads } from '@/hooks/useFetchThreads';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useChatStore } from '@/store/chat';
+
+// sync outside state to useChatStore
+const ThreadHydration = memo(() => {
+ const useStoreUpdater = createStoreUpdater(useChatStore);
+
+ // two-way bindings the topic params to chat store
+ const [portalThread, setThread] = useQueryState('portalThread');
+ useStoreUpdater('portalThreadId', portalThread!);
+
+ useLayoutEffect(() => {
+ const unsubscribe = useChatStore.subscribe(
+ (s) => s.portalThreadId,
+ (state) => {
+ setThread(!state ? null : state);
+ },
+ );
+
+ return () => {
+ unsubscribe();
+ };
+ }, [setThread]); // ✅ 现在 setValue 是稳定的,可以安全地添加到依赖数组
+
+ // should open portal automatically when portalThread is set
+ useEffect(() => {
+ if (!!portalThread && !useChatStore.getState().showPortal) {
+ useChatStore.getState().togglePortal(true);
+ }
+ }, [portalThread]);
+
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+
+ useFetchThreads(activeTopicId);
+
+ return null;
+});
+
+export default ThreadHydration;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/ZenModeToast/Toast.tsx b/src/app/[variants]/(main)/group/features/Conversation/ZenModeToast/Toast.tsx
new file mode 100644
index 00000000000..5bdac1762ab
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/ZenModeToast/Toast.tsx
@@ -0,0 +1,91 @@
+'use client';
+
+import { Hotkey } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useUserStore } from '@/store/user';
+import { settingsSelectors } from '@/store/user/selectors';
+import { HotkeyEnum } from '@/types/hotkey';
+
+const useStyles = createStyles(({ css, token }) => ({
+ closeButton: css`
+ color: ${token.colorTextSecondary};
+ transition: color 0.2s;
+
+ &:hover {
+ color: ${token.colorTextQuaternary};
+ }
+ `,
+
+ container: css`
+ position: fixed;
+ z-index: 50;
+ inset-block-start: 16px;
+ inset-inline-start: 50%;
+ transform: translateX(-50%);
+
+ animation: fade-in-slide-down 300ms ease;
+
+ @keyframes fade-in-slide-down {
+ from {
+ transform: translate(-50%, -16px);
+ opacity: 0;
+ }
+
+ to {
+ transform: translate(-50%, 0);
+ opacity: 1;
+ }
+ }
+ `,
+
+ text: css`
+ font-size: 16px;
+ font-weight: 500;
+ color: ${token.colorBgBase};
+ `,
+
+ toast: css`
+ display: flex;
+ align-items: center;
+
+ padding-block: 8px;
+ padding-inline: 24px;
+ border-radius: 9999px;
+
+ background: ${token.colorText};
+ box-shadow: ${token.boxShadowSecondary};
+ `,
+}));
+
+const Toast = () => {
+ const { t } = useTranslation('chat');
+ const { styles } = useStyles();
+ const [isVisible, setIsVisible] = useState(true);
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.ToggleZenMode));
+
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ setIsVisible(false);
+ }, 2000);
+
+ return () => clearTimeout(timer);
+ }, []);
+
+ if (!isVisible) return null;
+
+ return (
+ <div className={styles.container}>
+ <div className={styles.toast}>
+ <Flexbox align={'center'} className={styles.text} gap={8} horizontal>
+ {t('zenMode')} <Hotkey inverseTheme keys={hotkey} />
+ </Flexbox>
+ </div>
+ </div>
+ );
+};
+
+export default Toast;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/ZenModeToast/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/ZenModeToast/index.tsx
new file mode 100644
index 00000000000..28558c64573
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/ZenModeToast/index.tsx
@@ -0,0 +1,16 @@
+'use client';
+
+import { memo } from 'react';
+
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import Toast from './Toast';
+
+const ZenModeToast = memo(() => {
+ const inZenMode = useGlobalStore(systemStatusSelectors.inZenMode);
+
+ return inZenMode && <Toast />;
+});
+
+export default ZenModeToast;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/index.tsx b/src/app/[variants]/(main)/group/features/Conversation/index.tsx
new file mode 100644
index 00000000000..e0994f01f95
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/index.tsx
@@ -0,0 +1,22 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import ConversationArea from './ConversationArea';
+import ChatHeader from './Header';
+
+const ChatConversation = memo(() => {
+ const showHeader = useGlobalStore(systemStatusSelectors.showChatHeader);
+ return (
+ <Flexbox height={'100%'} style={{ overflow: 'hidden', position: 'relative' }} width={'100%'}>
+ {showHeader && <ChatHeader />}
+ <ConversationArea />
+ </Flexbox>
+ );
+});
+
+ChatConversation.displayName = 'ChatConversation';
+
+export default ChatConversation;
diff --git a/src/app/[variants]/(main)/group/features/Conversation/useActionsBarConfig.ts b/src/app/[variants]/(main)/group/features/Conversation/useActionsBarConfig.ts
new file mode 100644
index 00000000000..5ba2b21de03
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/useActionsBarConfig.ts
@@ -0,0 +1,63 @@
+'use client';
+
+import { App } from 'antd';
+import { Split } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type {
+ ActionsBarConfig,
+ MessageActionFactory,
+ MessageActionItem,
+} from '@/features/Conversation/types';
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Hook to create a branching action factory function.
+ * The factory function takes a message id and returns the branching action
+ * with proper ChatStore integration.
+ */
+export const useBranchingActionFactory = (): MessageActionFactory => {
+ const { t } = useTranslation('common');
+ const { message } = App.useApp();
+
+ const [topic, openThreadCreator] = useChatStore((s) => [s.activeTopicId, s.openThreadCreator]);
+
+ return useCallback(
+ (id: string): MessageActionItem | null => {
+ return {
+ handleClick: () => {
+ if (!topic) {
+ message.warning(t('branchingRequiresSavedTopic'));
+ return;
+ }
+ openThreadCreator(id);
+ },
+ icon: Split,
+ key: 'branching',
+ label: t('branching'),
+ };
+ },
+ [topic, openThreadCreator],
+ );
+};
+
+/**
+ * Hook to generate actionsBar configuration with branching support.
+ * This creates the complete actionsBar config to be passed to ChatList.
+ */
+export const useActionsBarConfig = (): ActionsBarConfig => {
+ const branchingFactory = useBranchingActionFactory();
+
+ return useMemo(
+ () => ({
+ assistant: {
+ // extraBarActions: [branchingFactory],
+ },
+ user: {
+ // extraBarActions: [branchingFactory],
+ },
+ }),
+ [branchingFactory],
+ );
+};
diff --git a/src/app/[variants]/(main)/group/features/Conversation/useGroupContext.ts b/src/app/[variants]/(main)/group/features/Conversation/useGroupContext.ts
new file mode 100644
index 00000000000..d5aa030e403
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/useGroupContext.ts
@@ -0,0 +1,33 @@
+'use client';
+
+import { ConversationContext } from '@lobechat/types';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Hook to get group conversation context
+ *
+ * Returns context with scope='group' or 'group_agent' and supervisorAgentId as agentId.
+ * Used for group chat pages where multiple agents participate.
+ */
+export function useGroupContext(): ConversationContext {
+ const [topicId, threadId, groupId] = useChatStore((s) => [
+ s.activeTopicId ?? null,
+ s.activeThreadId ?? null,
+ s.activeGroupId ?? null,
+ ]);
+
+ const currentGroup = useAgentGroupStore(agentGroupSelectors.currentGroup);
+ const supervisorAgentId = currentGroup?.supervisorAgentId;
+
+ // Group context uses supervisorAgentId as agentId for message storage
+ return {
+ agentId: supervisorAgentId || '',
+ groupId: groupId ?? undefined,
+ scope: threadId ? 'group_agent' : 'group',
+ threadId,
+ topicId,
+ };
+}
diff --git a/src/app/[variants]/(main)/group/features/Conversation/useGroupHooks.ts b/src/app/[variants]/(main)/group/features/Conversation/useGroupHooks.ts
new file mode 100644
index 00000000000..f0ef27f6c12
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Conversation/useGroupHooks.ts
@@ -0,0 +1,51 @@
+'use client';
+
+import { ConversationContext, SendMessageParams } from '@lobechat/types';
+import { useMemo } from 'react';
+
+import { ConversationHooks } from '@/features/Conversation';
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Hook to create ConversationHooks for Group chat
+ *
+ * Intercepts the default send flow and routes to Group-specific logic:
+ * - Uses sendGroupMessage from ChatStore (aiAgent/agentGroup slice)
+ * - Supports supervisor decision mode or direct @mentions
+ * - Future: will integrate with backend Agent mode (aiAgent.execAgent)
+ *
+ * @param context - The group conversation context
+ * @returns ConversationHooks for use with ConversationProvider
+ */
+export function useGroupHooks(context: ConversationContext): ConversationHooks {
+ const sendGroupMessage = useChatStore((s) => s.sendGroupMessage);
+
+ return useMemo(
+ (): ConversationHooks => ({
+ /**
+ * Intercept send and route to Group-specific logic
+ *
+ * Returns false to prevent the default ChatStore.sendMessage flow.
+ * Instead, we use sendGroupMessage which handles:
+ * - Supervisor decision (if enabled)
+ * - Direct @mentions (if supervisor disabled)
+ * - Future: backend Agent execution
+ */
+ onBeforeSendMessage: async (params: SendMessageParams) => {
+ const { groupId } = context;
+
+ if (!groupId) {
+ console.warn('[useGroupHooks] No groupId in context, falling back to default send');
+ return true; // Allow default flow
+ }
+
+ // Route to Group-specific send logic
+ await sendGroupMessage({ context, files: params.files, message: params.message });
+
+ // Return false to prevent default ChatStore.sendMessage
+ return false;
+ },
+ }),
+ [context],
+ );
+}
diff --git a/src/app/[variants]/(main)/group/features/GroupAvatar.tsx b/src/app/[variants]/(main)/group/features/GroupAvatar.tsx
new file mode 100644
index 00000000000..fd5892b3439
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/GroupAvatar.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { Avatar, GroupAvatar, Skeleton } from '@lobehub/ui';
+import React, { memo } from 'react';
+
+import { DEFAULT_AVATAR } from '@/const/meta';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+const SupervisorAvatar = memo<{ size?: number }>(({ size = 28 }) => {
+ const meta = useAgentStore(agentSelectors.currentAgentMeta);
+ const [isGroupsInit, groupMeta, agents] = useAgentGroupStore((s) => [
+ agentGroupSelectors.isGroupsInit(s),
+ agentGroupSelectors.currentGroupMeta(s),
+ agentGroupSelectors.currentGroupAgents(s),
+ ]);
+
+ if (isGroupsInit) return <Skeleton.Avatar shape={'square'} size={size} />;
+
+ if (meta?.avatar && meta?.avatar !== DEFAULT_AVATAR)
+ return <Avatar avatar={meta.avatar} background={meta?.backgroundColor} size={size} />;
+
+ return (
+ <GroupAvatar
+ avatarShape={'square'}
+ avatars={agents.map((agent) => ({
+ avatar: agent.avatar || DEFAULT_AVATAR,
+ background: agent.backgroundColor || undefined,
+ style: { borderRadius: 3 },
+ }))}
+ cornerShape={'square'}
+ size={size}
+ title={groupMeta?.title || undefined}
+ />
+ );
+});
+
+export default SupervisorAvatar;
diff --git a/src/app/[variants]/(main)/group/features/PageTitle/index.tsx b/src/app/[variants]/(main)/group/features/PageTitle/index.tsx
new file mode 100644
index 00000000000..60e97a1d175
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/PageTitle/index.tsx
@@ -0,0 +1,18 @@
+'use client';
+
+import { memo } from 'react';
+
+import PageTitle from '@/components/PageTitle';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+const Title = memo(() => {
+ const agentTitle = useAgentStore(agentSelectors.currentAgentTitle);
+
+ const topicTitle = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.title);
+ return <PageTitle title={[topicTitle, agentTitle].filter(Boolean).join(' · ')} />;
+});
+
+export default Title;
diff --git a/src/app/[variants]/(main)/group/features/Portal/_layout/Desktop.tsx b/src/app/[variants]/(main)/group/features/Portal/_layout/Desktop.tsx
new file mode 100644
index 00000000000..0ed3cd25979
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Portal/_layout/Desktop.tsx
@@ -0,0 +1,16 @@
+import { PropsWithChildren } from 'react';
+
+import { PortalHeader } from '@/features/Portal/router';
+
+import Body from '../features/Body';
+
+const Layout = ({ children }: PropsWithChildren) => {
+ return (
+ <>
+ <PortalHeader />
+ <Body>{children}</Body>
+ </>
+ );
+};
+
+export default Layout;
diff --git a/src/app/[variants]/(main)/group/features/Portal/_layout/Mobile.tsx b/src/app/[variants]/(main)/group/features/Portal/_layout/Mobile.tsx
new file mode 100644
index 00000000000..a52be46eefb
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Portal/_layout/Mobile.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { Modal } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { PropsWithChildren } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { PortalHeader } from '@/features/Portal/router';
+import { useChatStore } from '@/store/chat';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ background: linear-gradient(${token.colorBgElevated}, ${token.colorBgContainer}) !important;
+ `,
+}));
+
+const Layout = ({ children }: PropsWithChildren) => {
+ const { styles, cx } = useStyles();
+ const [showMobilePortal, isPortalThread, togglePortal] = useChatStore((s) => [
+ s.showPortal,
+ !!s.portalThreadId,
+ s.togglePortal,
+ ]);
+ const { t } = useTranslation('portal');
+
+ return (
+ <Modal
+ allowFullscreen
+ className={cx(isPortalThread && styles.container)}
+ footer={null}
+ height={'95%'}
+ onCancel={() => togglePortal(false)}
+ open={showMobilePortal}
+ styles={{
+ body: { padding: 0 },
+ header: { display: 'none' },
+ }}
+ title={t('title')}
+ >
+ <PortalHeader />
+ <Flexbox
+ gap={8}
+ height={'calc(100% - 52px)'}
+ padding={'0 8px'}
+ style={{ overflow: 'hidden' }}
+ >
+ <Flexbox
+ height={'100%'}
+ style={{ marginInline: -8, overflow: 'hidden', position: 'relative' }}
+ width={'calc(100% + 16px)'}
+ >
+ {children}
+ </Flexbox>
+ </Flexbox>
+ </Modal>
+ );
+};
+
+export default Layout;
diff --git a/src/app/[variants]/(main)/group/features/Portal/features/Body.tsx b/src/app/[variants]/(main)/group/features/Portal/features/Body.tsx
new file mode 100644
index 00000000000..8c60f7bd7fb
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Portal/features/Body.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { css, cx } from 'antd-style';
+import { PropsWithChildren } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+const body = css`
+ :has(.portal-artifact) {
+ overflow: hidden;
+ padding-block-end: 12px;
+ }
+`;
+
+const Body = ({ children }: PropsWithChildren) => {
+ return (
+ <Flexbox
+ className={cx(body, 'portal-body')}
+ height={'100%'}
+ style={{ flex: 1, height: 0, position: 'relative' }}
+ width={'100%'}
+ >
+ {children}
+ </Flexbox>
+ );
+};
+
+export default Body;
diff --git a/src/app/[variants]/(main)/group/features/Portal/features/Portal.tsx b/src/app/[variants]/(main)/group/features/Portal/features/Portal.tsx
new file mode 100644
index 00000000000..79f6fd9b180
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Portal/features/Portal.tsx
@@ -0,0 +1,104 @@
+'use client';
+
+import { DraggablePanel, DraggablePanelContainer, type DraggablePanelProps } from '@lobehub/ui';
+import { createStyles, useResponsive } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { PropsWithChildren, memo, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import {
+ CHAT_PORTAL_MAX_WIDTH,
+ CHAT_PORTAL_TOOL_UI_WIDTH,
+ CHAT_PORTAL_WIDTH,
+} from '@/const/layoutTokens';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors, portalThreadSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+const useStyles = createStyles(({ css, token }) => ({
+ content: css`
+ display: flex;
+ flex-direction: column;
+ height: 100% !important;
+ `,
+ drawer: css`
+ z-index: 10;
+ height: 100%;
+ background: ${token.colorBgContainer};
+ `,
+ panel: css`
+ overflow: hidden;
+ height: 100%;
+ background: ${token.colorBgContainer};
+ `,
+}));
+
+const PortalPanel = memo(({ children }: PropsWithChildren) => {
+ const { styles } = useStyles();
+ const { md = true } = useResponsive();
+
+ const [showPortal, showToolUI, showArtifactUI, showThread] = useChatStore((s) => [
+ chatPortalSelectors.showPortal(s),
+ chatPortalSelectors.showPluginUI(s),
+ chatPortalSelectors.showArtifactUI(s),
+ portalThreadSelectors.showThread(s),
+ ]);
+
+ const [portalWidth, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.portalWidth(s),
+ s.updateSystemStatus,
+ ]);
+
+ const [tmpWidth, setWidth] = useState(portalWidth);
+ if (tmpWidth !== portalWidth) setWidth(portalWidth);
+
+ const handleSizeChange: DraggablePanelProps['onSizeChange'] = (_, size) => {
+ if (!size) return;
+ const nextWidth = typeof size.width === 'string' ? Number.parseInt(size.width) : size.width;
+ if (!nextWidth) return;
+
+ if (isEqual(nextWidth, portalWidth)) return;
+ setWidth(nextWidth);
+ updateSystemStatus({ portalWidth: nextWidth });
+ };
+
+ return (
+ <DraggablePanel
+ className={styles.drawer}
+ classNames={{
+ content: styles.content,
+ }}
+ defaultSize={{ width: tmpWidth }}
+ expand={showPortal}
+ maxWidth={CHAT_PORTAL_MAX_WIDTH}
+ minWidth={
+ (showArtifactUI || showToolUI || showThread) && md
+ ? CHAT_PORTAL_TOOL_UI_WIDTH
+ : CHAT_PORTAL_WIDTH
+ }
+ mode={md ? 'fixed' : 'float'}
+ onSizeChange={handleSizeChange}
+ placement={'right'}
+ showHandleWhenCollapsed={false}
+ showHandleWideArea={false}
+ size={{ height: '100%', width: portalWidth }}
+ styles={{
+ handle: { display: 'none' },
+ }}
+ >
+ <DraggablePanelContainer
+ style={{
+ flex: 'none',
+ height: '100%',
+ maxHeight: '100vh',
+ minWidth: CHAT_PORTAL_WIDTH,
+ }}
+ >
+ <Flexbox className={styles.panel}>{children}</Flexbox>
+ </DraggablePanelContainer>
+ </DraggablePanel>
+ );
+});
+
+export default PortalPanel;
diff --git a/src/app/[variants]/(main)/group/features/Portal/features/PortalPanel.tsx b/src/app/[variants]/(main)/group/features/Portal/features/PortalPanel.tsx
new file mode 100644
index 00000000000..9080a2ef4e2
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Portal/features/PortalPanel.tsx
@@ -0,0 +1,27 @@
+import { Suspense, lazy, memo } from 'react';
+
+import DesktopLayout from '@/app/[variants]/(main)/chat/features/Portal/_layout/Desktop';
+import MobileLayout from '@/app/[variants]/(main)/chat/features/Portal/_layout/Mobile';
+import Loading from '@/components/Loading/BrandTextLoading';
+
+const PortalBody = lazy(() => import('@/features/Portal/router'));
+
+interface PortalPanelProps {
+ mobile?: boolean;
+}
+
+const PortalPanel = memo<PortalPanelProps>(({ mobile }) => {
+ const Layout = mobile ? MobileLayout : DesktopLayout;
+
+ return (
+ <Suspense fallback={<Loading debugId="PortalPanel" />}>
+ <Layout>
+ <PortalBody />
+ </Layout>
+ </Suspense>
+ );
+});
+
+PortalPanel.displayName = 'PortalPanel';
+
+export default PortalPanel;
diff --git a/src/app/[variants]/(main)/group/features/Portal/index.tsx b/src/app/[variants]/(main)/group/features/Portal/index.tsx
new file mode 100644
index 00000000000..6ce8b46db93
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/Portal/index.tsx
@@ -0,0 +1,19 @@
+import { Suspense } from 'react';
+
+import Portal from '@/app/[variants]/(main)/chat/features/Portal/features/Portal';
+import PortalPanel from '@/app/[variants]/(main)/chat/features/Portal/features/PortalPanel';
+import Loading from '@/components/Loading/BrandTextLoading';
+
+const ChatPortal = () => {
+ return (
+ <Portal>
+ <Suspense fallback={<Loading debugId={'ChatPortal'} />}>
+ <PortalPanel mobile={false} />
+ </Suspense>
+ </Portal>
+ );
+};
+
+ChatPortal.displayName = 'ChatPortal';
+
+export default ChatPortal;
diff --git a/src/app/[variants]/(main)/group/features/TelemetryNotification.tsx b/src/app/[variants]/(main)/group/features/TelemetryNotification.tsx
new file mode 100644
index 00000000000..8242530f1c0
--- /dev/null
+++ b/src/app/[variants]/(main)/group/features/TelemetryNotification.tsx
@@ -0,0 +1,92 @@
+'use client';
+
+import { Avatar, Button, Icon } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { LucideArrowUpRightFromSquare, TelescopeIcon } from 'lucide-react';
+import Link from 'next/link';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import Notification from '@/components/Notification';
+import { BRANDING_NAME } from '@/const/branding';
+import { PRIVACY_URL } from '@/const/url';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+
+const useStyles = createStyles(({ css, token }) => ({
+ desc: css`
+ color: ${token.colorTextSecondary};
+ `,
+ title: css`
+ font-size: 18px;
+ font-weight: bold;
+ `,
+}));
+
+const TelemetryNotification = memo<{ mobile?: boolean }>(({ mobile }) => {
+ const { styles, theme } = useStyles();
+
+ const { t } = useTranslation('common');
+ const isPreferenceInit = useUserStore(preferenceSelectors.isPreferenceInit);
+
+ const [useCheckTrace, updatePreference] = useUserStore((s) => [
+ s.useCheckTrace,
+ s.updatePreference,
+ ]);
+
+ const { data: showModal, mutate } = useCheckTrace(isPreferenceInit);
+
+ const updateTelemetry = (telemetry: boolean) => {
+ updatePreference({ telemetry });
+ mutate();
+ };
+
+ return (
+ <Notification mobile={mobile} show={showModal} showCloseIcon={false}>
+ <Flexbox>
+ <Avatar
+ avatar={<TelescopeIcon />}
+ background={theme.geekblue1}
+ style={{ color: theme.geekblue7 }}
+ />
+ </Flexbox>
+ <Flexbox gap={16}>
+ <Flexbox gap={12}>
+ <Flexbox className={styles.title}>
+ {t('telemetry.title', { appName: BRANDING_NAME })}
+ </Flexbox>
+ <div className={styles.desc}>
+ {t('telemetry.desc', { appName: BRANDING_NAME })}
+ <span>
+ <Link href={PRIVACY_URL} target={'_blank'}>
+ {t('telemetry.learnMore')}
+ <Icon icon={LucideArrowUpRightFromSquare} style={{ marginInlineStart: 4 }} />
+ </Link>
+ </span>
+ </div>
+ </Flexbox>
+ <Flexbox gap={8} horizontal>
+ <Button
+ onClick={() => {
+ updateTelemetry(true);
+ }}
+ type={'primary'}
+ >
+ {t('telemetry.allow')}
+ </Button>
+ <Button
+ onClick={() => {
+ updateTelemetry(false);
+ }}
+ type={'text'}
+ >
+ {t('telemetry.deny')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Notification>
+ );
+});
+
+export default TelemetryNotification;
diff --git a/src/app/[variants]/(main)/group/index.tsx b/src/app/[variants]/(main)/group/index.tsx
new file mode 100644
index 00000000000..9bd3eb7a6ae
--- /dev/null
+++ b/src/app/[variants]/(main)/group/index.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import MainInterfaceTracker from '@/components/Analytics/MainInterfaceTracker';
+
+import Conversation from './features/Conversation';
+import PageTitle from './features/PageTitle';
+import Portal from './features/Portal';
+import TelemetryNotification from './features/TelemetryNotification';
+
+const ChatPage = memo(() => {
+ return (
+ <>
+ <PageTitle />
+ <Flexbox
+ height={'100%'}
+ horizontal
+ style={{ overflow: 'hidden', position: 'relative' }}
+ width={'100%'}
+ >
+ <Conversation />
+ <Portal />
+ </Flexbox>
+ <MainInterfaceTracker />
+ <TelemetryNotification mobile={false} />
+ </>
+ );
+});
+
+export default ChatPage;