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.

♻️ refactor: refactor hooks

arvinxxe3fa62e73a04
diff --git a/src/hooks/useActiveTabKey.ts b/src/hooks/useActiveTabKey.ts
index 11917be041c..adce20ceda6 100644
--- a/src/hooks/useActiveTabKey.ts
+++ b/src/hooks/useActiveTabKey.ts
@@ -7,8 +7,7 @@ import { ProfileTabs, SettingsTabs, SidebarTabKey } from '@/store/global/initial
*/
export const useActiveTabKey = () => {
const pathname = usePathname();
-
- return pathname.split('/').find(Boolean)! as SidebarTabKey;
+ return (pathname.split('/').find(Boolean)! as SidebarTabKey) || SidebarTabKey.Home;
};
/**
diff --git a/src/hooks/useFetchAgentList.ts b/src/hooks/useFetchAgentList.ts
new file mode 100644
index 00000000000..be77d5a7e18
--- /dev/null
+++ b/src/hooks/useFetchAgentList.ts
@@ -0,0 +1,10 @@
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/slices/auth/selectors';
+
+export const useFetchAgentList = () => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const useFetchAgentList = useHomeStore((s) => s.useFetchAgentList);
+
+ useFetchAgentList(isLogin);
+};
diff --git a/src/hooks/useFetchGroups.ts b/src/hooks/useFetchGroups.ts
index 1d5eb8366d3..a55997fc0c1 100644
--- a/src/hooks/useFetchGroups.ts
+++ b/src/hooks/useFetchGroups.ts
@@ -1,10 +1,10 @@
-import { useChatGroupStore } from '@/store/chatGroup';
+import { useAgentGroupStore } from '@/store/agentGroup';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/slices/auth/selectors';
export const useFetchGroups = () => {
const isLogin = useUserStore(authSelectors.isLogin);
- const useFetchGroups = useChatGroupStore((s) => s.useFetchGroups);
+ const useFetchGroups = useAgentGroupStore((s) => s.useFetchGroups);
useFetchGroups(true, isLogin ?? false);
};
diff --git a/src/hooks/useFetchMessages.ts b/src/hooks/useFetchMessages.ts
deleted file mode 100644
index 5a834702a44..00000000000
--- a/src/hooks/useFetchMessages.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { useEffect } from 'react';
-
-import { useChatStore } from '@/store/chat';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-
-export const useFetchMessages = () => {
- const sessionId = useSessionStore((s) => s.activeId);
- const [activeTopicId, useFetchMessages, internal_updateActiveSessionType] = useChatStore((s) => [
- s.activeTopicId,
- s.useFetchMessages,
- s.internal_updateActiveSessionType,
- ]);
-
- const [currentSession, isGroupSession] = useSessionStore((s) => [
- sessionSelectors.currentSession(s),
- sessionSelectors.isCurrentSessionGroupSession(s),
- ]);
-
- // Update active session type when session changes
- useEffect(() => {
- if (currentSession?.type) {
- internal_updateActiveSessionType(currentSession.type as 'agent' | 'group');
- } else {
- internal_updateActiveSessionType(undefined);
- }
- }, [currentSession?.id, currentSession?.type, internal_updateActiveSessionType]);
-
- useFetchMessages(true, sessionId, activeTopicId, isGroupSession ? 'group' : 'session');
-};
diff --git a/src/hooks/useFetchTopics.test.ts b/src/hooks/useFetchTopics.test.ts
new file mode 100644
index 00000000000..e6d196d7e26
--- /dev/null
+++ b/src/hooks/useFetchTopics.test.ts
@@ -0,0 +1,158 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useFetchTopics } from './useFetchTopics';
+
+// Mock store dependencies
+const mockUseGlobalStore = vi.hoisted(() => vi.fn());
+const mockUseChatStore = vi.hoisted(() => vi.fn());
+const mockUseAgentStore = vi.hoisted(() => vi.fn());
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: mockUseChatStore,
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: mockUseGlobalStore,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: mockUseAgentStore,
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ builtinAgentSelectors: {
+ isInboxAgent: vi.fn((s) => s.isInboxAgent),
+ },
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: {
+ topicPageSize: vi.fn((s) => s.topicPageSize),
+ },
+}));
+
+describe('useFetchTopics', () => {
+ const mockUseFetchTopicsFn = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockUseGlobalStore.mockImplementation((selector) => selector({ topicPageSize: 20 }));
+ // Default: not inbox agent
+ mockUseAgentStore.mockImplementation((selector) => selector({ isInboxAgent: false }));
+ });
+
+ it('should fetch topics with agentId when no groupId is active', () => {
+ const activeAgentId = 'agent-123';
+
+ mockUseChatStore.mockImplementation((selector) =>
+ selector({
+ activeAgentId,
+ activeGroupId: undefined,
+ useFetchTopics: mockUseFetchTopicsFn,
+ }),
+ );
+
+ renderHook(() => useFetchTopics());
+
+ expect(mockUseFetchTopicsFn).toHaveBeenCalledWith(true, {
+ agentId: activeAgentId,
+ groupId: undefined,
+ isInbox: false,
+ pageSize: 20,
+ });
+ });
+
+ it('should fetch topics with groupId when group session is active', () => {
+ const activeAgentId = 'agent-123';
+ const activeGroupId = 'group-456';
+
+ mockUseChatStore.mockImplementation((selector) =>
+ selector({
+ activeAgentId,
+ activeGroupId,
+ useFetchTopics: mockUseFetchTopicsFn,
+ }),
+ );
+
+ renderHook(() => useFetchTopics());
+
+ expect(mockUseFetchTopicsFn).toHaveBeenCalledWith(true, {
+ agentId: activeAgentId,
+ groupId: activeGroupId,
+ isInbox: false,
+ pageSize: 20,
+ });
+ });
+
+ it('should set isInbox to false when groupId is present even if agentId is inbox', () => {
+ const activeGroupId = 'group-789';
+
+ // Even if isInboxAgent is true, groupId takes precedence
+ mockUseAgentStore.mockImplementation((selector) => selector({ isInboxAgent: true }));
+
+ mockUseChatStore.mockImplementation((selector) =>
+ selector({
+ activeAgentId: INBOX_SESSION_ID,
+ activeGroupId,
+ useFetchTopics: mockUseFetchTopicsFn,
+ }),
+ );
+
+ renderHook(() => useFetchTopics());
+
+ expect(mockUseFetchTopicsFn).toHaveBeenCalledWith(true, {
+ agentId: INBOX_SESSION_ID,
+ groupId: activeGroupId,
+ isInbox: false,
+ pageSize: 20,
+ });
+ });
+
+ it('should pass isInbox true when agentId is inbox and no groupId', () => {
+ // Set isInboxAgent to true for this test
+ mockUseAgentStore.mockImplementation((selector) => selector({ isInboxAgent: true }));
+
+ mockUseChatStore.mockImplementation((selector) =>
+ selector({
+ activeAgentId: INBOX_SESSION_ID,
+ activeGroupId: undefined,
+ useFetchTopics: mockUseFetchTopicsFn,
+ }),
+ );
+
+ renderHook(() => useFetchTopics());
+
+ expect(mockUseFetchTopicsFn).toHaveBeenCalledWith(true, {
+ agentId: INBOX_SESSION_ID,
+ groupId: undefined,
+ isInbox: true,
+ pageSize: 20,
+ });
+ });
+
+ it('should use topicPageSize from global store', () => {
+ const customPageSize = 50;
+
+ mockUseChatStore.mockImplementation((selector) =>
+ selector({
+ activeAgentId: 'agent-1',
+ activeGroupId: undefined,
+ useFetchTopics: mockUseFetchTopicsFn,
+ }),
+ );
+ mockUseGlobalStore.mockImplementation((selector) =>
+ selector({ topicPageSize: customPageSize }),
+ );
+
+ renderHook(() => useFetchTopics());
+
+ expect(mockUseFetchTopicsFn).toHaveBeenCalledWith(true, {
+ agentId: 'agent-1',
+ groupId: undefined,
+ isInbox: false,
+ pageSize: customPageSize,
+ });
+ });
+});
diff --git a/src/hooks/useFetchTopics.ts b/src/hooks/useFetchTopics.ts
index 4d63e0c549c..a1684229b22 100644
--- a/src/hooks/useFetchTopics.ts
+++ b/src/hooks/useFetchTopics.ts
@@ -1,12 +1,27 @@
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { useSessionStore } from '@/store/session';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
/**
- * Fetch topics for the current session
+ * Fetch topics for the current session (agent or group)
*/
export const useFetchTopics = () => {
- const [sessionId] = useSessionStore((s) => [s.activeId]);
- const useFetchTopics = useChatStore((s) => s.useFetchTopics);
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const [activeAgentId, activeGroupId, useFetchTopics] = useChatStore((s) => [
+ s.activeAgentId,
+ s.activeGroupId,
+ s.useFetchTopics,
+ ]);
- useFetchTopics(true, sessionId);
+ const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+
+ // If in group session, use groupId; otherwise use agentId
+ useFetchTopics(true, {
+ agentId: activeAgentId,
+ groupId: activeGroupId,
+ isInbox: activeGroupId ? false : isInbox,
+ pageSize: topicPageSize,
+ });
};
diff --git a/src/hooks/useHotkeys/chatScope.ts b/src/hooks/useHotkeys/chatScope.ts
index fd553ee7196..f7ead0c15db 100644
--- a/src/hooks/useHotkeys/chatScope.ts
+++ b/src/hooks/useHotkeys/chatScope.ts
@@ -1,18 +1,13 @@
-import isEqual from 'fast-deep-equal';
import { useEffect } from 'react';
import { useHotkeysContext } from 'react-hotkeys-hook';
-import { useSend } from '@/app/[variants]/(main)/chat/components/conversation/features/ChatInput/useSend';
import { useClearCurrentMessages } from '@/features/ChatInput/ActionBar/Clear';
import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';
import { useActionSWR } from '@/libs/swr';
import { useChatStore } from '@/store/chat';
-import { displayMessageSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
import { HotkeyEnum, HotkeyScopeEnum } from '@/types/hotkey';
-import { usePinnedAgentState } from '../usePinnedAgentState';
import { useHotkeyById } from './useHotkeyById';
export const useSaveTopicHotkey = () => {
@@ -31,98 +26,15 @@ export const useOpenChatSettingsHotkey = () => {
return useHotkeyById(HotkeyEnum.OpenChatSettings, openChatSettings);
};
-export const useRegenerateMessageHotkey = () => {
- const [regenerateUserMessage, regenerateAssistantMessage] = useChatStore((s) => [
- s.regenerateUserMessage,
- s.regenerateAssistantMessage,
- ]);
- const lastMessage = useChatStore((s) => displayMessageSelectors.mainAIChats(s).at(-1), isEqual);
+// Note: useRegenerateMessageHotkey has been moved to ConversationStore
+// Note: useDeleteAndRegenerateMessageHotkey has been moved to ConversationStore
+// Note: useDeleteLastMessageHotkey has been moved to ConversationStore
- const disable = !lastMessage;
-
- return useHotkeyById(
- HotkeyEnum.RegenerateMessage,
- () => {
- if (!lastMessage) return;
- if (lastMessage.role === 'user') return regenerateUserMessage(lastMessage.id);
-
- return regenerateAssistantMessage(lastMessage.id);
- },
- {
- enableOnContentEditable: true,
- enabled: !disable,
- },
- );
-};
-
-export const useDeleteAndRegenerateMessageHotkey = () => {
- const delAndRegenerateMessage = useChatStore((s) => s.delAndRegenerateMessage);
- const lastMessage = useChatStore((s) => displayMessageSelectors.mainAIChats(s).at(-1), isEqual);
-
- const disable = !lastMessage || lastMessage.id === 'default' || lastMessage.role === 'system';
-
- return useHotkeyById(
- HotkeyEnum.DeleteAndRegenerateMessage,
- () => !disable && delAndRegenerateMessage(lastMessage.id),
- {
- enableOnContentEditable: true,
- enabled: !disable,
- },
- );
-};
-
-export const useDeleteLastMessageHotkey = () => {
- const deleteMessage = useChatStore((s) => s.deleteMessage);
- const lastMessage = useChatStore((s) => displayMessageSelectors.mainAIChats(s).at(-1), isEqual);
-
- const disable = !lastMessage || lastMessage.id === 'default' || lastMessage.role === 'system';
-
- return useHotkeyById(
- HotkeyEnum.DeleteLastMessage,
- () => !disable && deleteMessage(lastMessage.id),
- {
- enableOnContentEditable: true,
- enabled: !disable,
- },
- );
-};
-
-export const useToggleLeftPanelHotkey = () => {
- const isZenMode = useGlobalStore((s) => s.status.zenMode);
- const [isPinned] = usePinnedAgentState();
- const showSessionPanel = useGlobalStore(systemStatusSelectors.showSessionPanel);
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
-
- return useHotkeyById(
- HotkeyEnum.ToggleLeftPanel,
- () =>
- updateSystemStatus({
- sessionsWidth: showSessionPanel ? 0 : 320,
- showSessionPanel: !showSessionPanel,
- }),
- {
- enableOnContentEditable: true,
- enabled: !isZenMode && !isPinned,
- },
- );
-};
-
-export const useToggleRightPanelHotkey = () => {
- const isZenMode = useGlobalStore((s) => s.status.zenMode);
- const toggleConfig = useGlobalStore((s) => s.toggleChatSideBar);
-
- return useHotkeyById(HotkeyEnum.ToggleRightPanel, () => toggleConfig(), {
- enableOnContentEditable: true,
- enabled: !isZenMode,
- });
-};
-
-export const useAddUserMessageHotkey = () => {
- const { send } = useSend();
+export const useAddUserMessageHotkey = (send: () => void) => {
return useHotkeyById(
HotkeyEnum.AddUserMessage,
() => {
- send({ onlyAddUserMessage: true });
+ send();
},
{
enableOnContentEditable: true,
@@ -146,16 +58,11 @@ export const useRegisterChatHotkeys = () => {
useOpenChatSettingsHotkey();
// Layout
- useToggleLeftPanelHotkey();
- useToggleRightPanelHotkey();
useToggleZenModeHotkey();
// Conversation
- useRegenerateMessageHotkey();
- useDeleteAndRegenerateMessageHotkey();
- useDeleteLastMessageHotkey();
+ // Note: Regenerate and delete hotkeys have been moved to ConversationStore
useSaveTopicHotkey();
- useAddUserMessageHotkey();
useClearCurrentMessagesHotkey();
useEffect(() => {
diff --git a/src/hooks/useHotkeys/filesScope.ts b/src/hooks/useHotkeys/filesScope.ts
index a714bb6ed46..dd75c4af75f 100644
--- a/src/hooks/useHotkeys/filesScope.ts
+++ b/src/hooks/useHotkeys/filesScope.ts
@@ -1,35 +1,36 @@
+import { HotkeyEnum, HotkeyScopeEnum } from '@lobechat/types';
import { useEffect } from 'react';
import { useHotkeysContext } from 'react-hotkeys-hook';
-import { FOLDER_WIDTH } from '@/const/layoutTokens';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { HotkeyEnum, HotkeyScopeEnum } from '@/types/hotkey';
-
import { useHotkeyById } from './useHotkeyById';
-export const useToggleFilesLeftPanelHotkey = () => {
- const showFilePanel = useGlobalStore(systemStatusSelectors.showFilePanel);
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
-
- return useHotkeyById(HotkeyEnum.ToggleLeftPanel, () =>
- updateSystemStatus({
- filePanelWidth: showFilePanel ? 0 : FOLDER_WIDTH,
- showFilePanel: !showFilePanel,
- }),
+/**
+ * Save document hotkey (Cmd+S / Ctrl+S)
+ * @param flushSave - Function to flush pending saves
+ */
+export const useSaveDocumentHotkey = (flushSave: () => void) => {
+ return useHotkeyById(
+ HotkeyEnum.SaveDocument,
+ () => {
+ flushSave();
+ },
+ {
+ enableOnContentEditable: true,
+ },
);
};
-// 注册聚合
-
+/**
+ * Register Files scope and enable it
+ * Use this in components that need Files scope hotkeys
+ */
export const useRegisterFilesHotkeys = () => {
const { enableScope, disableScope } = useHotkeysContext();
- // Layout
- useToggleFilesLeftPanelHotkey();
-
useEffect(() => {
enableScope(HotkeyScopeEnum.Files);
return () => disableScope(HotkeyScopeEnum.Files);
- }, []);
+ }, [enableScope, disableScope]);
+
+ return null;
};
diff --git a/src/hooks/useHotkeys/globalScope.ts b/src/hooks/useHotkeys/globalScope.ts
index 1ab042c90f9..4c346af4dd7 100644
--- a/src/hooks/useHotkeys/globalScope.ts
+++ b/src/hooks/useHotkeys/globalScope.ts
@@ -1,61 +1,19 @@
-import isEqual from 'fast-deep-equal';
-import { useHotkeys } from 'react-hotkeys-hook';
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { HotkeyEnum } from '@lobechat/types';
-import { INBOX_SESSION_ID } from '@/const/session';
+import { useNavigateToAgent } from '@/hooks/useNavigateToAgent';
import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
-import { useSwitchSession } from '@/hooks/useSwitchSession';
import { useGlobalStore } from '@/store/global';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
-import { HotkeyEnum, HotkeyScopeEnum, KeyEnum } from '@/types/hotkey';
import { useHotkeyById } from './useHotkeyById';
-export const useSwitchAgentHotkey = () => {
- const { showPinList } = useServerConfigStore(featureFlagsSelectors);
- const list = useSessionStore(sessionSelectors.pinnedSessions, isEqual);
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.SwitchAgent));
- const switchSession = useSwitchSession();
- const [, { pinAgent }] = usePinnedAgentState();
-
- const switchAgent = (id: string) => {
- switchSession(id);
- pinAgent();
- };
-
- const ref = useHotkeys(
- list.slice(0, 9).map((e, i) => hotkey.replaceAll(KeyEnum.Number, String(i + 1))),
- (_, hotkeysEvent) => {
- if (!hotkeysEvent.keys?.[0]) return;
- const index = parseInt(hotkeysEvent.keys?.[0]) - 1;
- const item = list[index];
- if (!item) return;
- switchAgent(item.id);
- },
- {
- enableOnFormTags: true,
- enabled: showPinList,
- preventDefault: true,
- scopes: [HotkeyScopeEnum.Global, HotkeyEnum.SwitchAgent],
- },
- );
-
- return {
- id: HotkeyEnum.SwitchAgent,
- ref,
- };
-};
-
// 切换到会话标签(并聚焦到随便聊聊)
export const useNavigateToChatHotkey = () => {
- const switchSession = useSwitchSession();
+ const navigateToAgent = useNavigateToAgent();
const [, { unpinAgent }] = usePinnedAgentState();
return useHotkeyById(HotkeyEnum.NavigateToChat, () => {
- switchSession(INBOX_SESSION_ID);
+ navigateToAgent(INBOX_SESSION_ID);
unpinAgent();
});
};
@@ -71,11 +29,39 @@ export const useOpenHotkeyHelperHotkey = () => {
);
};
-// 注册聚合
+export const useToggleLeftPanelHotkey = () => {
+ const isZenMode = useGlobalStore((s) => s.status.zenMode);
+ const toggleLeftPanel = useGlobalStore((s) => s.toggleLeftPanel);
+ return useHotkeyById(HotkeyEnum.ToggleLeftPanel, () => toggleLeftPanel(), {
+ enableOnContentEditable: true,
+ enabled: !isZenMode,
+ });
+};
+
+export const useToggleRightPanelHotkey = () => {
+ const isZenMode = useGlobalStore((s) => s.status.zenMode);
+ const toggleConfig = useGlobalStore((s) => s.toggleRightPanel);
+
+ return useHotkeyById(HotkeyEnum.ToggleRightPanel, () => toggleConfig(), {
+ enableOnContentEditable: true,
+ enabled: !isZenMode,
+ });
+};
+
+// CMDK
+export const useCommandPaletteHotkey = () => {
+ const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
+
+ return useHotkeyById(HotkeyEnum.CommandPalette, () => toggleCommandMenu(), {
+ enableOnContentEditable: true,
+ });
+};
export const useRegisterGlobalHotkeys = () => {
// 全局自动注册不需要 enableScope
- useSwitchAgentHotkey();
+ useToggleLeftPanelHotkey();
+ useToggleRightPanelHotkey();
useNavigateToChatHotkey();
useOpenHotkeyHelperHotkey();
+ useCommandPaletteHotkey();
};
diff --git a/src/hooks/useHotkeys/imageScope.ts b/src/hooks/useHotkeys/imageScope.ts
index e80e05fbeaf..44962cc295b 100644
--- a/src/hooks/useHotkeys/imageScope.ts
+++ b/src/hooks/useHotkeys/imageScope.ts
@@ -1,25 +1,12 @@
import { useEffect } from 'react';
import { useHotkeysContext } from 'react-hotkeys-hook';
-import { FOLDER_WIDTH } from '@/const/layoutTokens';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { HotkeyEnum, HotkeyScopeEnum } from '@/types/hotkey';
import { useHotkeyById } from './useHotkeyById';
-export const useToggleImageLeftPanelHotkey = () => {
- const showImagePanel = useGlobalStore(systemStatusSelectors.showImagePanel);
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
-
- return useHotkeyById(HotkeyEnum.ToggleLeftPanel, () =>
- updateSystemStatus({
- imagePanelWidth: showImagePanel ? 0 : FOLDER_WIDTH,
- showImagePanel: !showImagePanel,
- }),
- );
-};
-
export const useToggleImageRightPanelHotkey = () => {
const showImageTopicPanel = useGlobalStore(systemStatusSelectors.showImageTopicPanel);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
@@ -38,7 +25,6 @@ export const useRegisterImageHotkeys = () => {
const { enableScope, disableScope } = useHotkeysContext();
// Layout
- useToggleImageLeftPanelHotkey();
useToggleImageRightPanelHotkey();
useEffect(() => {
diff --git a/src/hooks/useHotkeys/useHotkeyById.test.ts b/src/hooks/useHotkeys/useHotkeyById.test.ts
index df203567da5..b8f6cfbd565 100644
--- a/src/hooks/useHotkeys/useHotkeyById.test.ts
+++ b/src/hooks/useHotkeys/useHotkeyById.test.ts
@@ -1,5 +1,5 @@
import { renderHook } from '@testing-library/react';
-import { uniq } from 'lodash-es';
+import { uniq } from 'es-toolkit/compat';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { HOTKEYS_REGISTRATION } from '@/const/hotkeys';
@@ -8,7 +8,7 @@ import { HotkeyEnum, HotkeyScopeEnum } from '@/types/hotkey';
import { useHotkeyById } from './useHotkeyById';
// Mock dependencies
-vi.mock('lodash-es', async (importOriginal) => {
+vi.mock('es-toolkit/compat', async (importOriginal) => {
const actual: any = await importOriginal();
return {
...actual,
diff --git a/src/hooks/useHotkeys/useHotkeyById.ts b/src/hooks/useHotkeys/useHotkeyById.ts
index 878017c4940..85a735d9ee7 100644
--- a/src/hooks/useHotkeys/useHotkeyById.ts
+++ b/src/hooks/useHotkeys/useHotkeyById.ts
@@ -1,4 +1,4 @@
-import { uniq } from 'lodash-es';
+import { uniq } from 'es-toolkit/compat';
import { DependencyList } from 'react';
import { type HotkeyCallback, type Options, useHotkeys } from 'react-hotkeys-hook';
diff --git a/src/hooks/useImgToClipboard.ts b/src/hooks/useImgToClipboard.ts
index ea3004980f2..a91e5ec162c 100644
--- a/src/hooks/useImgToClipboard.ts
+++ b/src/hooks/useImgToClipboard.ts
@@ -18,7 +18,7 @@ export const useImgToClipboard = ({
const blob = await fetch(dataUrl).then((res) => res.blob());
navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })]);
setLoading(false);
- message.success(t('copySuccess', { defaultValue: 'Copy Success', ns: 'common' }));
+ message.success(t('copySuccess', { ns: 'common' }));
} catch (error) {
console.error('Failed to copy image', error);
setLoading(false);
diff --git a/src/hooks/useInitAgentConfig.ts b/src/hooks/useInitAgentConfig.ts
index 85b8f6fbd43..a04185d0d14 100644
--- a/src/hooks/useInitAgentConfig.ts
+++ b/src/hooks/useInitAgentConfig.ts
@@ -1,32 +1,24 @@
+import { useParams } from 'react-router-dom';
+
import { useAgentStore } from '@/store/agent';
-import { useSessionStore } from '@/store/session';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
-import { LobeSessionType } from '@/types/session';
/**
* If a targetAgentId is provided, use it to fetch the agent config directly.
* Otherwise, use the active session id to fetch the config.
*/
-export const useInitAgentConfig = (targetAgentId?: string) => {
- const [useFetchAgentConfig] = useAgentStore((s) => [s.useFetchAgentConfig]);
+export const useInitAgentConfig = () => {
+ const [useFetchAgentConfig, activeAgentId] = useAgentStore((s) => [
+ s.useFetchAgentConfig,
+ s.activeAgentId,
+ ]);
const isLogin = useUserStore(authSelectors.isLogin);
- // If targetAgentId is provided, find the corresponding session ID
- // Otherwise, use the active session ID
- const sessionId = useSessionStore((s) => {
- if (targetAgentId) {
- // Find the session that has this agent
- const agentSession = s.sessions?.find(
- (session) => session.type === LobeSessionType.Agent && session.config?.id === targetAgentId,
- );
- return agentSession?.id || s.activeId;
- }
- return s.activeId;
- });
+ const params = useParams<{ aid?: string }>();
- const data = useFetchAgentConfig(isLogin, sessionId);
+ const data = useFetchAgentConfig(isLogin, activeAgentId ?? params.aid ?? '');
return { ...data, isLoading: data.isLoading && isLogin };
};
diff --git a/src/hooks/useInitBuiltinAgent.ts b/src/hooks/useInitBuiltinAgent.ts
new file mode 100644
index 00000000000..a17de6969d0
--- /dev/null
+++ b/src/hooks/useInitBuiltinAgent.ts
@@ -0,0 +1,17 @@
+import { BuiltinAgentSlug } from '@lobechat/builtin-agents';
+
+import { useAgentStore } from '@/store/agent';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+/**
+ * If a targetAgentId is provided, use it to fetch the agent config directly.
+ * Otherwise, use the active session id to fetch the config.
+ */
+export const useInitBuiltinAgent = (slug: BuiltinAgentSlug) => {
+ const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
+
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ useInitBuiltinAgent(slug, { isLogin });
+};
diff --git a/src/hooks/useInitGroupConfig.ts b/src/hooks/useInitGroupConfig.ts
index 0869b228f11..6c218412794 100644
--- a/src/hooks/useInitGroupConfig.ts
+++ b/src/hooks/useInitGroupConfig.ts
@@ -1,18 +1,18 @@
-import { useChatGroupStore } from '@/store/chatGroup';
-import { useSessionStore } from '@/store/session';
+import { useAgentGroupStore } from '@/store/agentGroup';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
export const useInitGroupConfig = () => {
- const [useFetchGroupDetail] = useChatGroupStore((s) => [s.useFetchGroupDetail]);
+ const [useFetchGroupDetail, activeGroupId] = useAgentGroupStore((s) => [
+ s.useFetchGroupDetail,
+ s.activeGroupId,
+ ]);
const isLogin = useUserStore(authSelectors.isLogin);
- const [sessionId] = useSessionStore((s) => [s.activeId]);
-
- // Only fetch group detail if we have a valid session ID and user is logged in
- const shouldFetch = Boolean(isLogin && sessionId && sessionId !== 'inbox');
- const data = useFetchGroupDetail(shouldFetch, sessionId || '');
+ // Only fetch group detail if we have a valid group ID and user is logged in
+ const shouldFetch = Boolean(isLogin && activeGroupId);
+ const data = useFetchGroupDetail(shouldFetch, activeGroupId || '');
return {
...data,
diff --git a/src/hooks/useInitRecentPage.ts b/src/hooks/useInitRecentPage.ts
new file mode 100644
index 00000000000..7d317237d45
--- /dev/null
+++ b/src/hooks/useInitRecentPage.ts
@@ -0,0 +1,24 @@
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+/**
+ * Hook to initialize and fetch recent pages (documents)
+ * Only fetches when user is logged in
+ *
+ * Usage:
+ * const { isLoading } = useInitRecentPage();
+ *
+ * Then access data directly from store:
+ * const recentPages = useHomeStore(homeRecentSelectors.recentPages);
+ * const isInit = useHomeStore(homeRecentSelectors.isRecentPagesInit);
+ */
+export const useInitRecentPage = () => {
+ const useFetchRecentPages = useHomeStore((s) => s.useFetchRecentPages);
+
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ const data = useFetchRecentPages(isLogin);
+
+ return { ...data, isLoading: data.isLoading && isLogin };
+};
diff --git a/src/hooks/useInitRecentResource.ts b/src/hooks/useInitRecentResource.ts
new file mode 100644
index 00000000000..59325e63309
--- /dev/null
+++ b/src/hooks/useInitRecentResource.ts
@@ -0,0 +1,24 @@
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+/**
+ * Hook to initialize and fetch recent resources (files)
+ * Only fetches when user is logged in
+ *
+ * Usage:
+ * const { isLoading } = useInitRecentResource();
+ *
+ * Then access data directly from store:
+ * const recentResources = useHomeStore(homeRecentSelectors.recentResources);
+ * const isInit = useHomeStore(homeRecentSelectors.isRecentResourcesInit);
+ */
+export const useInitRecentResource = () => {
+ const useFetchRecentResources = useHomeStore((s) => s.useFetchRecentResources);
+
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ const data = useFetchRecentResources(isLogin);
+
+ return { ...data, isLoading: data.isLoading && isLogin };
+};
diff --git a/src/hooks/useInitRecentTopic.ts b/src/hooks/useInitRecentTopic.ts
new file mode 100644
index 00000000000..2bc27dd9b3d
--- /dev/null
+++ b/src/hooks/useInitRecentTopic.ts
@@ -0,0 +1,24 @@
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+/**
+ * Hook to initialize and fetch recent topics
+ * Only fetches when user is logged in
+ *
+ * Usage:
+ * const { isLoading } = useInitRecentTopic();
+ *
+ * Then access data directly from store:
+ * const recentTopics = useHomeStore(homeRecentSelectors.recentTopics);
+ * const isInit = useHomeStore(homeRecentSelectors.isRecentTopicsInit);
+ */
+export const useInitRecentTopic = () => {
+ const useFetchRecentTopics = useHomeStore((s) => s.useFetchRecentTopics);
+
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ const data = useFetchRecentTopics(isLogin);
+
+ return { ...data, isLoading: data.isLoading && isLogin };
+};
diff --git a/src/hooks/useInterceptingRoutes.test.ts b/src/hooks/useInterceptingRoutes.test.ts
index 4bcbfb2c7c8..2c973ef40a3 100644
--- a/src/hooks/useInterceptingRoutes.test.ts
+++ b/src/hooks/useInterceptingRoutes.test.ts
@@ -1,11 +1,9 @@
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { INBOX_SESSION_ID } from '@/const/session';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useAgentStore } from '@/store/agent';
-import { ChatSettingsTabs, SettingsTabs } from '@/store/global/initialState';
-import { useSessionStore } from '@/store/session';
+import { ChatSettingsTabs } from '@/store/global/initialState';
import { useOpenChatSettings } from './useInterceptingRoutes';
@@ -19,9 +17,6 @@ vi.mock('react-router-dom', () => ({
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: vi.fn(),
}));
-vi.mock('@/store/session', () => ({
- useSessionStore: vi.fn(),
-}));
vi.mock('@/store/global', () => ({
useGlobalStore: {
setState: vi.fn(),
@@ -30,11 +25,11 @@ vi.mock('@/store/global', () => ({
describe('useOpenChatSettings', () => {
beforeEach(() => {
vi.clearAllMocks();
- useAgentStore.setState({ showAgentSetting: false });
+ useAgentStore.setState({ showAgentSetting: false, activeAgentId: undefined });
});
it('navigates to mobile chat settings with session info', () => {
- vi.mocked(useSessionStore).mockReturnValue('123');
+ useAgentStore.setState({ activeAgentId: '123' });
vi.mocked(useIsMobile).mockReturnValue(true);
const { result } = renderHook(() => useOpenChatSettings(ChatSettingsTabs.Meta));
@@ -48,7 +43,7 @@ describe('useOpenChatSettings', () => {
});
it('opens desktop agent settings overlay when not on mobile', () => {
- vi.mocked(useSessionStore).mockReturnValue('456');
+ useAgentStore.setState({ activeAgentId: '456' });
vi.mocked(useIsMobile).mockReturnValue(false);
const { result } = renderHook(() => useOpenChatSettings(ChatSettingsTabs.Meta));
diff --git a/src/hooks/useInterceptingRoutes.ts b/src/hooks/useInterceptingRoutes.ts
index 026d3a666f4..fb5fd9bba1d 100644
--- a/src/hooks/useInterceptingRoutes.ts
+++ b/src/hooks/useInterceptingRoutes.ts
@@ -4,20 +4,20 @@ import { useLocation, useNavigate } from 'react-router-dom';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useAgentStore } from '@/store/agent';
import { ChatSettingsTabs } from '@/store/global/initialState';
-import { useSessionStore } from '@/store/session';
export const useOpenChatSettings = (tab: ChatSettingsTabs = ChatSettingsTabs.Meta) => {
- const activeId = useSessionStore((s) => s.activeId);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
const isMobile = useIsMobile();
const navigate = useNavigate();
const location = useLocation();
return useMemo(() => {
- if (isMobile) return () => navigate(`/chat/settings?session=${activeId}&showMobileWorkspace=true`);
+ if (isMobile)
+ return () => navigate(`/chat/settings?session=${activeAgentId}&showMobileWorkspace=true`);
return () => {
useAgentStore.setState({ showAgentSetting: true });
};
- }, [activeId, navigate, location.pathname, tab, isMobile]);
+ }, [activeAgentId, navigate, location.pathname, tab, isMobile]);
};
diff --git a/src/hooks/useModelHasContextWindowToken.ts b/src/hooks/useModelHasContextWindowToken.ts
index 77a2f1db729..3ccd3ea20cc 100644
--- a/src/hooks/useModelHasContextWindowToken.ts
+++ b/src/hooks/useModelHasContextWindowToken.ts
@@ -1,5 +1,5 @@
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
+import { agentSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
export const useModelHasContextWindowToken = () => {
diff --git a/src/hooks/useNavigateToAgent.ts b/src/hooks/useNavigateToAgent.ts
new file mode 100644
index 00000000000..85467c44379
--- /dev/null
+++ b/src/hooks/useNavigateToAgent.ts
@@ -0,0 +1,19 @@
+import { SESSION_CHAT_URL } from '@lobechat/const';
+import { useCallback } from 'react';
+
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useChatStore } from '@/store/chat';
+
+export const useNavigateToAgent = () => {
+ const togglePortal = useChatStore((s) => s.togglePortal);
+ const router = useQueryRoute();
+
+ return useCallback(
+ (agentId: string) => {
+ togglePortal(false);
+
+ router.push(SESSION_CHAT_URL(agentId, false));
+ },
+ [togglePortal, router],
+ );
+};
diff --git a/src/hooks/useOperationState.test.ts b/src/hooks/useOperationState.test.ts
new file mode 100644
index 00000000000..3dbf94a93e9
--- /dev/null
+++ b/src/hooks/useOperationState.test.ts
@@ -0,0 +1,270 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+
+import { useOperationState } from './useOperationState';
+
+vi.mock('zustand/traditional');
+
+describe('useOperationState', () => {
+ const TEST_CONTEXT = {
+ agentId: 'test-agent-id',
+ topicId: 'test-topic-id',
+ threadId: null,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ act(() => {
+ useChatStore.setState({
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ toolCallingStreamIds: {},
+ });
+ });
+ });
+
+ describe('getMessageOperationState', () => {
+ describe('isGenerating', () => {
+ it('should return true when execAgentRuntime operation is running', () => {
+ const messageId = 'test-message-id';
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-1': {
+ id: 'op-1',
+ type: 'execAgentRuntime',
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-1'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isGenerating).toBe(true);
+ });
+
+ it('should return true when execServerAgentRuntime operation is running (Group Chat)', () => {
+ const messageId = 'test-message-id';
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-1': {
+ id: 'op-1',
+ type: 'execServerAgentRuntime',
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-1'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isGenerating).toBe(true);
+ });
+
+ it('should return false when operation is completed', () => {
+ const messageId = 'test-message-id';
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-1': {
+ id: 'op-1',
+ type: 'execServerAgentRuntime',
+ status: 'completed',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-1'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isGenerating).toBe(false);
+ });
+
+ it('should return false when no operations exist for the message', () => {
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState('non-existent-message');
+ expect(state.isGenerating).toBe(false);
+ });
+
+ it('should return true when message has multiple operations with at least one running execServerAgentRuntime', () => {
+ const messageId = 'test-message-id';
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-exec': {
+ id: 'op-exec',
+ type: 'execServerAgentRuntime',
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ 'op-stream': {
+ id: 'op-stream',
+ type: 'groupAgentStream',
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ parentOperationId: 'op-exec',
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-exec', 'op-stream'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isGenerating).toBe(true);
+ });
+
+ it('should detect isGenerating for all AI_RUNTIME_OPERATION_TYPES', () => {
+ // Verify the constant is used correctly by testing all types in it
+ for (const opType of AI_RUNTIME_OPERATION_TYPES) {
+ const messageId = `test-message-${opType}`;
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-1': {
+ id: 'op-1',
+ type: opType,
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-1'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isGenerating).toBe(true);
+ }
+ });
+ });
+
+ describe('other states', () => {
+ it('should return isCreating true when sendMessage operation is running', () => {
+ const messageId = 'test-message-id';
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-1': {
+ id: 'op-1',
+ type: 'sendMessage',
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-1'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isCreating).toBe(true);
+ });
+
+ it('should return isContinuing true when continue operation is running', () => {
+ const messageId = 'test-message-id';
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-1': {
+ id: 'op-1',
+ type: 'continue',
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-1'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isContinuing).toBe(true);
+ });
+
+ it('should return isRegenerating true when regenerate operation is running', () => {
+ const messageId = 'test-message-id';
+
+ act(() => {
+ useChatStore.setState({
+ operations: {
+ 'op-1': {
+ id: 'op-1',
+ type: 'regenerate',
+ status: 'running',
+ context: { messageId },
+ abortController: new AbortController(),
+ metadata: { startTime: Date.now() },
+ },
+ },
+ operationsByMessage: {
+ [messageId]: ['op-1'],
+ },
+ });
+ });
+
+ const { result } = renderHook(() => useOperationState(TEST_CONTEXT));
+
+ const state = result.current.getMessageOperationState(messageId);
+ expect(state.isRegenerating).toBe(true);
+ });
+ });
+ });
+});
diff --git a/src/hooks/useOperationState.ts b/src/hooks/useOperationState.ts
new file mode 100644
index 00000000000..59d2d533f3a
--- /dev/null
+++ b/src/hooks/useOperationState.ts
@@ -0,0 +1,109 @@
+import { useMemo } from 'react';
+import { useShallow } from 'zustand/react/shallow';
+
+import type { ConversationContext, OperationState } from '@/features/Conversation/types';
+import {
+ DEFAULT_MESSAGE_OPERATION_STATE,
+ DEFAULT_TOOL_OPERATION_STATE,
+} from '@/features/Conversation/types/operation';
+import { useChatStore } from '@/store/chat';
+import { operationSelectors } from '@/store/chat/selectors';
+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+/**
+ * Hook to create an OperationState object from ChatStore
+ *
+ * This hook subscribes to the ChatStore and builds an OperationState object
+ * that can be passed to ConversationProvider for reactive updates.
+ *
+ * @param context - The conversation context (sessionId, topicId, threadId)
+ * @returns OperationState object with reactive getters
+ */
+export const useOperationState = (context: ConversationContext): OperationState => {
+ const contextKey = messageMapKey(context);
+
+ // Subscribe to the relevant parts of ChatStore for reactivity
+ const { operations, operationsByContext, operationsByMessage, toolCallingStreamIds } =
+ useChatStore(
+ useShallow((s) => ({
+ operations: s.operations,
+ operationsByContext: s.operationsByContext,
+ operationsByMessage: s.operationsByMessage,
+ toolCallingStreamIds: s.toolCallingStreamIds,
+ })),
+ );
+
+ // Check if AI is generating in this context
+ const isAIGenerating = useChatStore((s) =>
+ operationSelectors.isAgentRuntimeRunningByContext(context)(s),
+ );
+
+ // Get send message error for this context
+ const sendMessageError = useMemo(() => {
+ const operationIds = operationsByContext[contextKey] || [];
+
+ // Find the latest sendMessage operation with error
+ for (const opId of [...operationIds].reverse()) {
+ const op = operations[opId];
+ if (op && op.type === 'sendMessage' && op.metadata.inputSendErrorMsg) {
+ return op.metadata.inputSendErrorMsg as string;
+ }
+ }
+
+ return undefined;
+ }, [operationsByContext, contextKey, operations]);
+
+ // Build the OperationState object
+ const operationState = useMemo<OperationState>(() => {
+ return {
+ getMessageOperationState: (messageId: string) => {
+ const state = useChatStore.getState();
+ const operationIds = operationsByMessage[messageId] || [];
+
+ if (operationIds.length === 0) {
+ return DEFAULT_MESSAGE_OPERATION_STATE;
+ }
+
+ const messageOps = operationIds.map((id) => operations[id]).filter(Boolean);
+ const runningOps = messageOps.filter((op) => op.status === 'running');
+
+ return {
+ isContinuing: runningOps.some((op) => op.type === 'continue'),
+ isCreating: runningOps.some(
+ (op) => op.type === 'sendMessage' || op.type === 'createAssistantMessage',
+ ),
+ // Check AI runtime operations (client-side and server-side)
+ isGenerating: runningOps.some((op) => AI_RUNTIME_OPERATION_TYPES.includes(op.type)),
+ isInReasoning: runningOps.some((op) => op.type === 'reasoning'),
+ isProcessing: operationSelectors.isMessageProcessing(messageId)(state),
+ isRegenerating: runningOps.some((op) => op.type === 'regenerate'),
+ };
+ },
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ getToolOperationState: (messageId: string, index: number, _toolCallId?: string) => {
+ const state = useChatStore.getState();
+
+ // Check tool streaming state
+ const toolStreamState = toolCallingStreamIds[messageId];
+ const isStreaming = toolStreamState ? (toolStreamState[index] ?? false) : false;
+
+ // Check tool invoking state (plugin API invocation)
+ const isInvoking = operationSelectors.isMessageInToolCalling(messageId)(state);
+
+ if (!isStreaming && !isInvoking) {
+ return DEFAULT_TOOL_OPERATION_STATE;
+ }
+
+ return {
+ isInvoking,
+ isStreaming,
+ };
+ },
+ isAIGenerating,
+ sendMessageError,
+ };
+ }, [operations, operationsByMessage, toolCallingStreamIds, isAIGenerating, sendMessageError]);
+
+ return operationState;
+};
diff --git a/src/hooks/usePinnedAgentState.ts b/src/hooks/usePinnedAgentState.ts
index f2fa572ad1c..c5a73557ebb 100644
--- a/src/hooks/usePinnedAgentState.ts
+++ b/src/hooks/usePinnedAgentState.ts
@@ -1,28 +1,19 @@
'use client';
-import { useSessionStore } from '@/store/session';
-import { useUrlHydrationStore } from '@/store/urlHydration';
+import { useAgentStore } from '@/store/agent';
export const usePinnedAgentState = () => {
- const isPinned = useSessionStore((s) => s.isAgentPinned);
- const setAgentPinned = useSessionStore((s) => s.setAgentPinned);
- const toggleAgentPinned = useSessionStore((s) => s.toggleAgentPinned);
- const syncToUrl = useUrlHydrationStore((s) => s.syncAgentPinnedToUrl);
-
- const withSync = <T extends (...args: any[]) => void>(fn: T) => {
- return (...args: Parameters<T>) => {
- fn(...args);
- syncToUrl();
- };
- };
+ const isPinned = useAgentStore((s) => s.isAgentPinned);
+ const setAgentPinned = useAgentStore((s) => s.setAgentPinned);
+ const toggleAgentPinned = useAgentStore((s) => s.toggleAgentPinned);
return [
isPinned,
{
- pinAgent: withSync(() => setAgentPinned(true)),
- setIsPinned: withSync(setAgentPinned),
- togglePinAgent: withSync(toggleAgentPinned),
- unpinAgent: withSync(() => setAgentPinned(false)),
+ pinAgent: () => setAgentPinned(true),
+ setIsPinned: setAgentPinned,
+ togglePinAgent: toggleAgentPinned,
+ unpinAgent: () => setAgentPinned(false),
},
] as const;
};
diff --git a/src/hooks/useQueryRoute.ts b/src/hooks/useQueryRoute.ts
index f689b781c30..a0788fc142b 100644
--- a/src/hooks/useQueryRoute.ts
+++ b/src/hooks/useQueryRoute.ts
@@ -1,9 +1,8 @@
+import { isOnServerSide } from '@lobechat/utils';
import qs, { type ParsedQuery } from 'query-string';
import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
-import { isOnServerSide } from '@/utils/env';
-
interface QueryRouteOptions {
hash?: string;
query?: ParsedQuery;
diff --git a/src/hooks/useShare.tsx b/src/hooks/useShare.tsx
index 127179db725..51223212b81 100644
--- a/src/hooks/useShare.tsx
+++ b/src/hooks/useShare.tsx
@@ -6,7 +6,7 @@ import {
SiWhatsapp,
SiX,
} from '@icons-pack/react-simple-icons';
-import { camelCase, identity, pickBy } from 'lodash-es';
+import { camelCase, identity, pickBy } from 'es-toolkit/compat';
import qs from 'query-string';
const stringifyHashtags = (hashtags: string[], joinfix: string = ',', prefix?: string) => {
diff --git a/src/hooks/useSwitchSession.ts b/src/hooks/useSwitchSession.ts
deleted file mode 100644
index ce8c8a0dbcd..00000000000
--- a/src/hooks/useSwitchSession.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { useCallback } from 'react';
-import { useLocation } from 'react-router-dom';
-
-import { useQueryRoute } from '@/hooks/useQueryRoute';
-import { useChatStore } from '@/store/chat';
-import { useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-
-export const useSwitchSession = () => {
- const switchSession = useSessionStore((s) => s.switchSession);
- const togglePortal = useChatStore((s) => s.togglePortal);
- const mobile = useServerConfigStore((s) => s.isMobile);
- const router = useQueryRoute();
- const location = useLocation();
- const pathname = location.pathname;
-
- return useCallback(
- (id: string) => {
- switchSession(id);
- togglePortal(false);
-
- const chatPath = '/chat';
- if (mobile || pathname !== chatPath) {
- setTimeout(() => {
- router.push(chatPath, {
- query: { session: id, showMobileWorkspace: 'true' },
- });
- }, 50);
- }
- },
- [mobile, pathname, switchSession, togglePortal, router],
- );
-};
diff --git a/src/hooks/useTTS.ts b/src/hooks/useTTS.ts
index fcc9c906c89..64624b1a4e2 100644
--- a/src/hooks/useTTS.ts
+++ b/src/hooks/useTTS.ts
@@ -12,7 +12,7 @@ import isEqual from 'fast-deep-equal';
import { createHeaderWithOpenAI } from '@/services/_header';
import { API_ENDPOINTS } from '@/services/_url';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
+import { agentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
diff --git a/src/hooks/useTokenCount.ts b/src/hooks/useTokenCount.ts
index 43ec9901e9d..774ff652078 100644
--- a/src/hooks/useTokenCount.ts
+++ b/src/hooks/useTokenCount.ts
@@ -1,4 +1,4 @@
-import { debounce } from 'lodash-es';
+import { debounce } from 'es-toolkit/compat';
import { startTransition, useCallback, useEffect, useState } from 'react';
import { encodeAsync } from '@/utils/tokenizer';