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.

✨ feat: layout sidebar impl (#13719)

Rdmclin22c397390b4c9
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 79a51015dcc..f5b18d5bd82 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -42,6 +42,11 @@
"confirmRemoveGroupSuccess": "Group deleted successfully",
"confirmRemoveSessionItemAlert": "You are about to delete this agent. Once deleted, it cannot be retrieved. Please confirm your action.",
"confirmRemoveSessionSuccess": "Agent removed successfully",
+ "createModal.createBlank": "Create Blank",
+ "createModal.groupPlaceholder": "Describe what this group should do...",
+ "createModal.groupTitle": "What should your group do?",
+ "createModal.placeholder": "Describe what your agent should do...",
+ "createModal.title": "What should your agent do?",
"defaultAgent": "Default Agent",
"defaultGroupChat": "Group",
"defaultList": "Default List",
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 4c8c8a487e5..204c26c9fa9 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -342,11 +342,20 @@
"mail.business": "Business Cooperation",
"mail.support": "Email Support",
"more": "More",
- "navPanel.agent": "Agent",
+ "navPanel.agent": "Agents",
+ "navPanel.customizeSidebar": "Customize sidebar",
"navPanel.displayItems": "Display Items",
+ "navPanel.hidden": "Hidden",
+ "navPanel.hideSection": "Hide section",
"navPanel.library": "Library",
+ "navPanel.moveDown": "Move down",
+ "navPanel.moveUp": "Move up",
+ "navPanel.pinned": "Pinned",
"navPanel.searchAgent": "Search Agent...",
+ "navPanel.searchRecent": "Search Recent...",
"navPanel.searchResultEmpty": "No search results found",
+ "navPanel.show": "Show",
+ "navPanel.visible": "Visible",
"new": "New",
"noContent": "No content",
"oauth": "SSO Login",
@@ -367,6 +376,7 @@
"promptTransform.actions.translate": "Translate",
"promptTransform.status.rewrite": "Expanding details...",
"promptTransform.status.translate": "Translating...",
+ "recents": "Recents",
"regenerate": "Regenerate",
"releaseNotes": "Version Details",
"rename": "Rename",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 629080155e3..0d1f3125dbe 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -42,6 +42,11 @@
"confirmRemoveGroupSuccess": "群组已删除",
"confirmRemoveSessionItemAlert": "确认删除该助理吗?删除后无法恢复",
"confirmRemoveSessionSuccess": "助理已删除",
+ "createModal.createBlank": "创建空白",
+ "createModal.groupPlaceholder": "描述这个群组应该做什么...",
+ "createModal.groupTitle": "你的群组应该做什么?",
+ "createModal.placeholder": "描述你的助理应该做什么...",
+ "createModal.title": "你的助理应该做什么?",
"defaultAgent": "自定义助理",
"defaultGroupChat": "群组",
"defaultList": "默认列表",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index f81db9d5315..b9ff24f84e6 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -343,10 +343,19 @@
"mail.support": "邮件支持",
"more": "更多",
"navPanel.agent": "助理",
+ "navPanel.customizeSidebar": "自定义侧边栏",
"navPanel.displayItems": "显示条目",
+ "navPanel.hidden": "已隐藏",
+ "navPanel.hideSection": "隐藏分组",
"navPanel.library": "资源库",
+ "navPanel.moveDown": "下移",
+ "navPanel.moveUp": "上移",
+ "navPanel.pinned": "已固定",
"navPanel.searchAgent": "搜索助理…",
+ "navPanel.searchRecent": "搜索最近…",
"navPanel.searchResultEmpty": "暂无搜索结果",
+ "navPanel.show": "显示",
+ "navPanel.visible": "显示中",
"new": "新",
"noContent": "暂无内容",
"oauth": "SSO 登录",
@@ -367,6 +376,7 @@
"promptTransform.actions.translate": "翻译",
"promptTransform.status.rewrite": "正在丰富细节...",
"promptTransform.status.translate": "正在翻译...",
+ "recents": "Recents",
"regenerate": "重新生成",
"releaseNotes": "版本详情",
"rename": "重命名",
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
new file mode 100644
index 00000000000..05c4b64c32a
--- /dev/null
+++ b/packages/database/src/models/recent.ts
@@ -0,0 +1,90 @@
+import { sql } from 'drizzle-orm';
+
+import { agents, documents, tasks, topics } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+
+export interface RecentDbItem {
+ id: string;
+ metadata?: any;
+ routeGroupId: string | null;
+ routeId: string | null;
+ title: string;
+ type: 'topic' | 'document' | 'task';
+ updatedAt: Date;
+}
+
+export class RecentModel {
+ private userId: string;
+ private db: LobeChatDatabase;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+
+ queryRecent = async (limit: number = 10): Promise<RecentDbItem[]> => {
+ const query = sql`
+ SELECT * FROM (
+ SELECT
+ ${topics.id} as id,
+ COALESCE(${topics.title}, 'Untitled Topic') as title,
+ 'topic' as type,
+ ${topics.agentId} as route_id,
+ ${topics.groupId} as route_group_id,
+ ${topics.updatedAt} as updated_at,
+ ${topics.metadata} as metadata
+ FROM ${topics}
+ LEFT JOIN ${agents} ON ${topics.agentId} = ${agents.id}
+ WHERE ${topics.userId} = ${this.userId}
+ AND (
+ ${topics.groupId} IS NOT NULL
+ OR ${agents.slug} = 'inbox'
+ OR (${topics.groupId} IS NULL AND ${agents.virtual} != true)
+ )
+
+ UNION ALL
+
+ SELECT
+ ${documents.id} as id,
+ COALESCE(${documents.title}, ${documents.filename}, 'Untitled Document') as title,
+ 'document' as type,
+ NULL as route_id,
+ NULL as route_group_id,
+ ${documents.updatedAt} as updated_at,
+ NULL as metadata
+ FROM ${documents}
+ WHERE ${documents.userId} = ${this.userId}
+ AND ${documents.sourceType} != 'file'
+ AND ${documents.knowledgeBaseId} IS NULL
+ AND ${documents.fileType} != 'custom/folder'
+
+ UNION ALL
+
+ SELECT
+ ${tasks.id} as id,
+ COALESCE(${tasks.name}, ${tasks.instruction}, 'Untitled Task') as title,
+ 'task' as type,
+ ${tasks.assigneeAgentId} as route_id,
+ NULL as route_group_id,
+ ${tasks.updatedAt} as updated_at,
+ NULL as metadata
+ FROM ${tasks}
+ WHERE ${tasks.createdByUserId} = ${this.userId}
+ ) AS combined
+ ORDER BY updated_at DESC
+ LIMIT ${limit}
+ `;
+
+ const result = await this.db.execute(query);
+
+ return result.rows.map((row: any) => ({
+ id: row.id,
+ metadata: row.metadata ?? undefined,
+ routeGroupId: row.route_group_id,
+ routeId: row.route_id,
+ title: row.title,
+ type: row.type as RecentDbItem['type'],
+ updatedAt: new Date(row.updated_at),
+ }));
+ };
+}
diff --git a/src/features/AgentHome/AgentInfo.tsx b/src/features/AgentHome/AgentInfo.tsx
new file mode 100644
index 00000000000..15415ed5f06
--- /dev/null
+++ b/src/features/AgentHome/AgentInfo.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+import { Avatar, Flexbox, Markdown, Text } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors';
+
+const AgentInfo = memo(() => {
+ const { t } = useTranslation(['chat', 'welcome']);
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const openingMessage = useAgentStore(agentSelectors.openingMessage);
+ const fontSize = useUserStore(userGeneralSettingsSelectors.fontSize);
+
+ const displayTitle = isInbox
+ ? meta.title || 'Lobe AI'
+ : meta.title || t('defaultSession', { ns: 'common' });
+
+ const message = useMemo(() => {
+ if (openingMessage) return openingMessage;
+ return t('agentDefaultMessageWithSystemRole', {
+ name: displayTitle,
+ });
+ }, [openingMessage, displayTitle, t]);
+
+ return (
+ <Flexbox gap={12}>
+ <Avatar
+ avatar={isInbox ? meta.avatar || DEFAULT_INBOX_AVATAR : meta.avatar || DEFAULT_AVATAR}
+ background={meta.backgroundColor}
+ shape={'square'}
+ size={64}
+ />
+ <Text fontSize={24} weight={'bold'}>
+ {displayTitle}
+ </Text>
+ <Flexbox width={'min(100%, 640px)'}>
+ <Markdown fontSize={fontSize} variant={'chat'}>
+ {message}
+ </Markdown>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default AgentInfo;
diff --git a/src/features/AgentHome/OpeningQuestions.tsx b/src/features/AgentHome/OpeningQuestions.tsx
new file mode 100644
index 00000000000..4b873b62efd
--- /dev/null
+++ b/src/features/AgentHome/OpeningQuestions.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import { Block, Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useConversationStore } from '@/features/Conversation';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ card: css`
+ padding-block: 8px;
+ padding-inline: 16px;
+ border-radius: 48px;
+ `,
+ container: css`
+ padding-block: 0;
+ padding-inline: 0;
+ `,
+ title: css`
+ color: ${cssVar.colorTextDescription};
+ `,
+}));
+
+interface OpeningQuestionsProps {
+ questions: string[];
+}
+
+const OpeningQuestions = memo<OpeningQuestionsProps>(({ questions }) => {
+ const { t } = useTranslation('welcome');
+ const [sendMessage] = useConversationStore((s) => [s.sendMessage]);
+
+ return (
+ <div className={styles.container}>
+ <p className={styles.title}>{t('guide.questions.title')}</p>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {questions.slice(0, 5).map((question) => (
+ <Block
+ clickable
+ className={styles.card}
+ key={question}
+ paddingBlock={8}
+ paddingInline={12}
+ variant={'filled'}
+ onClick={() => {
+ sendMessage({ message: question });
+ }}
+ >
+ {question}
+ </Block>
+ ))}
+ </Flexbox>
+ </div>
+ );
+});
+
+export default OpeningQuestions;
diff --git a/src/features/AgentHome/RecentTopics.tsx b/src/features/AgentHome/RecentTopics.tsx
new file mode 100644
index 00000000000..b85a7a44ac1
--- /dev/null
+++ b/src/features/AgentHome/RecentTopics.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { BotMessageSquareIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link, useParams } from 'react-router-dom';
+import useSWR from 'swr';
+
+import { topicService } from '@/services/topic';
+
+import SectionHeader from './SectionHeader';
+
+const AgentRecentTopics = memo(() => {
+ const { t } = useTranslation('chat');
+ const { aid } = useParams<{ aid: string }>();
+
+ const { data: result, isLoading } = useSWR(
+ aid ? ['agentHome.topics', aid] : null,
+ () => topicService.getTopics({ agentId: aid!, current: 0, pageSize: 10 }),
+ );
+
+ const topics = result?.items;
+
+ if (isLoading || !topics || topics.length === 0) return null;
+
+ return (
+ <Flexbox gap={16}>
+ <SectionHeader
+ icon={BotMessageSquareIcon}
+ title={t('topic.recent')}
+ actionUrl={`/agent/${aid}`}
+ actionLabel={t('topic.viewAll')}
+ />
+ <Flexbox horizontal gap={12} style={{ overflowX: 'auto', paddingBottom: 4 }}>
+ {topics.map((topic) => (
+ <Link
+ key={topic.id}
+ to={`/agent/${aid}?topic=${topic.id}`}
+ style={{ color: 'inherit', flexShrink: 0, textDecoration: 'none' }}
+ >
+ <Block
+ clickable
+ flex={'none'}
+ height={80}
+ variant={'outlined'}
+ width={180}
+ style={{
+ borderRadius: cssVar.borderRadiusLG,
+ overflow: 'hidden',
+ }}
+ >
+ <Flexbox gap={4} height={'100%'} justify={'center'} padding={12}>
+ <Text ellipsis weight={500}>
+ {topic.title || t('topic.defaultTitle')}
+ </Text>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {topic.updatedAt
+ ? new Date(topic.updatedAt).toLocaleDateString()
+ : ''}
+ </Text>
+ </Flexbox>
+ </Block>
+ </Link>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default AgentRecentTopics;
diff --git a/src/features/AgentHome/SectionHeader.tsx b/src/features/AgentHome/SectionHeader.tsx
new file mode 100644
index 00000000000..285f68495de
--- /dev/null
+++ b/src/features/AgentHome/SectionHeader.tsx
@@ -0,0 +1,34 @@
+'use client';
+
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { type LucideIcon } from 'lucide-react';
+import { memo } from 'react';
+import { Link } from 'react-router-dom';
+
+interface SectionHeaderProps {
+ actionLabel?: string;
+ actionUrl?: string;
+ icon: LucideIcon;
+ title: string;
+}
+
+const SectionHeader = memo<SectionHeaderProps>(({ icon, title, actionLabel, actionUrl }) => {
+ return (
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextDescription} icon={icon} size={18} />
+ <Text color={cssVar.colorTextSecondary}>{title}</Text>
+ </Flexbox>
+ {actionLabel && actionUrl && (
+ <Link to={actionUrl} style={{ color: 'inherit', textDecoration: 'none' }}>
+ <Text fontSize={12} type={'secondary'}>
+ {actionLabel}
+ </Text>
+ </Link>
+ )}
+ </Flexbox>
+ );
+});
+
+export default SectionHeader;
diff --git a/src/features/AgentHome/TaskList.tsx b/src/features/AgentHome/TaskList.tsx
new file mode 100644
index 00000000000..fe78b930d45
--- /dev/null
+++ b/src/features/AgentHome/TaskList.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { Block, Flexbox, Tag, Text } from '@lobehub/ui';
+import { CheckSquareIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router-dom';
+import useSWR from 'swr';
+
+import { taskService } from '@/services/task';
+
+import SectionHeader from './SectionHeader';
+
+const STATUS_COLORS: Record<string, string> = {
+ completed: 'green',
+ failed: 'red',
+ in_progress: 'blue',
+ pending: 'default',
+ running: 'blue',
+};
+
+const AgentTaskList = memo(() => {
+ const { t } = useTranslation('chat');
+ const { aid } = useParams<{ aid: string }>();
+
+ const { data: result, isLoading } = useSWR(aid ? ['agentHome.tasks', aid] : null, () =>
+ taskService.list({ assigneeAgentId: aid!, limit: 10 }),
+ );
+
+ const tasks = result?.data;
+
+ if (isLoading || !tasks || tasks.length === 0) return null;
+
+ return (
+ <Flexbox gap={16}>
+ <SectionHeader icon={CheckSquareIcon} title={t('task.title')} />
+ <Flexbox gap={2}>
+ {tasks.map((task: any) => (
+ <Block clickable key={task.id} variant={'borderless'}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ height={48}
+ justify={'space-between'}
+ paddingInline={12}
+ >
+ <Flexbox flex={1} gap={2} style={{ overflow: 'hidden' }}>
+ <Text ellipsis weight={500}>
+ {task.name || task.instruction}
+ </Text>
+ {task.description && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {task.description}
+ </Text>
+ )}
+ </Flexbox>
+ <Tag color={STATUS_COLORS[task.status] || 'default'} style={{ flexShrink: 0 }}>
+ {task.status}
+ </Tag>
+ </Flexbox>
+ </Block>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default AgentTaskList;
diff --git a/src/features/AgentHome/index.tsx b/src/features/AgentHome/index.tsx
new file mode 100644
index 00000000000..7f2586c25b4
--- /dev/null
+++ b/src/features/AgentHome/index.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+
+import ToolAuthAlert from '@/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import AgentInfo from './AgentInfo';
+import OpeningQuestions from './OpeningQuestions';
+
+const AgentHome = memo(() => {
+ const openingQuestions = useAgentStore(agentSelectors.openingQuestions, isEqual);
+
+ return (
+ <>
+ <Flexbox flex={1} />
+ <Flexbox gap={32} style={{ paddingBottom: 'max(4vh, 16px)' }} width={'100%'}>
+ <AgentInfo />
+ {openingQuestions.length > 0 && <OpeningQuestions questions={openingQuestions} />}
+ <ToolAuthAlert />
+ </Flexbox>
+ </>
+ );
+});
+
+export default AgentHome;
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index ba24a8bd303..9a1f9e47143 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -62,6 +62,7 @@ interface DesktopChatInputProps extends ActionToolbarProps {
extentHeaderContent?: ReactNode;
inputContainerProps?: ChatInputProps;
leftContent?: ReactNode;
+ placeholder?: ReactNode;
sendAreaPrefix?: ReactNode;
showFootnote?: boolean;
showRuntimeConfig?: boolean;
@@ -78,6 +79,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
extraActionItems,
dropdownPlacement,
leftContent,
+ placeholder,
sendAreaPrefix,
}) => {
const { t } = useTranslation('chat');
@@ -160,7 +162,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
{...inputContainerProps}
className={cx(expand && styles.inputFullscreen, inputContainerProps?.className)}
>
- <InputEditor />
+ <InputEditor placeholder={placeholder} />
</ChatInput>
{showRuntimeConfig && <RuntimeConfig />}
{showFootnote && !expand && (
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index 6451c6c40ef..81d615f7965 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -7,7 +7,7 @@ import { Editor, FloatMenu, useEditorState } from '@lobehub/editor/react';
import { combineKeys } from '@lobehub/ui';
import { css, cx } from 'antd-style';
import Fuse from 'fuse.js';
-import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
+import { memo, type ReactNode, useCallback, useEffect, useMemo, useRef } from 'react';
import { useHotkeysContext } from 'react-hotkeys-hook';
import { usePasteFile, useUploadFiles } from '@/components/DragUploadZone';
@@ -43,313 +43,320 @@ const className = cx(css`
}
`);
-const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
- const [editor, slashMenuRef, send, updateMarkdownContent, expand, slashPlacement] =
- useChatInputStore((s) => [
- s.editor,
- s.slashMenuRef,
- s.handleSendButton,
- s.updateMarkdownContent,
- s.expand,
- s.slashPlacement ?? 'top',
- ]);
-
- const storeApi = useStoreApi();
- const state = useEditorState(editor);
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
- const { enableScope, disableScope } = useHotkeysContext();
-
- const { compositionProps, isComposingRef } = useIMECompositionEvent();
-
- const useCmdEnterToSend = useUserStore(preferenceSelectors.useCmdEnterToSend);
-
- // --- Category-based mention system ---
- const categories = useMentionCategories();
- const stateRef = useRef<MentionMenuState>({ isSearch: false, matchingString: '' });
- const categoriesRef = useRef(categories);
- categoriesRef.current = categories;
-
- const allMentionItems = useMemo(() => categories.flatMap((c) => c.items), [categories]);
-
- const fuse = useMemo(
- () =>
- new Fuse(allMentionItems, {
- keys: ['key', 'label', 'metadata.topicTitle'],
- threshold: 0.3,
- }),
- [allMentionItems],
- );
-
- const mentionItemsFn = useCallback(
- async (
- search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
- ) => {
- if (search?.matchingString) {
- stateRef.current = { isSearch: true, matchingString: search.matchingString };
- return fuse.search(search.matchingString).map((r) => r.item);
- }
- stateRef.current = { isSearch: false, matchingString: '' };
- return [...allMentionItems];
- },
- [allMentionItems, fuse],
- );
-
- const MentionMenuComp = useMemo(() => createMentionMenu(stateRef, categoriesRef), []);
-
- const enableMention = allMentionItems.length > 0;
-
- // Get agent's model info for vision support check and handle paste upload
- const agentId = useAgentId();
- const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
- const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
- const { handleUploadFiles } = useUploadFiles({ model, provider });
-
- // Listen to editor's paste event for file uploads
- usePasteFile(editor, handleUploadFiles);
-
- useEffect(() => {
- const fn = (e: BeforeUnloadEvent) => {
- if (!state.isEmpty) {
- // set returnValue to trigger alert modal
- // Note: No matter what value is set, the browser will display the standard text
- e.returnValue = 'You are typing something, are you sure you want to leave?';
- }
- };
- window.addEventListener('beforeunload', fn);
- return () => {
- window.removeEventListener('beforeunload', fn);
- };
- }, [state.isEmpty]);
-
- const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
-
- const slashActionItems = useSlashActionItems();
- const slashItems = useCallback(
- async (
- search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
- ) => {
- const actionItems =
- typeof slashActionItems === 'function' ? await slashActionItems(search) : slashActionItems;
-
- return actionItems;
- },
- [slashActionItems],
- );
-
- // --- Auto-completion ---
- const inputCompletionConfig = useUserStore(systemAgentSelectors.inputCompletion);
- const isAutoCompleteEnabled = inputCompletionConfig.enabled;
-
- const getMessagesRef = useRef(storeApi.getState().getMessages);
- useEffect(() => {
- return storeApi.subscribe((s) => {
- getMessagesRef.current = s.getMessages;
- });
- }, [storeApi]);
-
- const handleAutoComplete = useCallback(
- async ({
- abortSignal,
- afterText,
- input,
- }: {
- abortSignal: AbortSignal;
- afterText: string;
- editor: any;
- input: string;
- selectionType: string;
- }): Promise<string | null> => {
- // Skip autocomplete during IME composition (e.g. Chinese input method)
- if (isComposingRef.current) return null;
-
- if (!input.trim()) return null;
-
- const { enabled: _, ...config } = systemAgentSelectors.inputCompletion(
- useUserStore.getState(),
- );
- const context = getMessagesRef.current?.();
- const chainParams = chainInputCompletion(input, afterText, context);
-
- const abortController = new AbortController();
- abortSignal.addEventListener('abort', () => abortController.abort());
-
- let result = '';
-
- try {
- await chatService.fetchPresetTaskResult({
- abortController,
- onMessageHandle: (chunk) => {
- if (chunk.type === 'text') {
- result += chunk.text;
- }
- },
- params: merge(config, chainParams),
- });
- } catch {
- return null;
- }
-
- if (abortSignal.aborted) return null;
-
- return result.trimEnd() || null;
- },
- [],
- );
-
- const autoCompletePlugin = useMemo(
- () =>
- isAutoCompleteEnabled
- ? Editor.withProps(ReactAutoCompletePlugin, {
- delay: 600,
- onAutoComplete: handleAutoComplete,
- })
- : null,
- [isAutoCompleteEnabled, handleAutoComplete],
- );
-
- // --- Stable mentionOption & slashOption to prevent infinite re-render on paste ---
- const mentionMarkdownWriter = useCallback((mention: any) => {
- if (mention.metadata?.type === 'topic') {
- return `<refer_topic name="${mention.metadata.topicTitle}" id="${mention.metadata.topicId}" />`;
- }
- return `<mention name="${mention.label}" id="${mention.metadata.id}" />`;
- }, []);
-
- const mentionOnSelect = useCallback((editor: any, option: any) => {
- if (option.metadata?.type === 'topic') {
- editor.dispatchCommand(INSERT_REFER_TOPIC_COMMAND, {
- topicId: option.metadata.topicId as string,
- topicTitle: String(option.metadata.topicTitle ?? option.label),
- });
- } else if (option.metadata?.type === 'skill' || option.metadata?.type === 'tool') {
- const payload: InsertActionTagPayload = {
- category: option.metadata.actionCategory as 'skill' | 'tool',
- label: String(option.label),
- type: String(option.metadata.actionType),
+const InputEditor = memo<{ defaultRows?: number; placeholder?: ReactNode }>(
+ ({ defaultRows = 2, placeholder }) => {
+ const [editor, slashMenuRef, send, updateMarkdownContent, expand, slashPlacement] =
+ useChatInputStore((s) => [
+ s.editor,
+ s.slashMenuRef,
+ s.handleSendButton,
+ s.updateMarkdownContent,
+ s.expand,
+ s.slashPlacement ?? 'top',
+ ]);
+
+ const storeApi = useStoreApi();
+ const state = useEditorState(editor);
+ const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
+ const { enableScope, disableScope } = useHotkeysContext();
+
+ const { compositionProps, isComposingRef } = useIMECompositionEvent();
+
+ const useCmdEnterToSend = useUserStore(preferenceSelectors.useCmdEnterToSend);
+
+ // --- Category-based mention system ---
+ const categories = useMentionCategories();
+ const stateRef = useRef<MentionMenuState>({ isSearch: false, matchingString: '' });
+ const categoriesRef = useRef(categories);
+ categoriesRef.current = categories;
+
+ const allMentionItems = useMemo(() => categories.flatMap((c) => c.items), [categories]);
+
+ const fuse = useMemo(
+ () =>
+ new Fuse(allMentionItems, {
+ keys: ['key', 'label', 'metadata.topicTitle'],
+ threshold: 0.3,
+ }),
+ [allMentionItems],
+ );
+
+ const mentionItemsFn = useCallback(
+ async (
+ search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
+ ) => {
+ if (search?.matchingString) {
+ stateRef.current = { isSearch: true, matchingString: search.matchingString };
+ return fuse.search(search.matchingString).map((r) => r.item);
+ }
+ stateRef.current = { isSearch: false, matchingString: '' };
+ return [...allMentionItems];
+ },
+ [allMentionItems, fuse],
+ );
+
+ const MentionMenuComp = useMemo(() => createMentionMenu(stateRef, categoriesRef), []);
+
+ const enableMention = allMentionItems.length > 0;
+
+ // Get agent's model info for vision support check and handle paste upload
+ const agentId = useAgentId();
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
+ const { handleUploadFiles } = useUploadFiles({ model, provider });
+
+ // Listen to editor's paste event for file uploads
+ usePasteFile(editor, handleUploadFiles);
+
+ useEffect(() => {
+ const fn = (e: BeforeUnloadEvent) => {
+ if (!state.isEmpty) {
+ // set returnValue to trigger alert modal
+ // Note: No matter what value is set, the browser will display the standard text
+ e.returnValue = 'You are typing something, are you sure you want to leave?';
+ }
};
- editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);
- } else {
- editor.dispatchCommand(INSERT_MENTION_COMMAND, {
- label: String(option.label),
- metadata: option.metadata,
+ window.addEventListener('beforeunload', fn);
+ return () => {
+ window.removeEventListener('beforeunload', fn);
+ };
+ }, [state.isEmpty]);
+
+ const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
+
+ const slashActionItems = useSlashActionItems();
+ const slashItems = useCallback(
+ async (
+ search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
+ ) => {
+ const actionItems =
+ typeof slashActionItems === 'function'
+ ? await slashActionItems(search)
+ : slashActionItems;
+
+ return actionItems;
+ },
+ [slashActionItems],
+ );
+
+ // --- Auto-completion ---
+ const inputCompletionConfig = useUserStore(systemAgentSelectors.inputCompletion);
+ const isAutoCompleteEnabled = inputCompletionConfig.enabled;
+
+ const getMessagesRef = useRef(storeApi.getState().getMessages);
+ useEffect(() => {
+ return storeApi.subscribe((s) => {
+ getMessagesRef.current = s.getMessages;
});
- }
- }, []);
-
- const mentionOption = useMemo(
- () =>
- enableMention
- ? {
- items: mentionItemsFn,
- markdownWriter: mentionMarkdownWriter,
- maxLength: 50,
- onSelect: mentionOnSelect,
- renderComp: MentionMenuComp,
- }
- : undefined,
- [enableMention, mentionItemsFn, mentionMarkdownWriter, mentionOnSelect, MentionMenuComp],
- );
-
- const slashOption = useMemo(() => ({ items: slashItems }), [slashItems]);
-
- const richRenderProps = useMemo(() => {
- const basePlugins = !enableRichRender
- ? CHAT_INPUT_EMBED_PLUGINS
- : createChatInputRichPlugins({
- mathPlugin: Editor.withProps(ReactMathPlugin, {
- renderComp: expand
- ? undefined
- : (props) => (
- <FloatMenu {...props} getPopupContainer={() => (slashMenuRef as any)?.current} />
- ),
- }),
- });
-
- const plugins = autoCompletePlugin ? [...basePlugins, autoCompletePlugin] : basePlugins;
-
- return !enableRichRender
- ? { enablePasteMarkdown: false, markdownOption: false, plugins }
- : { plugins };
- }, [enableRichRender, expand, slashMenuRef, autoCompletePlugin]);
-
- return (
- <Editor
- autoFocus
- pasteAsPlainText
- className={className}
- content={''}
- editor={editor}
- {...{ slashPlacement }}
- {...richRenderProps}
- mentionOption={mentionOption}
- placeholder={<Placeholder />}
- slashOption={slashOption}
- type={'text'}
- variant={'chat'}
- style={{
- minHeight: defaultRows > 1 ? defaultRows * 23 : undefined,
- }}
- onCompositionEnd={({ event }) => compositionProps.onCompositionEnd(event)}
- onCompositionStart={({ event }) => compositionProps.onCompositionStart(event)}
- onBlur={() => {
- disableScope(HotkeyEnum.AddUserMessage);
- }}
- onChange={() => {
- updateMarkdownContent();
- }}
- onContextMenu={async ({ event: e, editor }) => {
- if (isDesktop) {
- e.preventDefault();
- const { electronSystemService } = await import('@/services/electron/system');
-
- const selectionText = editor.getSelectionDocument('markdown') as unknown as string;
-
- await electronSystemService.showContextMenu('editor', {
- selectionText: selectionText || undefined,
+ }, [storeApi]);
+
+ const handleAutoComplete = useCallback(
+ async ({
+ abortSignal,
+ afterText,
+ input,
+ }: {
+ abortSignal: AbortSignal;
+ afterText: string;
+ editor: any;
+ input: string;
+ selectionType: string;
+ }): Promise<string | null> => {
+ // Skip autocomplete during IME composition (e.g. Chinese input method)
+ if (isComposingRef.current) return null;
+
+ if (!input.trim()) return null;
+
+ const { enabled: _, ...config } = systemAgentSelectors.inputCompletion(
+ useUserStore.getState(),
+ );
+ const context = getMessagesRef.current?.();
+ const chainParams = chainInputCompletion(input, afterText, context);
+
+ const abortController = new AbortController();
+ abortSignal.addEventListener('abort', () => abortController.abort());
+
+ let result = '';
+
+ try {
+ await chatService.fetchPresetTaskResult({
+ abortController,
+ onMessageHandle: (chunk) => {
+ if (chunk.type === 'text') {
+ result += chunk.text;
+ }
+ },
+ params: merge(config, chainParams),
});
+ } catch {
+ return null;
}
- }}
- onFocus={() => {
- enableScope(HotkeyEnum.AddUserMessage);
- }}
- onInit={(editor) => {
- const saved = storeApi.getState()._savedEditorState;
- storeApi.setState({ _savedEditorState: undefined, editor });
- if (saved) {
- requestAnimationFrame(() => {
- editor.setDocument('json', saved);
+
+ if (abortSignal.aborted) return null;
+
+ return result.trimEnd() || null;
+ },
+ [],
+ );
+
+ const autoCompletePlugin = useMemo(
+ () =>
+ isAutoCompleteEnabled
+ ? Editor.withProps(ReactAutoCompletePlugin, {
+ delay: 600,
+ onAutoComplete: handleAutoComplete,
+ })
+ : null,
+ [isAutoCompleteEnabled, handleAutoComplete],
+ );
+
+ // --- Stable mentionOption & slashOption to prevent infinite re-render on paste ---
+ const mentionMarkdownWriter = useCallback((mention: any) => {
+ if (mention.metadata?.type === 'topic') {
+ return `<refer_topic name="${mention.metadata.topicTitle}" id="${mention.metadata.topicId}" />`;
+ }
+ return `<mention name="${mention.label}" id="${mention.metadata.id}" />`;
+ }, []);
+
+ const mentionOnSelect = useCallback((editor: any, option: any) => {
+ if (option.metadata?.type === 'topic') {
+ editor.dispatchCommand(INSERT_REFER_TOPIC_COMMAND, {
+ topicId: option.metadata.topicId as string,
+ topicTitle: String(option.metadata.topicTitle ?? option.label),
+ });
+ } else if (option.metadata?.type === 'skill' || option.metadata?.type === 'tool') {
+ const payload: InsertActionTagPayload = {
+ category: option.metadata.actionCategory as 'skill' | 'tool',
+ label: String(option.label),
+ type: String(option.metadata.actionType),
+ };
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);
+ } else {
+ editor.dispatchCommand(INSERT_MENTION_COMMAND, {
+ label: String(option.label),
+ metadata: option.metadata,
+ });
+ }
+ }, []);
+
+ const mentionOption = useMemo(
+ () =>
+ enableMention
+ ? {
+ items: mentionItemsFn,
+ markdownWriter: mentionMarkdownWriter,
+ maxLength: 50,
+ onSelect: mentionOnSelect,
+ renderComp: MentionMenuComp,
+ }
+ : undefined,
+ [enableMention, mentionItemsFn, mentionMarkdownWriter, mentionOnSelect, MentionMenuComp],
+ );
+
+ const slashOption = useMemo(() => ({ items: slashItems }), [slashItems]);
+
+ const richRenderProps = useMemo(() => {
+ const basePlugins = !enableRichRender
+ ? CHAT_INPUT_EMBED_PLUGINS
+ : createChatInputRichPlugins({
+ mathPlugin: Editor.withProps(ReactMathPlugin, {
+ renderComp: expand
+ ? undefined
+ : (props) => (
+ <FloatMenu
+ {...props}
+ getPopupContainer={() => (slashMenuRef as any)?.current}
+ />
+ ),
+ }),
});
- }
- }}
- onPressEnter={({ event: e }) => {
- if (e.shiftKey || isComposingRef.current) return;
- // when user like alt + enter to add ai message
- if (e.altKey && hotkey === combineKeys([KeyEnum.Alt, KeyEnum.Enter])) return true;
- const commandKey = isCommandPressed(e);
- // In fullscreen mode, Enter inserts newline; only Cmd/Ctrl+Enter sends
- if (expand) {
- if (commandKey) {
- send();
- return true;
+
+ const plugins = autoCompletePlugin ? [...basePlugins, autoCompletePlugin] : basePlugins;
+
+ return !enableRichRender
+ ? { enablePasteMarkdown: false, markdownOption: false, plugins }
+ : { plugins };
+ }, [enableRichRender, expand, slashMenuRef, autoCompletePlugin]);
+
+ return (
+ <Editor
+ autoFocus
+ pasteAsPlainText
+ className={className}
+ content={''}
+ editor={editor}
+ {...{ slashPlacement }}
+ {...richRenderProps}
+ mentionOption={mentionOption}
+ placeholder={placeholder ?? <Placeholder />}
+ slashOption={slashOption}
+ type={'text'}
+ variant={'chat'}
+ style={{
+ minHeight: defaultRows > 1 ? defaultRows * 23 : undefined,
+ }}
+ onCompositionEnd={({ event }) => compositionProps.onCompositionEnd(event)}
+ onCompositionStart={({ event }) => compositionProps.onCompositionStart(event)}
+ onBlur={() => {
+ disableScope(HotkeyEnum.AddUserMessage);
+ }}
+ onChange={() => {
+ updateMarkdownContent();
+ }}
+ onContextMenu={async ({ event: e, editor }) => {
+ if (isDesktop) {
+ e.preventDefault();
+ const { electronSystemService } = await import('@/services/electron/system');
+
+ const selectionText = editor.getSelectionDocument('markdown') as unknown as string;
+
+ await electronSystemService.showContextMenu('editor', {
+ selectionText: selectionText || undefined,
+ });
}
- return;
- }
- // when user like cmd + enter to send message
- if (useCmdEnterToSend) {
- if (commandKey) {
- send();
- return true;
+ }}
+ onFocus={() => {
+ enableScope(HotkeyEnum.AddUserMessage);
+ }}
+ onInit={(editor) => {
+ const saved = storeApi.getState()._savedEditorState;
+ storeApi.setState({ _savedEditorState: undefined, editor });
+ if (saved) {
+ requestAnimationFrame(() => {
+ editor.setDocument('json', saved);
+ });
}
- } else {
- if (!commandKey) {
- send();
- return true;
+ }}
+ onPressEnter={({ event: e }) => {
+ if (e.shiftKey || isComposingRef.current) return;
+ // when user like alt + enter to add ai message
+ if (e.altKey && hotkey === combineKeys([KeyEnum.Alt, KeyEnum.Enter])) return true;
+ const commandKey = isCommandPressed(e);
+ // In fullscreen mode, Enter inserts newline; only Cmd/Ctrl+Enter sends
+ if (expand) {
+ if (commandKey) {
+ send();
+ return true;
+ }
+ return;
}
- }
- }}
- />
- );
-});
+ // when user like cmd + enter to send message
+ if (useCmdEnterToSend) {
+ if (commandKey) {
+ send();
+ return true;
+ }
+ } else {
+ if (!commandKey) {
+ send();
+ return true;
+ }
+ }
+ }}
+ />
+ );
+ },
+);
InputEditor.displayName = 'InputEditor';
diff --git a/src/features/Pages/PageLayout/Body/useDropdownMenu.tsx b/src/features/Pages/PageLayout/Body/useDropdownMenu.tsx
index d13d3eb1cc9..3ae492f0677 100644
--- a/src/features/Pages/PageLayout/Body/useDropdownMenu.tsx
+++ b/src/features/Pages/PageLayout/Body/useDropdownMenu.tsx
@@ -34,6 +34,7 @@ export const useDropdownMenu = (): MenuProps['items'] => {
return [
{
children: pageSizeItems,
+ extra: pagePageSize,
icon: <Icon icon={Hash} />,
key: 'displayItems',
label: t('common:navPanel.displayItems'),
diff --git a/src/hooks/useInitRecents.ts b/src/hooks/useInitRecents.ts
new file mode 100644
index 00000000000..be68c62e074
--- /dev/null
+++ b/src/hooks/useInitRecents.ts
@@ -0,0 +1,20 @@
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+export const useInitRecents = () => {
+ const useFetchRecents = useHomeStore((s) => s.useFetchRecents);
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);
+
+ const { isValidating, data, ...rest } = useFetchRecents(isLogin, recentPageSize);
+
+ return {
+ ...rest,
+ data,
+ isLoading: rest.isLoading && isLogin,
+ isRevalidating: isValidating && !!data,
+ };
+};
diff --git a/src/hooks/useNavLayout.ts b/src/hooks/useNavLayout.ts
index f67171d7532..7ebcfb91ca6 100644
--- a/src/hooks/useNavLayout.ts
+++ b/src/hooks/useNavLayout.ts
@@ -65,19 +65,19 @@ export const useNavLayout = (): NavLayout => {
const bottomMenuItems = useMemo(
() =>
[
- {
- icon: getRouteById('resource')!.icon,
- key: SidebarTabKey.Resource,
- title: t('tab.resource'),
- url: '/resource',
- },
{
hidden: !showMarket,
icon: getRouteById('community')!.icon,
key: SidebarTabKey.Community,
- title: t('tab.marketplace'),
+ title: t('tab.community'),
url: '/community',
},
+ {
+ icon: getRouteById('resource')!.icon,
+ key: SidebarTabKey.Resource,
+ title: t('tab.resource'),
+ url: '/resource',
+ },
] as NavItem[],
[t, showMarket],
);
diff --git a/src/hooks/usePrefetchAgent.ts b/src/hooks/usePrefetchAgent.ts
new file mode 100644
index 00000000000..9a19943a778
--- /dev/null
+++ b/src/hooks/usePrefetchAgent.ts
@@ -0,0 +1,24 @@
+import { useCallback } from 'react';
+
+import { mutate } from '@/libs/swr';
+import { agentService } from '@/services/agent';
+
+const FETCH_AGENT_CONFIG_KEY = 'FETCH_AGENT_CONFIG';
+
+/**
+ * Returns a callback to prefetch agent config data into the SWR cache.
+ * Call the returned function on mouseEnter to warm the cache before navigation.
+ */
+export const usePrefetchAgent = () => {
+ return useCallback((agentId: string) => {
+ if (!agentId) return;
+
+ const key = [FETCH_AGENT_CONFIG_KEY, agentId] as const;
+
+ // Populate the SWR cache without triggering re-renders on consuming hooks
+ mutate(key, agentService.getAgentConfigById(agentId), {
+ // Don't revalidate if data already exists
+ revalidate: false,
+ });
+ }, []);
+};
diff --git a/src/hooks/usePrefetchPage.ts b/src/hooks/usePrefetchPage.ts
new file mode 100644
index 00000000000..9508ee19ce2
--- /dev/null
+++ b/src/hooks/usePrefetchPage.ts
@@ -0,0 +1,24 @@
+import { useCallback } from 'react';
+
+import { mutate } from '@/libs/swr';
+import { documentService } from '@/services/document';
+
+/**
+ * Returns a callback to prefetch page/document data into the SWR cache.
+ * Call the returned function on mouseEnter to warm the cache before navigation.
+ */
+export const usePrefetchPage = () => {
+ return useCallback((documentId: string) => {
+ if (!documentId) return;
+
+ // Prefetch individual document content (for the editor)
+ mutate(['document/editor', documentId], documentService.getDocumentById(documentId), {
+ revalidate: false,
+ });
+
+ // Prefetch page documents list (for the sidebar)
+ mutate(['pageDocuments'], documentService.getPageDocuments(), {
+ revalidate: false,
+ });
+ }, []);
+};
diff --git a/src/hooks/usePrefetchResource.ts b/src/hooks/usePrefetchResource.ts
new file mode 100644
index 00000000000..b5d22951ffc
--- /dev/null
+++ b/src/hooks/usePrefetchResource.ts
@@ -0,0 +1,20 @@
+import { useCallback } from 'react';
+
+import { mutate } from '@/libs/swr';
+import { fileService } from '@/services/file';
+
+/**
+ * Returns a callback to prefetch resource/file data into the SWR cache.
+ * Call the returned function on mouseEnter to warm the cache before navigation.
+ */
+export const usePrefetchResource = () => {
+ return useCallback((fileId: string) => {
+ if (!fileId) return;
+
+ const key = ['useFetchKnowledgeItem', fileId] as const;
+
+ mutate(key, fileService.getKnowledgeItem(fileId), {
+ revalidate: false,
+ });
+ }, []);
+};
diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.ts
index 0edac3243dd..44e090d8ad2 100644
--- a/src/libs/swr/localStorageProvider.ts
+++ b/src/libs/swr/localStorageProvider.ts
@@ -273,6 +273,7 @@ const SWR_CACHEABLE_PATTERNS = [
'fetchRecentTopics', // Recent topics
'fetchRecentResources', // Recent resources
'fetchRecentPages', // Recent pages
+ 'fetchRecents', // Unified recents
// Chat page data
'SWR_USE_FETCH_TOPIC', // Topic list (cached per agentId/groupId)
'fetchGroupDetail', // Group detail (cached per groupId)
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 916de99d324..4d2dd06907f 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -153,7 +153,7 @@ export default {
'input.addUser': 'Add a user message',
'input.disclaimer': 'Agents can make mistakes. Use your judgment for critical info.',
'input.errorMsg': 'Send failed: {{errorMsg}}. Retry, or send again later.',
- 'input.more': 'more',
+ 'input.more': 'More',
'input.send': 'Send',
'input.sendWithCmdEnter': 'Press <key/> to send',
'input.sendWithEnter': 'Press <key/> to send',
@@ -236,6 +236,11 @@ export default {
'minimap.previousMessage': 'Previous message',
'minimap.senderAssistant': 'Agent',
'minimap.senderUser': 'You',
+ 'createModal.createBlank': 'Create Blank',
+ 'createModal.groupPlaceholder': 'Describe what this group should do...',
+ 'createModal.groupTitle': 'What should your group do?',
+ 'createModal.placeholder': 'Describe what your agent should do...',
+ 'createModal.title': 'What should your agent do?',
'newAgent': 'Create Agent',
'newGroupChat': 'Create Group',
'newPage': 'Create Page',
@@ -463,13 +468,16 @@ export default {
'toolAuth.authorizing': 'Authorizing...',
'toolAuth.hint':
'Without authorization or configuration, Skills may not work. This can limit the Agent or cause errors.',
+ 'task.title': 'Tasks',
'toolAuth.signIn': 'Sign In',
'toolAuth.title': 'Authorize Skills for this Agent',
'topic.checkOpenNewTopic': 'Start a new topic?',
'topic.checkSaveCurrentMessages': 'Do you want to save the current conversation as a topic?',
'topic.openNewTopic': 'Open New Topic',
+ 'topic.defaultTitle': 'Untitled Topic',
'topic.recent': 'Recent Topics',
'topic.saveCurrentMessages': 'Save current session as topic',
+ 'topic.viewAll': 'View All Topics',
'translate.action': 'Translate',
'translate.clear': 'Clear Translation',
'tts.action': 'Text-to-Speech',
diff --git a/src/locales/default/common.ts b/src/locales/default/common.ts
index 12f1c00bd54..253028083d0 100644
--- a/src/locales/default/common.ts
+++ b/src/locales/default/common.ts
@@ -423,10 +423,19 @@ export default {
'mail.business': 'Business Cooperation',
'mail.support': 'Email Support',
'more': 'More',
- 'navPanel.agent': 'Agent',
+ 'navPanel.agent': 'Agents',
+ 'navPanel.customizeSidebar': 'Customize sidebar',
'navPanel.displayItems': 'Display Items',
+ 'navPanel.hidden': 'Hidden',
+ 'navPanel.hideSection': 'Hide section',
'navPanel.library': 'Library',
+ 'navPanel.moveDown': 'Move down',
+ 'navPanel.pinned': 'Pinned',
+ 'navPanel.moveUp': 'Move up',
+ 'navPanel.show': 'Show',
+ 'navPanel.visible': 'Visible',
'navPanel.searchAgent': 'Search Agent...',
+ 'navPanel.searchRecent': 'Search Recent...',
'navPanel.searchResultEmpty': 'No search results found',
'new': 'New',
'pro': 'Pro',
@@ -484,7 +493,9 @@ export default {
'tab.image': 'Image',
'tab.audio': 'Audio',
'tab.chat': 'Chat',
+ 'recents': 'Recents',
'tab.community': 'Community',
+ 'tab.create': 'Create',
'tab.discover': 'Discover',
'tab.eval': 'Eval Lab',
'tab.files': 'Files',
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
index c50c46cd97f..cdf2c6e6d0d 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -100,6 +100,7 @@ export const useTopicActionsDropdownMenu = (
},
{
children: pageSizeItems,
+ extra: topicPageSize,
icon: <Icon icon={Hash} />,
key: 'displayItems',
label: t('displayItems'),
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 2772ec47494..5f8154381a0 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -4,6 +4,7 @@ import { Flexbox } from '@lobehub/ui';
import debug from 'debug';
import { memo, Suspense, useMemo } from 'react';
+import AgentHome from '@/features/AgentHome';
import ChatMiniMap from '@/features/ChatMiniMap';
import { ChatList, ConversationProvider, TodoProgress } from '@/features/Conversation';
import ZenModeToast from '@/features/ZenModeToast';
@@ -11,7 +12,6 @@ import { useOperationState } from '@/hooks/useOperationState';
import { useChatStore } from '@/store/chat';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import WelcomeChatItem from './AgentWelcome';
import ChatHydration from './ChatHydration';
import MainChatInput from './MainChatInput';
import MessageFromUrl from './MainChatInput/MessageFromUrl';
@@ -71,7 +71,7 @@ const Conversation = memo(() => {
position: 'relative',
}}
>
- <ChatList welcome={<WelcomeChatItem />} />
+ <ChatList welcome={<AgentHome />} />
</Flexbox>
<TodoProgress />
<MainChatInput />
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
index c50c46cd97f..cdf2c6e6d0d 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx
@@ -100,6 +100,7 @@ export const useTopicActionsDropdownMenu = (
},
{
children: pageSizeItems,
+ extra: topicPageSize,
icon: <Icon icon={Hash} />,
key: 'displayItems',
label: t('displayItems'),
diff --git a/src/routes/(main)/home/_layout/Body/Agent/Actions.tsx b/src/routes/(main)/home/_layout/Body/Agent/Actions.tsx
index 4419f6857f7..293448d8a94 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/Actions.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/Actions.tsx
@@ -1,23 +1,24 @@
import type { MenuProps } from '@lobehub/ui';
-import { ActionIcon, DropdownMenu } from '@lobehub/ui';
-import { MoreHorizontalIcon } from 'lucide-react';
+import { ActionIcon, DropdownMenu, Flexbox } from '@lobehub/ui';
+import { MoreHorizontalIcon, PlusIcon } from 'lucide-react';
import { memo } from 'react';
interface ActionsProps {
+ addMenuItems: MenuProps['items'];
dropdownMenu: MenuProps['items'];
isLoading?: boolean;
}
-const Actions = memo<ActionsProps>(({ dropdownMenu, isLoading }) => {
+const Actions = memo<ActionsProps>(({ dropdownMenu, addMenuItems, isLoading }) => {
return (
- <DropdownMenu items={dropdownMenu} nativeButton={false}>
- <ActionIcon
- icon={MoreHorizontalIcon}
- loading={isLoading}
- size={'small'}
- style={{ flex: 'none' }}
- />
- </DropdownMenu>
+ <Flexbox horizontal gap={2}>
+ <DropdownMenu items={dropdownMenu} nativeButton={false}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} style={{ flex: 'none' }} />
+ </DropdownMenu>
+ <DropdownMenu items={addMenuItems} nativeButton={false}>
+ <ActionIcon icon={PlusIcon} loading={isLoading} size={'small'} style={{ flex: 'none' }} />
+ </DropdownMenu>
+ </Flexbox>
);
});
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
index 0e7f6010e29..039be5f0cc0 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
@@ -9,10 +9,12 @@ import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { usePrefetchAgent } from '@/hooks/usePrefetchAgent';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
+import { prefetchRoute } from '@/utils/router';
import { useAgentModal } from '../../ModalProvider';
import Actions from '../Item/Actions';
@@ -32,6 +34,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className }) => {
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
+ const prefetchAgent = usePrefetchAgent();
const isUpdating = useHomeStore((s) => s.agentUpdatingId === id);
// Separate loading state from chat store - only show loading for this specific agent
@@ -44,6 +47,11 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className }) => {
const agentUrl = SESSION_CHAT_URL(id, false);
// Memoize event handlers
+ const handleMouseEnter = useCallback(() => {
+ prefetchAgent(id);
+ prefetchRoute(agentUrl);
+ }, [id, prefetchAgent, agentUrl]);
+
const handleDoubleClick = useCallback(() => {
openAgentInNewWindow(id);
}, [id, openAgentInNewWindow]);
@@ -102,7 +110,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className }) => {
});
return (
- <Link aria-label={displayTitle} ref={setAnchor} to={agentUrl}>
+ <Link aria-label={displayTitle} ref={setAnchor} to={agentUrl} onMouseEnter={handleMouseEnter}>
<NavItem
actions={<Actions dropdownMenu={dropdownMenu} />}
className={className}
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
index a6495a52365..189a5863f01 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/InboxItem.tsx
@@ -7,10 +7,12 @@ import { memo } from 'react';
import { Link } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { usePrefetchAgent } from '@/hooks/usePrefetchAgent';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
+import { prefetchRoute } from '@/utils/router';
interface InboxItemProps {
className?: string;
@@ -22,11 +24,17 @@ const InboxItem = memo<InboxItemProps>(({ className, style }) => {
const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId!));
const isLoading = useChatStore(operationSelectors.isAgentRuntimeRunning);
+ const prefetchAgent = usePrefetchAgent();
const inboxAgentTitle = inboxMeta.title || 'Lobe AI';
const inboxAgentAvatar = inboxMeta.avatar || DEFAULT_INBOX_AVATAR;
+ const inboxUrl = SESSION_CHAT_URL(inboxAgentId, false);
+
+ // Prefetch agent layout chunk and data eagerly since Lobe AI is almost always clicked
+ prefetchRoute(inboxUrl);
+ prefetchAgent(inboxAgentId!);
return (
- <Link aria-label={inboxAgentTitle} to={SESSION_CHAT_URL(inboxAgentId, false)}>
+ <Link aria-label={inboxAgentTitle} to={inboxUrl}>
<NavItem
className={className}
loading={isLoading}
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/List.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/List.tsx
index b4dcd408d96..a9d998b9a9d 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/List.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/List.tsx
@@ -14,6 +14,7 @@ import { homeAgentListSelectors } from '@/store/home/selectors';
import { SessionDefaultGroup } from '@/types/session';
import { useCreateMenuItems } from '../../../hooks';
+import NewAgentButton from '../../NewAgentButton';
import GroupItem from './AgentGroupItem';
import AgentItem from './AgentItem';
@@ -60,13 +61,16 @@ const List = memo<SessionListProps>(
<AgentItem className={itemClassName} item={item} key={item.id} style={itemStyle} />
),
)}
- {hasMore && (
- <NavItem
- icon={MoreHorizontal}
- title={t('input.more')}
- onClick={onMoreClick || openAllAgentsDrawer}
- />
- )}
+ {isDefaultList &&
+ (hasMore ? (
+ <NavItem
+ icon={MoreHorizontal}
+ title={t('input.more')}
+ onClick={onMoreClick || openAllAgentsDrawer}
+ />
+ ) : (
+ <NewAgentButton />
+ ))}
</Flexbox>
);
},
diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
index bb0e4fd032e..730c58b5ea6 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
@@ -1,11 +1,16 @@
'use client';
-import { type ReactNode } from 'react';
+import { type ReactNode, useCallback } from 'react';
import { createContext, memo, use, useMemo, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
import { ChatGroupWizard } from '@/components/ChatGroupWizard';
import { MemberSelectionModal } from '@/components/MemberSelectionModal';
import EditingPopover from '@/features/EditingPopover';
+import { CreateAgentModal } from '@/routes/(main)/home/_layout/hooks/useCreateModal';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useHomeStore } from '@/store/home';
import ConfigGroupModal from './Modals/ConfigGroupModal';
import CreateGroupModal from './Modals/CreateGroupModal';
@@ -18,6 +23,7 @@ interface AgentModalContextValue {
closeMemberSelectionModal: () => void;
openConfigGroupModal: () => void;
openCreateGroupModal: (sessionId: string) => void;
+ openCreateModal: (type: 'agent' | 'group') => void;
openGroupWizardModal: (callbacks: GroupWizardCallbacks) => void;
openMemberSelectionModal: (callbacks: MemberSelectionCallbacks) => void;
setGroupWizardLoading: (loading: boolean) => void;
@@ -44,6 +50,57 @@ export const useAgentModal = () => {
return context;
};
+export const useOptionalAgentModal = () => {
+ return use(AgentModalContext);
+};
+
+interface CreateModalRendererProps {
+ onClose: () => void;
+ open: boolean;
+ type: 'agent' | 'group';
+}
+
+const CreateModalRenderer = memo<CreateModalRendererProps>(({ open, type, onClose }) => {
+ const navigate = useNavigate();
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const storeCreateAgent = useAgentStore((s) => s.createAgent);
+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
+ const sendAsAgent = useHomeStore((s) => s.sendAsAgent);
+ const sendAsGroup = useHomeStore((s) => s.sendAsGroup);
+
+ const handleSubmit = useCallback(
+ async (prompt: string) => {
+ if (type === 'agent') {
+ await sendAsAgent({ message: prompt });
+ } else {
+ await sendAsGroup({ message: prompt });
+ }
+ },
+ [type, sendAsAgent, sendAsGroup],
+ );
+
+ const handleCreateBlank = useCallback(async () => {
+ if (type === 'agent') {
+ const result = await storeCreateAgent({});
+ navigate(`/agent/${result.agentId}/profile`);
+ await refreshAgentList();
+ } else {
+ await sendAsGroup({ message: '' });
+ }
+ }, [type, storeCreateAgent, navigate, refreshAgentList, sendAsGroup]);
+
+ return (
+ <CreateAgentModal
+ agentId={inboxAgentId}
+ open={open}
+ type={type}
+ onClose={onClose}
+ onCreateBlank={handleCreateBlank}
+ onSubmit={handleSubmit}
+ />
+ );
+});
+
interface AgentModalProviderProps {
children: ReactNode;
}
@@ -66,6 +123,10 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
const [memberSelectionCallbacks, setMemberSelectionCallbacks] =
useState<MemberSelectionCallbacks>({});
+ // CreateAgentModal state
+ const [createModalOpen, setCreateModalOpen] = useState(false);
+ const [createModalType, setCreateModalType] = useState<'agent' | 'group'>('agent');
+
const contextValue = useMemo<AgentModalContextValue>(
() => ({
closeAllModals: () => {
@@ -73,6 +134,7 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
setConfigGroupModalOpen(false);
setGroupWizardOpen(false);
setMemberSelectionOpen(false);
+ setCreateModalOpen(false);
},
closeConfigGroupModal: () => setConfigGroupModalOpen(false),
closeCreateGroupModal: () => setCreateGroupModalOpen(false),
@@ -83,6 +145,10 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
setCreateGroupSessionId(sessionId);
setCreateGroupModalOpen(true);
},
+ openCreateModal: (type: 'agent' | 'group') => {
+ setCreateModalType(type);
+ setCreateModalOpen(true);
+ },
openGroupWizardModal: (callbacks: GroupWizardCallbacks) => {
setGroupWizardCallbacks(callbacks);
setGroupWizardOpen(true);
@@ -98,6 +164,11 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
return (
<AgentModalContext value={contextValue}>
+ <CreateModalRenderer
+ open={createModalOpen}
+ type={createModalType}
+ onClose={() => setCreateModalOpen(false)}
+ />
{children}
{/* All modals rendered at top level */}
diff --git a/src/routes/(main)/home/_layout/Body/Agent/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/index.tsx
index 1ea2813d93d..55eff6533cf 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { AccordionItem, ContextMenuTrigger, Flexbox, Text } from '@lobehub/ui';
-import React, { memo, Suspense, useCallback } from 'react';
+import React, { memo, Suspense, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
@@ -25,7 +25,12 @@ const Agent = memo<AgentProps>(({ itemKey }) => {
const { openConfigGroupModal } = useAgentModal();
// Create menu items
- const { isLoading } = useCreateMenuItems();
+ const { createAgentMenuItem, createGroupChatMenuItem, isLoading } = useCreateMenuItems();
+
+ const addMenuItems = useMemo(
+ () => [createAgentMenuItem(), createGroupChatMenuItem()],
+ [createAgentMenuItem, createGroupChatMenuItem],
+ );
const handleOpenConfigGroupModal = useCallback(() => {
openConfigGroupModal();
@@ -37,10 +42,12 @@ const Agent = memo<AgentProps>(({ itemKey }) => {
return (
<AccordionItem
- action={<Actions dropdownMenu={dropdownMenu} isLoading={isLoading} />}
itemKey={itemKey}
paddingBlock={4}
paddingInline={'8px 4px'}
+ action={
+ <Actions addMenuItems={addMenuItems} dropdownMenu={dropdownMenu} isLoading={isLoading} />
+ }
headerWrapper={(header) => (
<ContextMenuTrigger items={dropdownMenu}>{header}</ContextMenuTrigger>
)}
diff --git a/src/routes/(main)/home/_layout/Body/Agent/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/useDropdownMenu.tsx
index 90242eebecc..607d2578b6f 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/useDropdownMenu.tsx
@@ -1,9 +1,10 @@
import { type MenuProps } from '@lobehub/ui';
import { Icon } from '@lobehub/ui';
-import { Hash, LucideCheck } from 'lucide-react';
-import { useMemo } from 'react';
+import { ArrowDownIcon, ArrowUpIcon, Hash, LucideCheck, SlidersHorizontalIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { openCustomizeSidebarModal } from '@/routes/(main)/home/_layout/Body/CustomizeSidebarModal';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -18,26 +19,40 @@ export const useAgentActionsDropdownMenu = ({
}: AgentActionsDropdownMenuProps): MenuProps['items'] => {
const { t } = useTranslation('common');
- const [agentPageSize, updateSystemStatus] = useGlobalStore((s) => [
- systemStatusSelectors.agentPageSize(s),
- s.updateSystemStatus,
- ]);
+ const [agentPageSize, sidebarSectionOrder, hiddenSections, updateSystemStatus] = useGlobalStore(
+ (s) => [
+ systemStatusSelectors.agentPageSize(s),
+ systemStatusSelectors.sidebarSectionOrder(s),
+ systemStatusSelectors.hiddenSidebarSections(s),
+ s.updateSystemStatus,
+ ],
+ );
+
+ const visibleOrder = sidebarSectionOrder.filter((k) => !hiddenSections.includes(k));
+ const visibleIndex = visibleOrder.indexOf('agent');
+ const isFirst = visibleIndex === 0;
+ const isLast = visibleIndex === visibleOrder.length - 1;
+
+ const moveSection = useCallback(
+ (direction: 'up' | 'down') => {
+ const newOrder = [...sidebarSectionOrder];
+ const idx = newOrder.indexOf('agent');
+ const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
+ if (swapIdx < 0 || swapIdx >= newOrder.length) return;
+ [newOrder[idx], newOrder[swapIdx]] = [newOrder[swapIdx], newOrder[idx]];
+ updateSystemStatus({ sidebarSectionOrder: newOrder });
+ },
+ [sidebarSectionOrder, updateSystemStatus],
+ );
// Create menu items
- const {
- createAgentMenuItem,
- createGroupChatMenuItem,
- createSessionGroupMenuItem,
- configMenuItem,
- } = useCreateMenuItems();
+ const { createSessionGroupMenuItem, configMenuItem } = useCreateMenuItems();
return useMemo(() => {
- const createAgentItem = createAgentMenuItem();
- const createGroupChatItem = createGroupChatMenuItem();
const createSessionGroupItem = createSessionGroupMenuItem();
const configItem = configMenuItem(openConfigGroupModal);
- const pageSizeOptions = [10, 15, 20, 40];
+ const pageSizeOptions = [5, 10, 15, 20];
const pageSizeItems = pageSizeOptions.map((size) => ({
icon: agentPageSize === size ? <Icon icon={LucideCheck} /> : <div />,
key: `pageSize-${size}`,
@@ -48,27 +63,48 @@ export const useAgentActionsDropdownMenu = ({
}));
return [
- createAgentItem,
- createGroupChatItem,
+ createSessionGroupItem,
+ configItem,
{ type: 'divider' as const },
{
children: pageSizeItems,
+ extra: agentPageSize,
icon: <Icon icon={Hash} />,
- key: 'displayItems',
- label: t('navPanel.displayItems'),
+ key: 'show',
+ label: t('navPanel.show'),
+ },
+ {
+ disabled: isFirst,
+ icon: <Icon icon={ArrowUpIcon} />,
+ key: 'moveUp',
+ label: t('navPanel.moveUp'),
+ onClick: () => moveSection('up'),
+ },
+ {
+ disabled: isLast,
+ icon: <Icon icon={ArrowDownIcon} />,
+ key: 'moveDown',
+ label: t('navPanel.moveDown'),
+ onClick: () => moveSection('down'),
},
{ type: 'divider' as const },
- createSessionGroupItem,
- configItem,
+ {
+ icon: <Icon icon={SlidersHorizontalIcon} />,
+ key: 'customizeSidebar',
+ label: t('navPanel.customizeSidebar'),
+ onClick: () => openCustomizeSidebarModal(),
+ },
].filter(Boolean) as MenuProps['items'];
}, [
agentPageSize,
updateSystemStatus,
- createAgentMenuItem,
- createGroupChatMenuItem,
createSessionGroupMenuItem,
configMenuItem,
openConfigGroupModal,
+ isFirst,
+ isLast,
+ moveSection,
+ visibleOrder.length,
t,
]);
};
diff --git a/src/routes/(main)/home/_layout/Body/BottomMenu/index.tsx b/src/routes/(main)/home/_layout/Body/BottomMenu/index.tsx
index 0412d828cc4..e813ecef7c5 100644
--- a/src/routes/(main)/home/_layout/Body/BottomMenu/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/BottomMenu/index.tsx
@@ -1,36 +1,90 @@
-import { Flexbox } from '@lobehub/ui';
-import { memo } from 'react';
+import { type MenuProps } from '@lobehub/ui';
+import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
+import { EyeOffIcon, MoreHorizontalIcon, SlidersHorizontalIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useActiveTabKey } from '@/hooks/useActiveTabKey';
import { useNavLayout } from '@/hooks/useNavLayout';
+import { openCustomizeSidebarModal } from '@/routes/(main)/home/_layout/Body/CustomizeSidebarModal';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
import { isModifierClick } from '@/utils/navigation';
+import { prefetchRoute } from '@/utils/router';
const BottomMenu = memo(() => {
+ const { t } = useTranslation('common');
const tab = useActiveTabKey();
const navigate = useNavigate();
const { bottomMenuItems: items } = useNavLayout();
+ const [hiddenSections, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.hiddenSidebarSections(s),
+ s.updateSystemStatus,
+ ]);
+
+ const hideSection = useCallback(
+ (key: string) => {
+ updateSystemStatus({ hiddenSidebarSections: [...hiddenSections, key] });
+ },
+ [hiddenSections, updateSystemStatus],
+ );
+
+ const getContextMenuItems = useCallback(
+ (key: string): MenuProps['items'] => [
+ {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'hideSection',
+ label: t('navPanel.hideSection'),
+ onClick: () => hideSection(key),
+ },
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={SlidersHorizontalIcon} />,
+ key: 'customizeSidebar',
+ label: t('navPanel.customizeSidebar'),
+ onClick: () => openCustomizeSidebarModal(),
+ },
+ ],
+ [t, hideSection],
+ );
+
+ const visibleItems = items.filter((item) => !item.hidden && !hiddenSections.includes(item.key));
+
+ if (visibleItems.length === 0) return null;
return (
<Flexbox
gap={1}
paddingBlock={4}
style={{
+ marginTop: 12,
overflow: 'hidden',
}}
>
- {items.map((item) => (
+ {visibleItems.map((item) => (
<Link
key={item.key}
to={item.url!}
+ onMouseEnter={() => prefetchRoute(item.url!)}
onClick={(e) => {
if (isModifierClick(e)) return;
e.preventDefault();
navigate(item.url!);
}}
>
- <NavItem active={tab === item.key} icon={item.icon} title={item.title} />
+ <NavItem
+ active={tab === item.key}
+ contextMenuItems={getContextMenuItems(item.key)}
+ icon={item.icon}
+ title={item.title}
+ actions={
+ <DropdownMenu items={getContextMenuItems(item.key)} nativeButton={false}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} style={{ flex: 'none' }} />
+ </DropdownMenu>
+ }
+ />
</Link>
))}
</Flexbox>
diff --git a/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.tsx b/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.tsx
new file mode 100644
index 00000000000..208a21c122f
--- /dev/null
+++ b/src/routes/(main)/home/_layout/Body/CustomizeSidebarModal.tsx
@@ -0,0 +1,161 @@
+'use client';
+
+import { ActionIcon, Block, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
+import { Modal } from '@lobehub/ui/base-ui';
+import { Divider } from 'antd';
+import { Eye, EyeOff, PinIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { create } from 'zustand';
+
+import { getRouteById } from '@/config/routes';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+// Top nav items (Pages)
+const TOP_NAV_ITEMS: { key: string; labelKey: string; routeId?: string }[] = [
+ { key: 'pages', labelKey: 'tab.pages', routeId: 'page' },
+];
+
+// Accordion sections (Recents, Agents)
+// `alwaysVisible` sections cannot be hidden by the user
+const SECTION_ITEMS: { alwaysVisible?: boolean; icon?: any; key: string; labelKey: string }[] = [
+ { key: 'recents', labelKey: 'recents' },
+ { alwaysVisible: true, key: 'agent', labelKey: 'navPanel.agent' },
+];
+
+// Bottom menu items (Community, Resources)
+const BOTTOM_ITEMS: { key: string; labelKey: string; routeId?: string }[] = [
+ { key: 'community', labelKey: 'tab.community', routeId: 'community' },
+ { key: 'resource', labelKey: 'tab.resource', routeId: 'resource' },
+];
+
+const useCustomizeSidebarModalStore = create<{
+ open: boolean;
+ setOpen: (open: boolean) => void;
+}>((set) => ({
+ open: false,
+ setOpen: (open) => set({ open }),
+}));
+
+export const openCustomizeSidebarModal = () =>
+ useCustomizeSidebarModalStore.getState().setOpen(true);
+
+const SectionRow = memo<{
+ alwaysVisible?: boolean;
+ icon?: any;
+ isHidden: boolean;
+ label: string;
+ pinnedTooltip?: string;
+ toggleTooltip?: string;
+ onToggle: () => void;
+}>(({ label, icon, isHidden, alwaysVisible, pinnedTooltip, toggleTooltip, onToggle }) => (
+ <Block style={{ opacity: isHidden ? 0.5 : 1 }} variant={isHidden ? 'filled' : 'borderless'}>
+ <Flexbox horizontal align={'center'} height={40} justify={'space-between'} paddingInline={8}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ {icon && <Icon icon={icon} size={18} />}
+ <Text>{label}</Text>
+ </Flexbox>
+ {alwaysVisible ? (
+ <Tooltip title={pinnedTooltip}>
+ <ActionIcon icon={PinIcon} size={'small'} style={{ cursor: 'default', opacity: 0.45 }} />
+ </Tooltip>
+ ) : (
+ <Tooltip title={toggleTooltip}>
+ <ActionIcon icon={isHidden ? EyeOff : Eye} size={'small'} onClick={onToggle} />
+ </Tooltip>
+ )}
+ </Flexbox>
+ </Block>
+));
+
+const CustomizeSidebarContent = memo(() => {
+ const { t } = useTranslation('common');
+
+ const [sidebarSectionOrder, hiddenSections, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.sidebarSectionOrder(s),
+ systemStatusSelectors.hiddenSidebarSections(s),
+ s.updateSystemStatus,
+ ]);
+
+ const toggleSection = (sectionKey: string) => {
+ const isHidden = hiddenSections.includes(sectionKey);
+ const newHidden = isHidden
+ ? hiddenSections.filter((k) => k !== sectionKey)
+ : [...hiddenSections, sectionKey];
+ updateSystemStatus({ hiddenSidebarSections: newHidden });
+ };
+
+ return (
+ <Flexbox gap={2}>
+ {TOP_NAV_ITEMS.map((item) => {
+ const route = item.routeId ? getRouteById(item.routeId) : undefined;
+ const isHidden = hiddenSections.includes(item.key);
+ return (
+ <SectionRow
+ icon={route?.icon}
+ isHidden={isHidden}
+ key={item.key}
+ label={t(item.labelKey as any)}
+ toggleTooltip={t(isHidden ? ('navPanel.hidden' as any) : ('navPanel.visible' as any))}
+ onToggle={() => toggleSection(item.key)}
+ />
+ );
+ })}
+ <Divider style={{ margin: '8px 0' }} />
+ {sidebarSectionOrder.map((key) => {
+ const item = SECTION_ITEMS.find((i) => i.key === key);
+ if (!item) return null;
+ const isHidden = !item.alwaysVisible && hiddenSections.includes(key);
+
+ return (
+ <SectionRow
+ alwaysVisible={item.alwaysVisible}
+ isHidden={isHidden}
+ key={key}
+ label={t(item.labelKey as any)}
+ pinnedTooltip={t('navPanel.pinned' as any)}
+ toggleTooltip={t(isHidden ? ('navPanel.hidden' as any) : ('navPanel.visible' as any))}
+ onToggle={() => toggleSection(key)}
+ />
+ );
+ })}
+ <Divider style={{ margin: '8px 0' }} />
+ {BOTTOM_ITEMS.map((item) => {
+ const route = item.routeId ? getRouteById(item.routeId) : undefined;
+ const icon = route?.icon;
+ const isHidden = hiddenSections.includes(item.key);
+ return (
+ <SectionRow
+ icon={icon}
+ isHidden={isHidden}
+ key={item.key}
+ label={t(item.labelKey as any)}
+ toggleTooltip={t(isHidden ? ('navPanel.hidden' as any) : ('navPanel.visible' as any))}
+ onToggle={() => toggleSection(item.key)}
+ />
+ );
+ })}
+ </Flexbox>
+ );
+});
+
+export const CustomizeSidebarModal = memo(() => {
+ const { t } = useTranslation('common');
+ const open = useCustomizeSidebarModalStore((s) => s.open);
+ const setOpen = useCustomizeSidebarModalStore((s) => s.setOpen);
+
+ return (
+ <Modal
+ centered
+ destroyOnHidden
+ footer={null}
+ open={open}
+ title={t('navPanel.customizeSidebar')}
+ width={360}
+ onCancel={() => setOpen(false)}
+ >
+ <CustomizeSidebarContent />
+ </Modal>
+ );
+});
diff --git a/src/routes/(main)/home/_layout/Body/InboxEntry.tsx b/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
new file mode 100644
index 00000000000..f2d1d94b811
--- /dev/null
+++ b/src/routes/(main)/home/_layout/Body/InboxEntry.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import { DEFAULT_INBOX_AVATAR, SESSION_CHAT_URL } from '@lobechat/const';
+import { Avatar } from '@lobehub/ui';
+import { memo } from 'react';
+import { Link, useNavigate } from 'react-router-dom';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { operationSelectors } from '@/store/chat/selectors';
+import { isModifierClick } from '@/utils/navigation';
+
+const InboxEntry = memo(() => {
+ const navigate = useNavigate();
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId!));
+ const isLoading = useChatStore(operationSelectors.isAgentRuntimeRunning);
+
+ const title = inboxMeta.title || 'Lobe AI';
+ const avatar = inboxMeta.avatar || DEFAULT_INBOX_AVATAR;
+ const url = SESSION_CHAT_URL(inboxAgentId, false);
+
+ return (
+ <Link
+ aria-label={title}
+ to={url}
+ onClick={(e) => {
+ if (isModifierClick(e)) return;
+ e.preventDefault();
+ navigate(url);
+ }}
+ >
+ <NavItem
+ loading={isLoading}
+ title={title}
+ icon={<Avatar emojiScaleWithBackground avatar={avatar} shape={'square'} size={24} />}
+ />
+ </Link>
+ );
+});
+
+export default InboxEntry;
diff --git a/src/routes/(main)/home/_layout/Body/NewAgentButton.tsx b/src/routes/(main)/home/_layout/Body/NewAgentButton.tsx
new file mode 100644
index 00000000000..da6dc574a51
--- /dev/null
+++ b/src/routes/(main)/home/_layout/Body/NewAgentButton.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import { ActionIcon, DropdownMenu } from '@lobehub/ui';
+import { CreateBotIcon } from '@lobehub/ui/icons';
+import { cssVar } from 'antd-style';
+import { ChevronDownIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+
+import { useCreateMenuItems } from '../hooks';
+
+const NewAgentButton = memo(() => {
+ const { t } = useTranslation('chat');
+ const { createAgentMenuItem, createGroupChatMenuItem, isMutatingAgent, openCreateModal } =
+ useCreateMenuItems();
+
+ const dropdownItems = useMemo(
+ () => [createAgentMenuItem(), createGroupChatMenuItem()],
+ [createAgentMenuItem, createGroupChatMenuItem],
+ );
+
+ return (
+ <NavItem
+ icon={CreateBotIcon}
+ loading={isMutatingAgent}
+ title={t('newAgent')}
+ actions={
+ <DropdownMenu items={dropdownItems} nativeButton={false}>
+ <ActionIcon
+ color={cssVar.colorTextQuaternary}
+ icon={ChevronDownIcon}
+ size={'small'}
+ style={{ flex: 'none' }}
+ />
+ </DropdownMenu>
+ }
+ onClick={() => openCreateModal?.('agent')}
+ />
+ );
+});
+
+export default NewAgentButton;
diff --git a/src/routes/(main)/home/_layout/Body/index.tsx b/src/routes/(main)/home/_layout/Body/index.tsx
index 888e18f98f0..b24ed354412 100644
--- a/src/routes/(main)/home/_layout/Body/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/index.tsx
@@ -1,23 +1,47 @@
'use client';
import { Accordion, Flexbox } from '@lobehub/ui';
-import { memo } from 'react';
+import { memo, type ReactElement, useMemo } from 'react';
+
+import Recents from '@/routes/(main)/home/features/Recents';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
import Agent from './Agent';
import BottomMenu from './BottomMenu';
+import { CustomizeSidebarModal } from './CustomizeSidebarModal';
export enum GroupKey {
Agent = 'agent',
Project = 'project',
+ Recents = 'recents',
}
+const sectionComponents: Record<string, (key: string) => ReactElement> = {
+ [GroupKey.Agent]: (key) => <Agent itemKey={key} key={key} />,
+ [GroupKey.Recents]: (key) => <Recents itemKey={key} key={key} />,
+};
+
const Body = memo(() => {
+ const sidebarSectionOrder = useGlobalStore(systemStatusSelectors.sidebarSectionOrder);
+ const hiddenSections = useGlobalStore(systemStatusSelectors.hiddenSidebarSections);
+
+ const sections = useMemo(
+ () =>
+ sidebarSectionOrder
+ .filter((key) => key === GroupKey.Agent || !hiddenSections.includes(key))
+ .map((key) => sectionComponents[key]?.(key))
+ .filter(Boolean),
+ [sidebarSectionOrder, hiddenSections],
+ );
+
return (
<Flexbox flex={1} justify={'space-between'} paddingInline={4}>
- <Accordion defaultExpandedKeys={[GroupKey.Project, GroupKey.Agent]} gap={8}>
- <Agent itemKey={GroupKey.Agent} />
+ <Accordion defaultExpandedKeys={[GroupKey.Recents, GroupKey.Project, GroupKey.Agent]} gap={8}>
+ {sections}
</Accordion>
<BottomMenu />
+ <CustomizeSidebarModal />
</Flexbox>
);
});
diff --git a/src/routes/(main)/home/_layout/Footer/index.tsx b/src/routes/(main)/home/_layout/Footer/index.tsx
index 818a38d8417..71602b7452f 100644
--- a/src/routes/(main)/home/_layout/Footer/index.tsx
+++ b/src/routes/(main)/home/_layout/Footer/index.tsx
@@ -12,8 +12,8 @@ import {
FileClockIcon,
FlaskConical,
Rocket,
- Settings,
Settings2,
+ SettingsIcon,
} from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -29,6 +29,7 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors/systemStatus';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors';
+import { prefetchRoute } from '@/utils/router';
const PRODUCT_HUNT_NOTIFICATION = {
actionHref: 'https://www.producthunt.com/products/lobehub?launch=lobehub',
@@ -239,9 +240,14 @@ const Footer = memo(() => {
<DropdownMenu items={helpMenuItems} placement="topLeft">
<ActionIcon aria-label={t('userPanel.help')} icon={CircleHelp} size={16} />
</DropdownMenu>
- {isDevMode && !isSettingsPage && (
- <Link to="/settings">
- <ActionIcon aria-label={t('userPanel.setting')} icon={Settings} size={16} />
+ {isDevMode && (
+ <Link to="/settings" onMouseEnter={() => prefetchRoute('/settings')}>
+ <ActionIcon
+ aria-label={t('userPanel.setting')}
+ icon={SettingsIcon}
+ size={16}
+ title={t('userPanel.setting')}
+ />
</Link>
)}
</Flexbox>
diff --git a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx b/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
index cda88a93b47..2c0450ad27b 100644
--- a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
@@ -17,7 +17,7 @@ const AddButton = memo(() => {
createAgentMenuItem,
createGroupChatMenuItem,
createPageMenuItem,
- createAgent,
+ openCreateModal,
isMutatingAgent,
isCreatingGroup,
} = useCreateMenuItems();
@@ -26,9 +26,9 @@ const AddButton = memo(() => {
(e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
- createAgent();
+ openCreateModal?.('agent');
},
- [createAgent],
+ [openCreateModal],
);
const dropdownItems = useMemo(() => {
diff --git a/src/routes/(main)/home/_layout/Header/components/Nav.tsx b/src/routes/(main)/home/_layout/Header/components/Nav.tsx
index 85123769efa..5f9f10b9976 100644
--- a/src/routes/(main)/home/_layout/Header/components/Nav.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/Nav.tsx
@@ -1,7 +1,9 @@
'use client';
-import { Flexbox, Tag } from '@lobehub/ui';
-import { memo } from 'react';
+import { type MenuProps } from '@lobehub/ui';
+import { ActionIcon, DropdownMenu, Flexbox, Icon, Tag } from '@lobehub/ui';
+import { EyeOffIcon, MoreHorizontalIcon, SlidersHorizontalIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate } from 'react-router-dom';
@@ -9,13 +11,50 @@ import { type NavItemProps } from '@/features/NavPanel/components/NavItem';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useActiveTabKey } from '@/hooks/useActiveTabKey';
import { useNavLayout } from '@/hooks/useNavLayout';
+import { openCustomizeSidebarModal } from '@/routes/(main)/home/_layout/Body/CustomizeSidebarModal';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
import { isModifierClick } from '@/utils/navigation';
+import { prefetchRoute } from '@/utils/router';
+
+/** Keys that cannot be hidden and should not show section actions */
+const PERMANENT_KEYS = new Set(['home', 'search']);
const Nav = memo(() => {
const tab = useActiveTabKey();
const navigate = useNavigate();
const { t } = useTranslation('common');
const { topNavItems: items } = useNavLayout();
+ const [hiddenSections, updateSystemStatus] = useGlobalStore((s) => [
+ systemStatusSelectors.hiddenSidebarSections(s),
+ s.updateSystemStatus,
+ ]);
+
+ const hideSection = useCallback(
+ (key: string) => {
+ updateSystemStatus({ hiddenSidebarSections: [...hiddenSections, key] });
+ },
+ [hiddenSections, updateSystemStatus],
+ );
+
+ const getSectionMenuItems = useCallback(
+ (key: string): MenuProps['items'] => [
+ {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'hideSection',
+ label: t('navPanel.hideSection'),
+ onClick: () => hideSection(key),
+ },
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={SlidersHorizontalIcon} />,
+ key: 'customizeSidebar',
+ label: t('navPanel.customizeSidebar'),
+ onClick: () => openCustomizeSidebarModal(),
+ },
+ ],
+ [t, hideSection],
+ );
const newBadge = (
<Tag color="blue" size="small">
@@ -25,44 +64,52 @@ const Nav = memo(() => {
return (
<Flexbox gap={1} paddingInline={4}>
- {items.map((item) => {
- const extra = item.isNew ? newBadge : undefined;
- const content = (
- <NavItem
- active={tab === item.key}
- extra={extra}
- hidden={item.hidden}
- icon={item.icon as NavItemProps['icon']}
- key={item.key}
- title={item.title}
- onClick={item.onClick}
- />
- );
- if (!item.url) return content;
+ {items
+ .filter((item) => !hiddenSections.includes(item.key))
+ .map((item) => {
+ const extra = item.isNew ? newBadge : undefined;
+ const canHide = !PERMANENT_KEYS.has(item.key);
+ const menuItems = canHide ? getSectionMenuItems(item.key) : undefined;
- return (
- <Link
- key={item.key}
- to={item.url}
- onClick={(e) => {
- if (isModifierClick(e)) return;
- e.preventDefault();
- item?.onClick?.();
- if (item.url) {
- navigate(item.url);
- }
- }}
- >
+ const navItem = (
<NavItem
active={tab === item.key}
+ contextMenuItems={menuItems}
extra={extra}
hidden={item.hidden}
icon={item.icon as NavItemProps['icon']}
title={item.title}
+ actions={
+ menuItems ? (
+ <DropdownMenu items={menuItems} nativeButton={false}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} style={{ flex: 'none' }} />
+ </DropdownMenu>
+ ) : undefined
+ }
+ onClick={item.onClick}
/>
- </Link>
- );
- })}
+ );
+
+ if (!item.url) return <div key={item.key}>{navItem}</div>;
+
+ return (
+ <Link
+ key={item.key}
+ to={item.url}
+ onMouseEnter={() => prefetchRoute(item.url!)}
+ onClick={(e) => {
+ if (isModifierClick(e)) return;
+ e.preventDefault();
+ item?.onClick?.();
+ if (item.url) {
+ navigate(item.url);
+ }
+ }}
+ >
+ {navItem}
+ </Link>
+ );
+ })}
</Flexbox>
);
});
diff --git a/src/routes/(main)/home/_layout/Header/index.tsx b/src/routes/(main)/home/_layout/Header/index.tsx
index b3b95408fc4..a168d262444 100644
--- a/src/routes/(main)/home/_layout/Header/index.tsx
+++ b/src/routes/(main)/home/_layout/Header/index.tsx
@@ -4,7 +4,6 @@ import { memo } from 'react';
import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
-import AddButton from './components/AddButton';
import InboxButton from './components/InboxButton';
import Nav from './components/Nav';
import User from './components/User';
@@ -12,16 +11,7 @@ import User from './components/User';
const Header = memo(() => {
return (
<>
- <SideBarHeaderLayout
- left={<User />}
- showBack={false}
- right={
- <>
- <InboxButton />
- <AddButton />
- </>
- }
- />
+ <SideBarHeaderLayout left={<User />} right={<InboxButton />} showBack={false} />
<Nav />
</>
);
diff --git a/src/routes/(main)/home/_layout/RecentHydration.tsx b/src/routes/(main)/home/_layout/RecentHydration.tsx
index b51ba881431..835d204817a 100644
--- a/src/routes/(main)/home/_layout/RecentHydration.tsx
+++ b/src/routes/(main)/home/_layout/RecentHydration.tsx
@@ -2,12 +2,14 @@ import { memo } from 'react';
import { useInitRecentPage } from '@/hooks/useInitRecentPage';
import { useInitRecentResource } from '@/hooks/useInitRecentResource';
+import { useInitRecents } from '@/hooks/useInitRecents';
import { useInitRecentTopic } from '@/hooks/useInitRecentTopic';
const RecentHydration = memo(() => {
useInitRecentTopic();
useInitRecentResource();
useInitRecentPage();
+ useInitRecents();
return null;
});
diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
index 8954e320f76..f321d67dc96 100644
--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
@@ -10,6 +10,7 @@ import useSWRMutation from 'swr/mutation';
import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';
import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';
+import { useOptionalAgentModal } from '@/routes/(main)/home/_layout/Body/Agent/ModalProvider';
import { type CreateAgentParams } from '@/services/agent';
import { type GroupMemberConfig } from '@/services/chatGroup';
import { chatGroupService } from '@/services/chatGroup';
@@ -65,12 +66,12 @@ export const useCreateMenuItems = () => {
// SWR-based group creation with auto navigation to profile
const { trigger: mutateGroup, isMutating: isMutatingGroup } = useSWRMutation(
'group.createGroup',
- async (_key: string, { arg }: { arg?: CreateAgentOptions }) => {
+ async (_key: string, { arg }: { arg?: CreateAgentOptions & { title?: string } }) => {
const groupId = await createGroup(
{
config: DEFAULT_CHAT_GROUP_CHAT_CONFIG,
groupId: arg?.groupId,
- title: t('defaultGroupChat'),
+ title: arg?.title || t('defaultGroupChat'),
},
[],
true, // silent mode - don't switch session, we'll navigate instead
@@ -87,11 +88,12 @@ export const useCreateMenuItems = () => {
);
/**
- * Create agent action
+ * Create agent action (optionally with a prompt as systemRole)
*/
const createAgent = useCallback(
- async (options?: CreateAgentOptions) => {
- await mutateAgent({ groupId: options?.groupId });
+ async (options?: CreateAgentOptions & { prompt?: string }) => {
+ const config = options?.prompt ? { systemRole: options.prompt } : undefined;
+ await mutateAgent({ config, groupId: options?.groupId });
options?.onSuccess?.();
},
[mutateAgent],
@@ -180,6 +182,19 @@ export const useCreateMenuItems = () => {
[createGroup, message, t],
);
+ /**
+ * Create empty group and navigate to profile
+ */
+ const createEmptyGroup = useCallback(
+ async (options?: CreateAgentOptions & { title?: string }) => {
+ await mutateGroup(options);
+ },
+ [mutateGroup],
+ );
+
+ const agentModal = useOptionalAgentModal();
+ const openCreateModal = agentModal?.openCreateModal;
+
/**
* Create agent menu item
*/
@@ -190,20 +205,16 @@ export const useCreateMenuItems = () => {
label: t('newAgent'),
onClick: async (info) => {
info.domEvent?.stopPropagation();
- await createAgent(options);
+ if (options?.groupId) {
+ await createAgent(options);
+ } else if (openCreateModal) {
+ openCreateModal('agent');
+ } else {
+ await createAgent(options);
+ }
},
}),
- [t, createAgent],
- );
-
- /**
- * Create empty group and navigate to profile
- */
- const createEmptyGroup = useCallback(
- async (options?: CreateAgentOptions) => {
- await mutateGroup(options);
- },
- [mutateGroup],
+ [t, createAgent, openCreateModal],
);
/**
@@ -217,10 +228,16 @@ export const useCreateMenuItems = () => {
label: t('newGroupChat'),
onClick: async (info) => {
info.domEvent?.stopPropagation();
- await createEmptyGroup(options);
+ if (options?.groupId) {
+ await createEmptyGroup(options);
+ } else if (openCreateModal) {
+ openCreateModal('group');
+ } else {
+ await createEmptyGroup(options);
+ }
},
}),
- [t, createEmptyGroup],
+ [t, createEmptyGroup, openCreateModal],
);
/**
@@ -298,6 +315,7 @@ export const useCreateMenuItems = () => {
createPage,
createPageMenuItem,
createSessionGroupMenuItem,
+ openCreateModal,
// Loading states
isCreatingGroup,
diff --git a/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx
new file mode 100644
index 00000000000..490af7d69f7
--- /dev/null
+++ b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx
@@ -0,0 +1,225 @@
+import { ActionIcon, Block, Button, Flexbox, Text } from '@lobehub/ui';
+import { Modal } from '@lobehub/ui/base-ui';
+import { cssVar } from 'antd-style';
+import { Lightbulb, PencilLineIcon, RefreshCw, X } from 'lucide-react';
+import { memo, useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ type ActionKeys,
+ type ChatInputEditor,
+ ChatInputProvider,
+ DesktopChatInput,
+} from '@/features/ChatInput';
+import { useRandomQuestions } from '@/routes/(main)/home/features/SuggestQuestions/useRandomQuestions';
+
+const LEFT_ACTIONS: ActionKeys[] = ['model'];
+
+interface ExampleItemProps {
+ description: string;
+ onClick: (prompt: string) => void;
+ prompt: string;
+ title: string;
+}
+
+const ExampleItem = memo<ExampleItemProps>(({ title, description, onClick, prompt }) => {
+ return (
+ <Block
+ clickable
+ variant={'outlined'}
+ style={{
+ borderRadius: cssVar.borderRadiusLG,
+ cursor: 'pointer',
+ }}
+ onClick={() => onClick(prompt)}
+ >
+ <Flexbox gap={4} paddingBlock={12} paddingInline={14}>
+ <Text ellipsis fontSize={14} style={{ fontWeight: 500 }}>
+ {title}
+ </Text>
+ <Text color={cssVar.colorTextTertiary} ellipsis={{ rows: 2 }} fontSize={12}>
+ {description}
+ </Text>
+ </Flexbox>
+ </Block>
+ );
+});
+
+interface ExamplesProps {
+ onExampleClick: (prompt: string) => void;
+ suggestMode: 'agent' | 'group';
+}
+
+const Examples = memo<ExamplesProps>(({ suggestMode, onExampleClick }) => {
+ const { t: tCommon } = useTranslation('common');
+ const { t: tSuggest } = useTranslation('suggestQuestions');
+ const { questions, refresh } = useRandomQuestions(suggestMode);
+
+ if (questions.length === 0) return null;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Lightbulb color={cssVar.colorTextDescription} size={18} />
+ <Text color={cssVar.colorTextSecondary}>{tCommon('home.suggestQuestions')}</Text>
+ </Flexbox>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={{ cursor: 'pointer' }}
+ onClick={refresh}
+ >
+ <ActionIcon icon={RefreshCw} size={'small'} />
+ <Text color={cssVar.colorTextSecondary} fontSize={12}>
+ {tCommon('switch')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ <Flexbox gap={12} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
+ {questions.map((item) => {
+ const prompt = tSuggest(item.promptKey as any);
+ return (
+ <ExampleItem
+ description={prompt}
+ key={item.id}
+ prompt={prompt}
+ title={tSuggest(item.titleKey as any)}
+ onClick={onExampleClick}
+ />
+ );
+ })}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export interface CreateAgentModalProps {
+ agentId?: string;
+ onClose: () => void;
+ onCreateBlank: () => void;
+ onSubmit: (prompt: string) => void;
+ open: boolean;
+ type: 'agent' | 'group';
+}
+
+export const CreateAgentModal = memo<CreateAgentModalProps>(
+ ({ open, type, agentId, onClose, onSubmit, onCreateBlank }) => {
+ const { t } = useTranslation('chat');
+ const editorRef = useRef<ChatInputEditor | null>(null);
+ const contentRef = useRef('');
+ const [loading, setLoading] = useState(false);
+
+ const isAgent = type === 'agent';
+ const modalTitle = isAgent ? t('createModal.title') : t('createModal.groupTitle');
+
+ const handleSubmit = useCallback(
+ async (prompt?: string) => {
+ const text = prompt || contentRef.current.trim();
+ if (!text || loading) return;
+ setLoading(true);
+ contentRef.current = '';
+ await onSubmit(text);
+ setLoading(false);
+ onClose();
+ },
+ [onClose, onSubmit, loading],
+ );
+
+ const handleCreateBlank = useCallback(async () => {
+ if (loading) return;
+ setLoading(true);
+ contentRef.current = '';
+ await onCreateBlank();
+ setLoading(false);
+ onClose();
+ }, [onClose, onCreateBlank, loading]);
+
+ const handleExampleClick = useCallback((prompt: string) => {
+ editorRef.current?.instance?.setDocument('markdown', prompt);
+ editorRef.current?.focus();
+ contentRef.current = prompt;
+ }, []);
+
+ const handleSend = useCallback(() => {
+ handleSubmit();
+ }, [handleSubmit]);
+
+ const inputContainerProps = useMemo(
+ () => ({
+ minHeight: 88,
+ resize: false,
+ style: { borderRadius: 16 },
+ }),
+ [],
+ );
+
+ const sendButtonProps = useMemo(
+ () => ({
+ generating: loading,
+ onStop: () => {},
+ shape: 'round' as const,
+ }),
+ [loading],
+ );
+
+ return (
+ <Modal
+ centered
+ destroyOnHidden
+ closable={false}
+ footer={null}
+ open={open}
+ title={false}
+ width={'min(90vw, 760px)'}
+ styles={{
+ body: { padding: 0 },
+ }}
+ onCancel={onClose}
+ >
+ <Flexbox gap={24} paddingBlock={'16px 24px'} paddingInline={24}>
+ {/* Header: Create Blank + Close */}
+ <Flexbox horizontal align="center" gap={4} justify="flex-end">
+ <Button icon={<PencilLineIcon size={14} />} type="text" onClick={handleCreateBlank}>
+ {t('createModal.createBlank')}
+ </Button>
+ <ActionIcon icon={X} onClick={onClose} />
+ </Flexbox>
+ {/* Title */}
+ <Flexbox align="center">
+ <h3 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>{modalTitle}</h3>
+ </Flexbox>
+
+ {/* ChatInput */}
+ {open && (
+ <ChatInputProvider
+ agentId={agentId}
+ allowExpand={false}
+ leftActions={LEFT_ACTIONS}
+ sendButtonProps={sendButtonProps}
+ chatInputEditorRef={(instance) => {
+ if (instance) editorRef.current = instance;
+ }}
+ onSend={handleSend}
+ onMarkdownContentChange={(content) => {
+ contentRef.current = content;
+ }}
+ >
+ <DesktopChatInput
+ inputContainerProps={inputContainerProps}
+ placeholder={
+ isAgent ? t('createModal.placeholder') : t('createModal.groupPlaceholder')
+ }
+ showRuntimeConfig={false}
+ />
+ </ChatInputProvider>
+ )}
+
+ {/* Examples */}
+ <Examples suggestMode={type} onExampleClick={handleExampleClick} />
+ </Flexbox>
+ </Modal>
+ );
+ },
+);
diff --git a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
new file mode 100644
index 00000000000..a83c0f7dba8
--- /dev/null
+++ b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
@@ -0,0 +1,82 @@
+'use client';
+
+import { Empty, Flexbox, SearchBar } from '@lobehub/ui';
+import { SearchIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
+
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
+import { useClientDataSWR } from '@/libs/swr';
+import { recentService } from '@/services/recent';
+
+import RecentListItem from './Item';
+
+interface AllRecentsDrawerProps {
+ onClose: () => void;
+ open: boolean;
+}
+
+const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {
+ const { t } = useTranslation('common');
+ const [searchKeyword, setSearchKeyword] = useState('');
+
+ const { data: recents, isLoading } = useClientDataSWR(open ? ['allRecents', open] : null, () =>
+ recentService.getAll(50),
+ );
+
+ const filteredRecents = useMemo(() => {
+ if (!recents) return [];
+ const keyword = searchKeyword.trim().toLowerCase();
+ if (!keyword) return recents;
+ return recents.filter((item) => item.title.toLowerCase().includes(keyword));
+ }, [recents, searchKeyword]);
+
+ return (
+ <SideBarDrawer
+ open={open}
+ title={t('recents')}
+ subHeader={
+ <Flexbox paddingBlock={'0 8px'} paddingInline={8}>
+ <SearchBar
+ allowClear
+ defaultValue={searchKeyword}
+ placeholder={t('navPanel.searchRecent')}
+ onSearch={(keyword) => setSearchKeyword(keyword)}
+ onInputChange={(keyword) => {
+ setSearchKeyword(keyword);
+ }}
+ />
+ </Flexbox>
+ }
+ onClose={onClose}
+ >
+ <Flexbox gap={1} paddingBlock={1} paddingInline={4}>
+ {isLoading || !recents ? (
+ <SkeletonList rows={5} />
+ ) : filteredRecents.length === 0 && searchKeyword.trim() ? (
+ <Empty
+ description={t('navPanel.searchResultEmpty')}
+ icon={SearchIcon}
+ style={{ paddingBlock: 24 }}
+ />
+ ) : (
+ filteredRecents.map((item) => (
+ <Link
+ key={`${item.type}-${item.id}`}
+ style={{ color: 'inherit', textDecoration: 'none' }}
+ to={item.routePath}
+ >
+ <RecentListItem {...item} />
+ </Link>
+ ))
+ )}
+ </Flexbox>
+ </SideBarDrawer>
+ );
+});
+
+AllRecentsDrawer.displayName = 'AllRecentsDrawer';
+
+export default AllRecentsDrawer;
diff --git a/src/routes/(main)/home/features/Recents/Item.tsx b/src/routes/(main)/home/features/Recents/Item.tsx
new file mode 100644
index 00000000000..80f9bedb951
--- /dev/null
+++ b/src/routes/(main)/home/features/Recents/Item.tsx
@@ -0,0 +1,86 @@
+import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { CheckSquareIcon, FileTextIcon, HashIcon, MoreHorizontalIcon } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+
+import InlineRename from '@/components/InlineRename';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { usePrefetchAgent } from '@/hooks/usePrefetchAgent';
+import { usePrefetchPage } from '@/hooks/usePrefetchPage';
+import { getPlatformIcon } from '@/routes/(main)/agent/channel/const';
+import { type RecentItem } from '@/server/routers/lambda/recent';
+
+import { useRecentItemDropdownMenu } from './useDropdownMenu';
+
+const TYPE_ICON_MAP = {
+ document: FileTextIcon,
+ task: CheckSquareIcon,
+ topic: HashIcon,
+};
+
+const RecentListItem = memo<RecentItem>((item) => {
+ const { title, type, agentId, id, metadata } = item;
+ const IconComponent = TYPE_ICON_MAP[type] || FileTextIcon;
+ const [editing, setEditing] = useState(false);
+ const prefetchAgent = usePrefetchAgent();
+ const prefetchPage = usePrefetchPage();
+
+ const toggleEditing = useCallback((visible?: boolean) => {
+ setEditing(!!visible);
+ }, []);
+
+ const handleMouseEnter = useCallback(() => {
+ switch (type) {
+ case 'topic':
+ case 'task': {
+ if (agentId) prefetchAgent(agentId);
+ break;
+ }
+ case 'document': {
+ prefetchPage(id);
+ break;
+ }
+ }
+ }, [type, agentId, id, prefetchAgent, prefetchPage]);
+
+ const { dropdownMenu, handleRename } = useRecentItemDropdownMenu(item, toggleEditing);
+
+ return (
+ <Flexbox style={{ position: 'relative' }}>
+ <NavItem
+ contextMenuItems={dropdownMenu}
+ disabled={editing}
+ title={title}
+ actions={
+ <DropdownMenu items={dropdownMenu()} nativeButton={false}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} style={{ flex: 'none' }} />
+ </DropdownMenu>
+ }
+ icon={(() => {
+ if (type === 'topic' && metadata?.bot?.platform) {
+ const ProviderIcon = getPlatformIcon(metadata.bot.platform);
+ if (ProviderIcon) {
+ return <ProviderIcon color={cssVar.colorTextDescription} size={16} />;
+ }
+ }
+ return (
+ <Icon
+ icon={IconComponent}
+ size={'small'}
+ style={{ color: cssVar.colorTextDescription }}
+ />
+ );
+ })()}
+ onMouseEnter={handleMouseEnter}
+ />
+ <InlineRename
+ open={editing}
+ title={title}
+ onOpenChange={(open) => toggleEditing(open)}
+ onSave={handleRename}
+ />
+ </Flexbox>
+ );
+});
+
+export default RecentListItem;
diff --git a/src/routes/(main)/home/features/Recents/List.tsx b/src/routes/(main)/home/features/Recents/List.tsx
new file mode 100644
index 00000000000..3c429df7a9f
--- /dev/null
+++ b/src/routes/(main)/home/features/Recents/List.tsx
@@ -0,0 +1,54 @@
+import { Flexbox } from '@lobehub/ui';
+import { MoreHorizontalIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeRecentSelectors } from '@/store/home/selectors';
+
+import AllRecentsDrawer from './AllRecentsDrawer';
+import RecentListItem from './Item';
+
+const RecentsList = memo(() => {
+ const { t } = useTranslation('chat');
+ const recents = useHomeStore(homeRecentSelectors.recents);
+ const isInit = useHomeStore(homeRecentSelectors.isRecentsInit);
+ const recentPageSize = useGlobalStore(systemStatusSelectors.recentPageSize);
+ const [drawerOpen, openDrawer, closeDrawer] = useHomeStore((s) => [
+ s.allRecentsDrawerOpen,
+ s.openAllRecentsDrawer,
+ s.closeAllRecentsDrawer,
+ ]);
+
+ const displayItems = useMemo(() => recents.slice(0, recentPageSize), [recents, recentPageSize]);
+ const hasMore = recents.length > recentPageSize;
+
+ if (!isInit) {
+ return <SkeletonList rows={3} />;
+ }
+
+ return (
+ <Flexbox gap={2}>
+ {displayItems.map((item) => (
+ <Link
+ key={`${item.type}-${item.id}`}
+ style={{ color: 'inherit', textDecoration: 'none' }}
+ to={item.routePath}
+ >
+ <RecentListItem {...item} />
+ </Link>
+ ))}
+ {hasMore && (
+ <NavItem icon={MoreHorizontalIcon} title={t('input.more')} onClick={openDrawer} />
+ )}
+ <AllRecentsDrawer open={drawerOpen} onClose={closeDrawer} />
+ </Flexbox>
+ );
+});
+
+export default RecentsList;
diff --git a/src/routes/(main)/home/features/Recents/index.tsx b/src/routes/(main)/home/features/Recents/index.tsx
new file mode 100644
index 00000000000..03cfe4b1a53
--- /dev/null
+++ b/src/routes/(main)/home/features/Recents/index.tsx
@@ -0,0 +1,168 @@
+import { type MenuProps } from '@lobehub/ui';
+import {
+ AccordionItem,
+ ActionIcon,
+ ContextMenuTrigger,
+ DropdownMenu,
+ Flexbox,
+ Icon,
+ Text,
+} from '@lobehub/ui';
+import {
+ ArrowDownIcon,
+ ArrowUpIcon,
+ EyeOffIcon,
+ Hash,
+ LucideCheck,
+ MoreHorizontalIcon,
+ SlidersHorizontalIcon,
+} from 'lucide-react';
+import { memo, Suspense, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useInitRecents } from '@/hooks/useInitRecents';
+import { openCustomizeSidebarModal } from '@/routes/(main)/home/_layout/Body/CustomizeSidebarModal';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeRecentSelectors } from '@/store/home/selectors';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/slices/auth/selectors';
+
+import RecentsList from './List';
+
+interface RecentsProps {
+ itemKey: string;
+}
+
+const Recents = memo<RecentsProps>(({ itemKey }) => {
+ const { t } = useTranslation('common');
+ const recents = useHomeStore(homeRecentSelectors.recents);
+ const isInit = useHomeStore(homeRecentSelectors.isRecentsInit);
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const { isRevalidating } = useInitRecents();
+
+ const [recentPageSize, sidebarSectionOrder, hiddenSections, updateSystemStatus] = useGlobalStore(
+ (s) => [
+ systemStatusSelectors.recentPageSize(s),
+ systemStatusSelectors.sidebarSectionOrder(s),
+ systemStatusSelectors.hiddenSidebarSections(s),
+ s.updateSystemStatus,
+ ],
+ );
+
+ const visibleOrder = sidebarSectionOrder.filter((k) => !hiddenSections.includes(k));
+ const visibleIndex = visibleOrder.indexOf('recents');
+ const isFirst = visibleIndex === 0;
+ const isLast = visibleIndex === visibleOrder.length - 1;
+
+ const moveSection = useCallback(
+ (direction: 'up' | 'down') => {
+ const newOrder = [...sidebarSectionOrder];
+ const idx = newOrder.indexOf('recents');
+ const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
+ if (swapIdx < 0 || swapIdx >= newOrder.length) return;
+ [newOrder[idx], newOrder[swapIdx]] = [newOrder[swapIdx], newOrder[idx]];
+ updateSystemStatus({ sidebarSectionOrder: newOrder });
+ },
+ [sidebarSectionOrder, updateSystemStatus],
+ );
+
+ const hideSection = useCallback(() => {
+ updateSystemStatus({ hiddenSidebarSections: [...hiddenSections, 'recents'] });
+ }, [hiddenSections, updateSystemStatus]);
+
+ const dropdownMenu = useMemo(() => {
+ const pageSizeOptions = [5, 10, 15, 20];
+ const pageSizeItems = pageSizeOptions.map((size) => ({
+ icon: recentPageSize === size ? <Icon icon={LucideCheck} /> : <div />,
+ key: `pageSize-${size}`,
+ label: t('pageSizeItem', { count: size }),
+ onClick: () => {
+ updateSystemStatus({ recentPageSize: size });
+ },
+ }));
+
+ return [
+ {
+ children: pageSizeItems,
+ extra: recentPageSize,
+ icon: <Icon icon={Hash} />,
+ key: 'show',
+ label: t('navPanel.show'),
+ },
+ {
+ disabled: isFirst,
+ icon: <Icon icon={ArrowUpIcon} />,
+ key: 'moveUp',
+ label: t('navPanel.moveUp'),
+ onClick: () => moveSection('up'),
+ },
+ {
+ disabled: isLast,
+ icon: <Icon icon={ArrowDownIcon} />,
+ key: 'moveDown',
+ label: t('navPanel.moveDown'),
+ onClick: () => moveSection('down'),
+ },
+ {
+ disabled: false,
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'hideSection',
+ label: t('navPanel.hideSection'),
+ onClick: hideSection,
+ },
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={SlidersHorizontalIcon} />,
+ key: 'customizeSidebar',
+ label: t('navPanel.customizeSidebar'),
+ onClick: () => openCustomizeSidebarModal(),
+ },
+ ] as MenuProps['items'];
+ }, [
+ recentPageSize,
+ updateSystemStatus,
+ t,
+ isFirst,
+ isLast,
+ moveSection,
+ hideSection,
+ visibleOrder.length,
+ ]);
+
+ if (!isLogin) return null;
+ if (isInit && (!recents || recents.length === 0)) return null;
+
+ return (
+ <AccordionItem
+ itemKey={itemKey}
+ paddingBlock={4}
+ paddingInline={'8px 4px'}
+ action={
+ <DropdownMenu items={dropdownMenu} nativeButton={false}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} style={{ flex: 'none' }} />
+ </DropdownMenu>
+ }
+ headerWrapper={(header) => (
+ <ContextMenuTrigger items={dropdownMenu}>{header}</ContextMenuTrigger>
+ )}
+ title={
+ <Flexbox horizontal align="center" gap={4}>
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {t('recents')}
+ </Text>
+ {isRevalidating && <NeuralNetworkLoading size={14} />}
+ </Flexbox>
+ }
+ >
+ <Suspense fallback={<SkeletonList rows={3} />}>
+ <RecentsList />
+ </Suspense>
+ </AccordionItem>
+ );
+});
+
+export default Recents;
diff --git a/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx b/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
new file mode 100644
index 00000000000..e633ffb5f26
--- /dev/null
+++ b/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx
@@ -0,0 +1,112 @@
+import { type MenuProps } from '@lobehub/ui';
+import { Icon } from '@lobehub/ui';
+import { App } from 'antd';
+import { PencilLineIcon, Trash } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type RecentItem } from '@/server/routers/lambda/recent';
+import { documentService } from '@/services/document';
+import { taskService } from '@/services/task';
+import { topicService } from '@/services/topic';
+import { useChatStore } from '@/store/chat';
+import { useHomeStore } from '@/store/home';
+
+export const useRecentItemDropdownMenu = (
+ item: RecentItem,
+ toggleEditing: (visible?: boolean) => void,
+) => {
+ const { t } = useTranslation(['common', 'topic', 'components']);
+ const { modal } = App.useApp();
+ const removeTopic = useChatStore((s) => s.removeTopic);
+ const [updateRecentTitle, removeRecent, refreshRecents] = useHomeStore((s) => [
+ s.updateRecentTitle,
+ s.removeRecent,
+ s.refreshRecents,
+ ]);
+
+ const handleRename = useCallback(
+ async (newTitle: string) => {
+ // Optimistic update
+ updateRecentTitle(item.id, newTitle);
+
+ // Persist to server
+ switch (item.type) {
+ case 'document': {
+ await documentService.updateDocument({ id: item.id, title: newTitle });
+ break;
+ }
+ case 'task': {
+ await taskService.update(item.id, { name: newTitle });
+ break;
+ }
+ case 'topic': {
+ await topicService.updateTopic(item.id, { title: newTitle });
+ break;
+ }
+ }
+ },
+ [item, updateRecentTitle],
+ );
+
+ const handleDelete = useCallback(() => {
+ const confirmMessages: Record<string, string> = {
+ document: t('FileManager.actions.confirmDelete', { ns: 'components' }),
+ topic: t('actions.confirmRemoveTopic', { ns: 'topic' }),
+ };
+
+ modal.confirm({
+ centered: true,
+ okButtonProps: { danger: true },
+ onOk: async () => {
+ // Optimistic remove
+ removeRecent(item.id);
+
+ // Persist to server
+ switch (item.type) {
+ case 'topic': {
+ await removeTopic(item.id);
+ break;
+ }
+ case 'document': {
+ await documentService.deleteDocument(item.id);
+ break;
+ }
+ case 'task': {
+ await taskService.delete(item.id);
+ break;
+ }
+ }
+ // Refresh to get accurate data from server
+ await refreshRecents();
+ },
+ title: confirmMessages[item.type] || t('delete', { ns: 'common' }),
+ });
+ }, [item, modal, t, removeTopic, removeRecent, refreshRecents]);
+
+ const dropdownMenu = useCallback((): MenuProps['items'] => {
+ const canRename = true;
+
+ return [
+ ...(canRename
+ ? [
+ {
+ icon: <Icon icon={PencilLineIcon} />,
+ key: 'rename',
+ label: t('rename'),
+ onClick: () => toggleEditing(true),
+ },
+ ]
+ : []),
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete'),
+ onClick: handleDelete,
+ },
+ ];
+ }, [item.type, t, toggleEditing, handleDelete]);
+
+ return { dropdownMenu, handleRename };
+};
diff --git a/src/routes/(main)/home/features/index.tsx b/src/routes/(main)/home/features/index.tsx
index ce363990c24..83a690fd0a4 100644
--- a/src/routes/(main)/home/features/index.tsx
+++ b/src/routes/(main)/home/features/index.tsx
@@ -11,9 +11,6 @@ import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selec
import CommunityAgents from './CommunityAgents';
import InputArea from './InputArea';
-import RecentPage from './RecentPage';
-import RecentResource from './RecentResource';
-import RecentTopic from './RecentTopic';
import WelcomeText from './WelcomeText';
const Home = memo(() => {
@@ -34,14 +31,7 @@ const Home = memo(() => {
<InputArea />
{/* Use CSS visibility to hide instead of unmounting to prevent data re-fetching */}
<Flexbox gap={40} style={{ display: hideOtherModules ? 'none' : undefined }}>
- {isDevMode && isLogin && (
- <>
- <RecentTopic />
- <RecentPage />
- </>
- )}
{isDevMode && <CommunityAgents />}
- {isDevMode && isLogin && <RecentResource />}
</Flexbox>
</Flexbox>
);
diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.ts
index 3fa26d01bde..d1da6de1713 100644
--- a/src/server/routers/lambda/index.ts
+++ b/src/server/routers/lambda/index.ts
@@ -47,6 +47,7 @@ import { notificationRouter } from './notification';
import { oauthDeviceFlowRouter } from './oauthDeviceFlow';
import { pluginRouter } from './plugin';
import { ragEvalRouter } from './ragEval';
+import { recentRouter } from './recent';
import { searchRouter } from './search';
import { sessionRouter } from './session';
import { sessionGroupRouter } from './sessionGroup';
@@ -103,6 +104,7 @@ export const lambdaRouter = router({
oauthDeviceFlow: oauthDeviceFlowRouter,
plugin: pluginRouter,
ragEval: ragEvalRouter,
+ recent: recentRouter,
search: searchRouter,
session: sessionRouter,
sessionGroup: sessionGroupRouter,
diff --git a/src/server/routers/lambda/recent.ts b/src/server/routers/lambda/recent.ts
new file mode 100644
index 00000000000..1730c868a40
--- /dev/null
+++ b/src/server/routers/lambda/recent.ts
@@ -0,0 +1,74 @@
+import { z } from 'zod';
+
+import { RecentModel } from '@/database/models/recent';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import type { ChatTopicMetadata } from '@/types/topic';
+
+export interface RecentItem {
+ agentId?: string | null;
+ icon: string;
+ id: string;
+ metadata?: ChatTopicMetadata;
+ routePath: string;
+ title: string;
+ type: 'topic' | 'document' | 'task';
+ updatedAt: Date;
+}
+
+const recentProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: {
+ recentModel: new RecentModel(ctx.serverDB, ctx.userId),
+ },
+ });
+});
+
+export const recentRouter = router({
+ getAll: recentProcedure
+ .input(z.object({ limit: z.number().optional() }).optional())
+ .query(async ({ ctx, input }): Promise<RecentItem[]> => {
+ const limit = input?.limit ?? 10;
+
+ const items = await ctx.recentModel.queryRecent(limit);
+
+ return items.map((item) => {
+ let routePath: string;
+
+ switch (item.type) {
+ case 'topic': {
+ if (item.routeGroupId) {
+ routePath = `/group/${item.routeGroupId}?topic=${item.id}`;
+ } else if (item.routeId) {
+ routePath = `/agent/${item.routeId}?topic=${item.id}`;
+ } else {
+ routePath = '/';
+ }
+ break;
+ }
+ case 'document': {
+ routePath = `/page/${item.id}`;
+ break;
+ }
+ case 'task': {
+ routePath = item.routeId ? `/agent/${item.routeId}` : '/';
+ break;
+ }
+ }
+
+ return {
+ agentId: item.routeId,
+ icon: item.type,
+ id: item.id,
+ metadata: item.metadata as ChatTopicMetadata | undefined,
+ routePath,
+ title: item.title,
+ type: item.type,
+ updatedAt: item.updatedAt,
+ };
+ });
+ }),
+});
+
+export type RecentRouter = typeof recentRouter;
diff --git a/src/services/document/index.ts b/src/services/document/index.ts
index f82c3f379fc..11ef5b2f332 100644
--- a/src/services/document/index.ts
+++ b/src/services/document/index.ts
@@ -43,6 +43,26 @@ export class DocumentService {
return lambdaClient.document.queryDocuments.query(params);
}
+ /**
+ * Query page documents with standard filters for the page sidebar.
+ */
+ async getPageDocuments(pageSize: number = 20): Promise<DocumentItem[]> {
+ const result = await this.queryDocuments({
+ current: 0,
+ fileTypes: ['custom/document', 'application/pdf'],
+ pageSize,
+ sourceTypes: ['editor', 'file', 'api'],
+ });
+
+ return result.items
+ .filter(
+ (doc) =>
+ ['editor', 'file', 'api'].includes(doc.sourceType) &&
+ ['custom/document', 'application/pdf'].includes(doc.fileType),
+ )
+ .map((doc) => ({ ...doc, filename: doc.filename ?? doc.title ?? 'Untitled' }));
+ }
+
async getDocumentById(id: string, uniqueKey?: string): Promise<DocumentItem | undefined> {
if (uniqueKey) {
// Use fixed key so switching documents cancels the previous request
diff --git a/src/services/recent/index.ts b/src/services/recent/index.ts
new file mode 100644
index 00000000000..2ed6cc61242
--- /dev/null
+++ b/src/services/recent/index.ts
@@ -0,0 +1,10 @@
+import { lambdaClient } from '@/libs/trpc/client';
+import { type RecentItem } from '@/server/routers/lambda/recent';
+
+class RecentService {
+ getAll = (limit?: number): Promise<RecentItem[]> => {
+ return lambdaClient.recent.getAll.query({ limit });
+ };
+}
+
+export const recentService = new RecentService();
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index fa26ff83559..ad9e6666e9b 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -110,6 +110,10 @@ export interface SystemStatus {
* Group Agent Builder panel width
*/
groupAgentBuilderPanelWidth?: number;
+ /**
+ * Hidden sidebar sections
+ */
+ hiddenSidebarSections?: string[];
hidePWAInstaller?: boolean;
hideThreadLimitAlert?: boolean;
hideTopicSharePrivacyWarning?: boolean;
@@ -153,6 +157,10 @@ export interface SystemStatus {
pagePageSize?: number;
portalWidth: number;
readNotificationSlugs?: string[];
+ /**
+ * number of recent items to display
+ */
+ recentPageSize?: number;
/**
* Resource Manager column widths
*/
@@ -171,6 +179,10 @@ export interface SystemStatus {
showSystemRole?: boolean;
showVideoPanel?: boolean;
showVideoTopicPanel?: boolean;
+ /**
+ * Order of sidebar sections (e.g. ['recents', 'agent'])
+ */
+ sidebarSectionOrder?: string[];
systemRoleExpandedMap: Record<string, boolean>;
/**
* Whether to display tokens in short format
@@ -220,8 +232,9 @@ export interface GlobalState {
export const INITIAL_STATUS = {
agentBuilderPanelWidth: 360,
- agentPageSize: 10,
+ agentPageSize: 5,
chatInputHeight: 64,
+ recentPageSize: 5,
disabledModelProvidersSortType: 'default',
disabledModelsSortType: 'default',
expandInputActionbar: true,
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 7c6f56311bc..9c7c88327f9 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -12,10 +12,15 @@ const topicGroupKeys = (s: GlobalState): string[] | undefined => s.status.expand
const topicPageSize = (s: GlobalState): number => s.status.topicPageSize || 20;
-const agentPageSize = (s: GlobalState): number => s.status.agentPageSize || 10;
+const agentPageSize = (s: GlobalState): number => s.status.agentPageSize || 5;
+
+const recentPageSize = (s: GlobalState): number => s.status.recentPageSize || 5;
const pagePageSize = (s: GlobalState): number => s.status.pagePageSize || 20;
+const hiddenSidebarSections = (s: GlobalState): string[] => s.status.hiddenSidebarSections || [];
+const sidebarSectionOrder = (s: GlobalState): string[] =>
+ s.status.sidebarSectionOrder || ['recents', 'agent'];
const showSystemRole = (s: GlobalState) => s.status.showSystemRole;
const mobileShowTopic = (s: GlobalState) => s.status.mobileShowTopic;
const mobileShowPortal = (s: GlobalState) => s.status.mobileShowPortal;
@@ -84,6 +89,7 @@ export const systemStatusSelectors = {
filePanelWidth,
getAgentSystemRoleExpanded,
groupAgentBuilderPanelWidth,
+ hiddenSidebarSections,
hidePWAInstaller,
imagePanelWidth,
imageTopicViewMode,
@@ -101,6 +107,8 @@ export const systemStatusSelectors = {
pageAgentPanelWidth,
pagePageSize,
portalWidth,
+ recentPageSize,
+ sidebarSectionOrder,
sessionGroupKeys,
showChatHeader,
showFilePanel,
diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.ts
index 5ccf3d3f4d8..fdc5d07598d 100644
--- a/src/store/home/slices/recent/action.ts
+++ b/src/store/home/slices/recent/action.ts
@@ -1,8 +1,10 @@
import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
-import { useClientDataSWRWithSync } from '@/libs/swr';
+import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
+import { type RecentItem } from '@/server/routers/lambda/recent';
import { fileService } from '@/services/file';
+import { recentService } from '@/services/recent';
import { topicService } from '@/services/topic';
import { type HomeStore } from '@/store/home/store';
import { type StoreSetter } from '@/store/types';
@@ -15,6 +17,7 @@ const n = setNamespace('recent');
const FETCH_RECENT_TOPICS_KEY = 'fetchRecentTopics';
const FETCH_RECENT_RESOURCES_KEY = 'fetchRecentResources';
const FETCH_RECENT_PAGES_KEY = 'fetchRecentPages';
+const FETCH_RECENTS_KEY = 'fetchRecents';
type Setter = StoreSetter<HomeStore>;
export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
@@ -30,6 +33,45 @@ export class RecentActionImpl {
this.#get = get;
}
+ closeAllRecentsDrawer = (): void => {
+ this.#set({ allRecentsDrawerOpen: false }, false, n('closeAllRecentsDrawer'));
+ };
+
+ openAllRecentsDrawer = (): void => {
+ this.#set({ allRecentsDrawerOpen: true }, false, n('openAllRecentsDrawer'));
+ };
+
+ updateRecentTitle = (id: string, title: string): void => {
+ const recents = this.#get().recents.map((item) => (item.id === id ? { ...item, title } : item));
+ this.#set({ recents }, false, n('updateRecentTitle'));
+ };
+
+ removeRecent = (id: string): void => {
+ const recents = this.#get().recents.filter((item) => item.id !== id);
+ this.#set({ recents }, false, n('removeRecent'));
+ };
+
+ refreshRecents = async (): Promise<void> => {
+ await mutate((key: unknown) => Array.isArray(key) && key[0] === FETCH_RECENTS_KEY);
+ };
+
+ useFetchRecents = (
+ isLogin: boolean | undefined,
+ limit: number = 10,
+ ): SWRResponse<RecentItem[]> => {
+ return useClientDataSWRWithSync<RecentItem[]>(
+ isLogin === true ? [FETCH_RECENTS_KEY, isLogin, limit] : null,
+ async () => recentService.getAll(limit + 1),
+ {
+ onData: (data) => {
+ if (this.#get().isRecentsInit && isEqual(this.#get().recents, data)) return;
+
+ this.#set({ isRecentsInit: true, recents: data }, false, n('useFetchRecents/onData'));
+ },
+ },
+ );
+ };
+
useFetchRecentPages = (isLogin: boolean | undefined): SWRResponse<any[]> => {
return useClientDataSWRWithSync<any[]>(
// Only fetch when login status is explicitly true (not null/undefined)
diff --git a/src/store/home/slices/recent/initialState.ts b/src/store/home/slices/recent/initialState.ts
index d8a5917cd66..0cdf44ba5cf 100644
--- a/src/store/home/slices/recent/initialState.ts
+++ b/src/store/home/slices/recent/initialState.ts
@@ -1,20 +1,27 @@
+import { type RecentItem } from '@/server/routers/lambda/recent';
import { type FileListItem } from '@/types/files';
import { type RecentTopic } from '@/types/topic';
export interface RecentState {
+ allRecentsDrawerOpen: boolean;
isRecentPagesInit: boolean;
isRecentResourcesInit: boolean;
+ isRecentsInit: boolean;
isRecentTopicsInit: boolean;
recentPages: any[];
recentResources: FileListItem[];
+ recents: RecentItem[];
recentTopics: RecentTopic[];
}
export const initialRecentState: RecentState = {
+ allRecentsDrawerOpen: false,
isRecentPagesInit: false,
isRecentResourcesInit: false,
isRecentTopicsInit: false,
+ isRecentsInit: false,
recentPages: [],
recentResources: [],
recentTopics: [],
+ recents: [],
};
diff --git a/src/store/home/slices/recent/selectors.ts b/src/store/home/slices/recent/selectors.ts
index 94305a2a548..9a1b90f5e50 100644
--- a/src/store/home/slices/recent/selectors.ts
+++ b/src/store/home/slices/recent/selectors.ts
@@ -3,16 +3,20 @@ import { type HomeStore } from '@/store/home/store';
const recentTopics = (s: HomeStore) => s.recentTopics;
const recentResources = (s: HomeStore) => s.recentResources;
const recentPages = (s: HomeStore) => s.recentPages;
+const recents = (s: HomeStore) => s.recents;
const isRecentTopicsInit = (s: HomeStore) => s.isRecentTopicsInit;
const isRecentResourcesInit = (s: HomeStore) => s.isRecentResourcesInit;
const isRecentPagesInit = (s: HomeStore) => s.isRecentPagesInit;
+const isRecentsInit = (s: HomeStore) => s.isRecentsInit;
export const homeRecentSelectors = {
isRecentPagesInit,
isRecentResourcesInit,
isRecentTopicsInit,
+ isRecentsInit,
recentPages,
recentResources,
recentTopics,
+ recents,
};
diff --git a/src/store/page/slices/list/action.ts b/src/store/page/slices/list/action.ts
index d2f4eeb14ad..563eada7070 100644
--- a/src/store/page/slices/list/action.ts
+++ b/src/store/page/slices/list/action.ts
@@ -7,7 +7,6 @@ import { type StoreSetter } from '@/store/types';
import { type LobeDocument } from '@/types/document';
import { setNamespace } from '@/utils/storeDebug';
-import { type PageQueryFilter } from '../../initialState';
import { type PageStore } from '../../store';
const n = setNamespace('page/list');
@@ -41,23 +40,9 @@ export class ListActionImpl {
fetchDocuments = async (): Promise<void> => {
try {
const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
- const queryFilters: PageQueryFilter = {
- fileTypes: Array.from(ALLOWED_PAGE_FILE_TYPES),
- sourceTypes: Array.from(ALLOWED_PAGE_SOURCE_TYPES),
- };
-
- const result = await documentService.queryDocuments({
- current: 0,
- pageSize,
- ...queryFilters,
- });
-
- const documents = result.items.filter(isAllowedPage).map((doc) => ({
- ...doc,
- filename: doc.filename ?? doc.title ?? 'Untitled',
- })) as LobeDocument[];
- const hasMore = result.items.length >= pageSize;
+ const documents = (await documentService.getPageDocuments(pageSize)) as LobeDocument[];
+ const hasMore = documents.length >= pageSize;
// Use internal dispatch to set documents
this.#get().internal_dispatchDocuments({ documents, type: 'setDocuments' });
@@ -65,9 +50,12 @@ export class ListActionImpl {
this.#set(
{
currentPage: 0,
- documentsTotal: result.total,
+ documentsTotal: documents.length,
hasMoreDocuments: hasMore,
- queryFilter: queryFilters,
+ queryFilter: {
+ fileTypes: Array.from(ALLOWED_PAGE_FILE_TYPES),
+ sourceTypes: Array.from(ALLOWED_PAGE_SOURCE_TYPES),
+ },
},
false,
n('fetchDocuments/success'),
@@ -139,23 +127,7 @@ export class ListActionImpl {
['pageDocuments'],
async () => {
const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
- const queryFilters: PageQueryFilter = {
- fileTypes: Array.from(ALLOWED_PAGE_FILE_TYPES),
- sourceTypes: Array.from(ALLOWED_PAGE_SOURCE_TYPES),
- };
-
- const result = await documentService.queryDocuments({
- current: 0,
- pageSize,
- ...queryFilters,
- });
-
- const documents = result.items.filter(isAllowedPage).map((doc) => ({
- ...doc,
- filename: doc.filename ?? doc.title ?? 'Untitled',
- })) as LobeDocument[];
-
- return documents;
+ return (await documentService.getPageDocuments(pageSize)) as LobeDocument[];
},
{
onData: (documents) => {
diff --git a/src/utils/router.tsx b/src/utils/router.tsx
index b3e8b506f45..04b9f12e41c 100644
--- a/src/utils/router.tsx
+++ b/src/utils/router.tsx
@@ -193,3 +193,29 @@ export function createAppRouter(routes: RouteObject[], options?: CreateAppRouter
export function redirectElement(to: string): ReactElement {
return <Navigate replace to={to} />;
}
+
+/**
+ * Prefetch route layout chunks on hover to reduce navigation delay.
+ * Each import is only triggered once — subsequent calls are no-ops.
+ */
+const prefetchedRoutes = new Set<string>();
+
+const routePrefetchMap: Record<string, () => Promise<unknown>> = {
+ '/agent': () => import('@/routes/(main)/agent/_layout'),
+ '/community': () => import('@/routes/(main)/community/_layout'),
+ '/group': () => import('@/routes/(main)/group/_layout'),
+ '/page': () => import('@/routes/(main)/page/_layout'),
+ '/resource': () => import('@/routes/(main)/resource/_layout'),
+ '/settings': () => import('@/routes/(main)/settings/_layout'),
+};
+
+export function prefetchRoute(path: string): void {
+ // Match the first path segment, e.g. "/settings/provider" -> "/settings"
+ const key = '/' + path.replace(/^\//, '').split('/')[0];
+ if (prefetchedRoutes.has(key)) return;
+ const loader = routePrefetchMap[key];
+ if (loader) {
+ prefetchedRoutes.add(key);
+ loader();
+ }
+}