🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
feat: Better CMDK (#10915)
René Wang1f3531f8f584
diff --git a/packages/context-engine/src/providers/PageEditorContextInjector.ts b/packages/context-engine/src/providers/PageEditorContextInjector.tsindex 624328f6085..586a5d25ffe 100644--- a/packages/context-engine/src/providers/PageEditorContextInjector.ts+++ b/packages/context-engine/src/providers/PageEditorContextInjector.ts@@ -251,14 +251,6 @@ const defaultFormatPageContext = (context: PageEditorContext): string => {// Convert Lexical JSON to XML format with node IDsconst xmlStructure = convertLexicalToXml(context.editorData.root);- // Log the conversion for debugging- const nodeCount = context.editorData.root?.children?.length || 0;- console.log(- '[PageEditorContextInjector] Converted Lexical to XML, root children count:',- nodeCount,- );- console.log('[PageEditorContextInjector] XML preview:', xmlStructure.slice(0, 500));-// Don't escape the XML since it's already properly formatted XML// Just include it directly (not escaped) so the model can parse the structureparts.push(`<document_structure>\n${xmlStructure}\n</document_structure>`);diff --git a/src/features/CommandMenu/AskAIMenu.tsx b/src/features/CommandMenu/AskAIMenu.tsxnew file mode 100644index 00000000000..a5442c0e289--- /dev/null+++ b/src/features/CommandMenu/AskAIMenu.tsx@@ -0,0 +1,84 @@+import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@lobechat/const';+import { Avatar } from '@lobehub/ui';+import { Command } from 'cmdk';+import { Image } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';++import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';++import { useCommandMenuContext } from './CommandMenuContext';+import { useStyles } from './styles';+import { useCommandMenu } from './useCommandMenu';++const AskAIMenu = memo(() => {+ const { t } = useTranslation('common');+ const navigate = useNavigate();+ const { handleAskLobeAI, handleAIPainting, closeCommandMenu } = useCommandMenu();+ const { search } = useCommandMenuContext();+ const { styles } = useStyles();++ // Get agent list (limit to first 20 items for simplicity)+ const allAgents = useHomeStore(homeAgentListSelectors.allAgents);+ const agents = allAgents.filter((item) => item.type === 'agent').slice(0, 20);++ const heading = search.trim()+ ? t('cmdk.askAIHeading', { query: `"${search.trim()}"` })+ : t('cmdk.askAIHeadingEmpty');++ const handleAgentSelect = (agentId: string) => {+ if (search.trim()) {+ const message = encodeURIComponent(search.trim());+ navigate(`/agent/${agentId}?message=${message}`);+ } else {+ navigate(`/agent/${agentId}`);+ }+ closeCommandMenu();+ };++ return (+ <Command.Group heading={heading}>+ <Command.Item onSelect={handleAskLobeAI} value="lobe-ai">+ <Avatar+ avatar={DEFAULT_INBOX_AVATAR}+ emojiScaleWithBackground+ shape="square"+ size={18}+ />+ <div className={styles.itemContent}>+ <div className={styles.itemLabel}>Lobe AI</div>+ </div>+ </Command.Item>+ <Command.Item onSelect={handleAIPainting} value="ai-painting">+ <Image className={styles.icon} />+ <div className={styles.itemContent}>+ <div className={styles.itemLabel}>{t('cmdk.aiPainting')}</div>+ </div>+ </Command.Item>++ {agents.map((agent) => (+ <Command.Item+ key={agent.id}+ onSelect={() => handleAgentSelect(agent.id)}+ value={`agent-${agent.id}`}+ >+ <Avatar+ avatar={typeof agent.avatar === 'string' ? agent.avatar : DEFAULT_AVATAR}+ emojiScaleWithBackground+ shape="square"+ size={18}+ />+ <div className={styles.itemContent}>+ <div className={styles.itemLabel}>{agent.title || t('defaultAgent')}</div>+ </div>+ </Command.Item>+ ))}+ </Command.Group>+ );+});++AskAIMenu.displayName = 'AskAIMenu';++export default AskAIMenu;diff --git a/src/features/CommandMenu/CommandMenuContext.tsx b/src/features/CommandMenu/CommandMenuContext.tsxindex aabea779971..9ea6eed6795 100644--- a/src/features/CommandMenu/CommandMenuContext.tsx+++ b/src/features/CommandMenu/CommandMenuContext.tsx@@ -7,7 +7,6 @@ import { MenuContext, PageType } from './types';import { detectContext } from './utils/context';interface CommandMenuContextValue {- isAiMode: boolean;menuContext: MenuContext;mounted: boolean;page: PageType | undefined;@@ -22,7 +21,7 @@ interface CommandMenuContextValue {viewMode: MenuViewMode;}-type MenuViewMode = 'default' | 'search' | 'ai-chat';+type MenuViewMode = 'default' | 'search';const CommandMenuContext = createContext<CommandMenuContextValue | undefined>(undefined);@@ -41,7 +40,6 @@ export const CommandMenuProvider = ({ children, pathname }: CommandMenuProviderP// Derived valuesconst page = pages.at(-1);- const isAiMode = page === 'ai-chat';// Ensure we're mounted on the clientuseEffect(() => {@@ -49,19 +47,16 @@ export const CommandMenuProvider = ({ children, pathname }: CommandMenuProviderP}, []);useEffect(() => {- if (pages.at(-1) === 'ai-chat') {- setViewMode('ai-chat');- } else if (search.trim().length > 0) {+ if (search.trim().length > 0) {setViewMode('search');} else {setViewMode('default');}- }, [pages, search]);+ }, [search]);return (<CommandMenuContext.Providervalue={{- isAiMode,menuContext,mounted,page,diff --git a/src/features/CommandMenu/MainMenu.tsx b/src/features/CommandMenu/MainMenu.tsxindex b3e477d5c81..811046a43b3 100644--- a/src/features/CommandMenu/MainMenu.tsx+++ b/src/features/CommandMenu/MainMenu.tsx@@ -7,6 +7,8 @@ import {Github,Image,LibraryBig,+ MailIcon,+ MessageSquarePlusIcon,Monitor,Settings,Shapes,@@ -27,7 +29,15 @@ const MainMenu = memo(() => {const { pathname, menuContext, setPages, pages } = useCommandMenuContext();const { t } = useTranslation('common');- const { handleCreateSession, handleNavigate, handleExternalLink } = useCommandMenu();+ const {+ handleCreateSession,+ handleCreateTopic,+ handleCreateLibrary,+ handleCreatePage,+ handleNavigate,+ handleExternalLink,+ handleCreateAgentTeam,+ } = useCommandMenu();return (<>@@ -37,20 +47,49 @@ const MainMenu = memo(() => {<CommandItemicon={<Bot />}onSelect={handleCreateSession}+ unpinned={menuContext === 'agent' || menuContext === 'page'}value="create new agent assistant">{t('cmdk.newAgent')}</CommandItem>- {menuContext === 'resource' && (- <CommandItem icon={<Bot />} onSelect={handleCreateSession} value="create new library">- {t('cmdk.newLibrary')}+ <CommandItem+ icon={<Bot />}+ onSelect={handleCreateAgentTeam}+ unpinned={menuContext === 'agent' || menuContext === 'page'}+ value="create new agent team"+ >+ {t('cmdk.newAgentTeam')}+ </CommandItem>++ {menuContext === 'agent' && (+ <CommandItem+ icon={<MessageSquarePlusIcon />}+ onSelect={handleCreateTopic}+ unpinned={menuContext !== 'agent'}+ value="create new topic"+ >+ {t('cmdk.newTopic')}</CommandItem>)}+ <CommandItem icon={<FilePen />} onSelect={handleCreatePage} value="create new page">+ {t('cmdk.newPage')}+ </CommandItem>++ <CommandItem+ icon={<LibraryBig />}+ onSelect={handleCreateLibrary}+ unpinned={menuContext !== 'resource'}+ value="create new library"+ >+ {t('cmdk.newLibrary')}+ </CommandItem>+{menuContext !== 'settings' && (<CommandItemicon={<Settings />}+ keywords={['settings', 'preferences', 'configuration', 'options']}onSelect={() => handleNavigate('/settings')}value="settings">@@ -58,7 +97,11 @@ const MainMenu = memo(() => {</CommandItem>)}- <CommandItem icon={<Monitor />} onSelect={() => setPages([...pages, 'theme'])} value="theme">+ <CommandItem+ icon={<Monitor />}+ onSelect={() => setPages([...pages, 'theme'])}+ value="theme"+ >{t('cmdk.theme')}</CommandItem></Command.Group>@@ -108,8 +151,17 @@ const MainMenu = memo(() => {</Command.Group><Command.Group heading={t('cmdk.about')}>+ <CommandItem+ icon={<MailIcon />}+ keywords={['feedback', 'issue', 'bug', 'problem']}+ onSelect={() => handleExternalLink(FEEDBACK)}+ value="contact-via-email"+ >+ {t('cmdk.contactViaEmail')}+ </CommandItem><CommandItemicon={<Github />}+ keywords={['issue', 'bug', 'problem', 'feedback']}onSelect={() => handleExternalLink(FEEDBACK)}value="submit-issue">@@ -117,6 +169,7 @@ const MainMenu = memo(() => {</CommandItem><CommandItemicon={<Star />}+ keywords={['github', 'star', 'favorite', 'like']}onSelect={() => handleExternalLink(SOCIAL_URL.github)}value="star-github">@@ -124,6 +177,7 @@ const MainMenu = memo(() => {</CommandItem><CommandItemicon={<DiscordIcon />}+ keywords={['discord', 'help', 'support', 'customer service']}onSelect={() => handleExternalLink(SOCIAL_URL.discord)}value="discord">diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsxindex f085c285182..d05dd86a3a7 100644--- a/src/features/CommandMenu/SearchResults.tsx+++ b/src/features/CommandMenu/SearchResults.tsx@@ -8,8 +8,8 @@ import { useNavigate } from 'react-router-dom';import type { SearchResult } from '@/database/repositories/search';-import { CommandItem } from './components';import { useCommandMenuContext } from './CommandMenuContext';+import { CommandItem } from './components';import { useStyles } from './styles';import type { ValidSearchType } from './utils/queryParser';@@ -70,7 +70,7 @@ const SearchResults = memo<SearchResultsProps>(break;}case 'page': {- navigate(`/page/${result.id}`);+ navigate(`/page/${result.id.split('_')[1]}`);break;}case 'mcp': {diff --git a/src/features/CommandMenu/components/CommandInput.tsx b/src/features/CommandMenu/components/CommandInput.tsxindex ce16ef8bc43..5b8978047b6 100644--- a/src/features/CommandMenu/components/CommandInput.tsx+++ b/src/features/CommandMenu/components/CommandInput.tsx@@ -42,7 +42,7 @@ const CommandInput = memo(() => {const { styles } = useStyles();const { handleBack } = useCommandMenu();- const { menuContext, viewMode, pages, search, setSearch, typeFilter, setTypeFilter } =+ const { menuContext, pages, page, search, setSearch, typeFilter, setTypeFilter } =useCommandMenuContext();const hasPages = pages.length > 0;@@ -78,11 +78,11 @@ const CommandInput = memo(() => {autoFocusonValueChange={setSearch}placeholder={- viewMode === 'ai-chat' ? t('cmdk.aiModePlaceholder') : t('cmdk.searchPlaceholder')+ page === 'ask-ai' ? t('cmdk.aiModePlaceholder') : t('cmdk.searchPlaceholder')}value={search}/>- {viewMode !== 'ai-chat' && search.trim() ? (+ {page !== 'ask-ai' && search.trim() ? (<><span style={{ fontSize: '14px', opacity: 0.6 }}>{t('cmdk.askAI')}</span><Tag>{t('cmdk.keyboard.Tab')}</Tag>diff --git a/src/features/CommandMenu/components/CommandItem.tsx b/src/features/CommandMenu/components/CommandItem.tsxindex 3f9981dc063..1d17263e27b 100644--- a/src/features/CommandMenu/components/CommandItem.tsx+++ b/src/features/CommandMenu/components/CommandItem.tsx@@ -2,9 +2,16 @@ import { Command } from 'cmdk';import type { ComponentProps, ReactNode } from 'react';import { cloneElement, isValidElement, memo } from 'react';+import { useCommandMenuContext } from '../CommandMenuContext';import { useStyles } from '../styles';-type BaseCommandItemProps = Omit<ComponentProps<typeof Command.Item>, 'children'>;+type BaseCommandItemProps = Omit<ComponentProps<typeof Command.Item>, 'children'> & {+ /**+ * Hide the item from default view but keep it searchable+ * When true, the item won't show in the default list but will appear in search results+ */+ unpinned?: boolean;+};type SimpleCommandItemProps = BaseCommandItemProps & {children: ReactNode;@@ -27,9 +34,18 @@ type CommandItemProps = SimpleCommandItemProps | DetailedCommandItemProps;*/const CommandItem = memo<CommandItemProps>((props) => {const { styles } = useStyles();+ const { search } = useCommandMenuContext();++ // Check if item should be rendered+ // Unpinned items are only rendered when there's an active search+ const shouldRender = props.unpinned ? !!search : true;++ if (!shouldRender) {+ return null;+ }if (props.variant === 'detailed') {- const { icon, title, description, trailingLabel, ...itemProps } = props;+ const { icon, title, description, trailingLabel, unpinned: _unpinned, ...itemProps } = props;return (<Command.Item {...itemProps}><div className={styles.itemContent}>@@ -45,7 +61,7 @@ const CommandItem = memo<CommandItemProps>((props) => {}// Simple variant (default)- const { icon, children, ...itemProps } = props;+ const { icon, children, unpinned: _unpinned, ...itemProps } = props;// Clone the icon element and add the icon className if it's a valid React elementconst iconWithClass =diff --git a/src/features/CommandMenu/index.tsx b/src/features/CommandMenu/index.tsxindex 59d1c07b568..36ad3248a22 100644--- a/src/features/CommandMenu/index.tsx+++ b/src/features/CommandMenu/index.tsx@@ -8,6 +8,7 @@ import { useLocation } from 'react-router-dom';import { useGlobalStore } from '@/store/global';+import AskAIMenu from './AskAIMenu';import { CommandMenuProvider, useCommandMenuContext } from './CommandMenuContext';import MainMenu from './MainMenu';import SearchResults from './SearchResults';@@ -25,10 +26,8 @@ const CommandMenuContent = memo(() => {const { styles } = useStyles();const {closeCommandMenu,- handleAskAISubmit,handleBack,hasSearch,- isAiMode,isSearching,searchQuery,searchResults,@@ -43,18 +42,10 @@ const CommandMenuContent = memo(() => {<CommandclassName={styles.commandRoot}onKeyDown={(e) => {- // Tab key to ask AI when not in AI mode- if (e.key === 'Tab' && viewMode !== 'ai-chat') {+ // Tab key to ask AI+ if (e.key === 'Tab' && page !== 'ask-ai') {e.preventDefault();-- setPages([...pages, 'ai-chat']);-- return;- }- // Enter key in AI mode to submit- if (e.key === 'Enter' && viewMode === 'ai-chat') {- e.preventDefault();- handleAskAISubmit();+ setPages([...pages, 'ask-ai']);return;}// Escape goes to previous page or closes@@ -72,19 +63,19 @@ const CommandMenuContent = memo(() => {setPages((prev) => prev.slice(0, -1));}}}- shouldFilter={viewMode !== 'ai-chat'}+ shouldFilter={page !== 'ask-ai'}><CommandInput /><Command.List>- {!isAiMode && !isSearching && <Command.Empty>{t('cmdk.noResults')}</Command.Empty>}- {isAiMode && <Command.Empty>{t('cmdk.aiModeHint')}</Command.Empty>}+ <Command.Empty>{t('cmdk.noResults')}</Command.Empty>{!page && <MainMenu />}{page === 'theme' && <ThemeMenu />}+ {page === 'ask-ai' && <AskAIMenu />}- {!page && hasSearch && !isAiMode && (+ {!page && hasSearch && (<SearchResultsisLoading={isSearching}onClose={closeCommandMenu}diff --git a/src/features/CommandMenu/types.ts b/src/features/CommandMenu/types.tsindex 4b9d742c8e1..ab902204333 100644--- a/src/features/CommandMenu/types.ts+++ b/src/features/CommandMenu/types.ts@@ -6,7 +6,7 @@ export interface ChatMessage {export type ThemeMode = 'light' | 'dark' | 'auto';-export type PageType = 'theme' | 'ai-chat' | string;+export type PageType = 'theme' | 'ask-ai' | string;export interface Context {name: string;diff --git a/src/features/CommandMenu/useCommandMenu.ts b/src/features/CommandMenu/useCommandMenu.tsindex 31ea3c193c6..cae520218b5 100644--- a/src/features/CommandMenu/useCommandMenu.ts+++ b/src/features/CommandMenu/useCommandMenu.ts@@ -3,10 +3,14 @@ import { useEffect, useMemo } from 'react';import { useNavigate } from 'react-router-dom';import useSWR from 'swr';+import { useCreateMenuItems } from '@/app/[variants]/(main)/home/_layout/hooks';import type { SearchResult } from '@/database/repositories/search';+import { useCreateNewModal } from '@/features/LibraryModal';+import { useGroupWizard } from '@/layout/GlobalProvider/GroupWizardProvider';import { lambdaClient } from '@/libs/trpc/client';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors/builtinAgentSelectors';+import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';import { globalHelpers } from '@/store/global/helpers';import { useHomeStore } from '@/store/home';@@ -28,7 +32,6 @@ export const useCommandMenu = () => {typeFilter,setTypeFilter,page,- isAiMode,menuContext: context,pathname,} = useCommandMenuContext();@@ -38,6 +41,9 @@ export const useCommandMenu = () => {const createAgent = useAgentStore((s) => s.createAgent);const refreshAgentList = useHomeStore((s) => s.refreshAgentList);const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);+ const { openGroupWizard } = useGroupWizard();+ const { createGroupWithMembers, createGroupFromTemplate, createPage } = useCreateMenuItems();+ const { open: openCreateLibraryModal } = useCreateNewModal();// Extract agentId from pathname when in agent contextconst agentId = useMemo(() => {@@ -56,7 +62,7 @@ export const useCommandMenu = () => {const searchQuery = debouncedSearch.trim();const { data: searchResults, isLoading: isSearching } = useSWR<SearchResult[]>(- hasSearch && !isAiMode ? ['search', searchQuery, agentId, typeFilter] : null,+ hasSearch ? ['search', searchQuery, agentId, typeFilter] : null,async () => {const locale = globalHelpers.getCurrentLanguage();return lambdaClient.search.query.query({@@ -104,7 +110,7 @@ export const useCommandMenu = () => {closeCommandMenu();};- const handleAskAISubmit = () => {+ const handleAskLobeAI = () => {// Navigate to inbox agent with the message query parameterif (inboxAgentId && search.trim()) {const message = encodeURIComponent(search.trim());@@ -113,6 +119,15 @@ export const useCommandMenu = () => {}};+ const handleAIPainting = () => {+ // Navigate to painting page with search as prompt+ if (search.trim()) {+ const prompt = encodeURIComponent(search.trim());+ navigate(`/image?prompt=${prompt}`);+ closeCommandMenu();+ }+ };+const handleBack = () => {setPages((prev) => prev.slice(0, -1));};@@ -129,16 +144,63 @@ export const useCommandMenu = () => {closeCommandMenu();};+ const [openNewTopicOrSaveTopic] = useChatStore((s) => [s.openNewTopicOrSaveTopic]);++ const handleCreateTopic = async () => {+ openNewTopicOrSaveTopic();+ closeCommandMenu();+ };++ const handleCreateLibrary = async () => {+ closeCommandMenu();+ openCreateLibraryModal({+ onSuccess: (id) => {+ navigate(`/resource/library/${id}`);+ },+ });+ };++ const handleCreatePage = async () => {+ await createPage();+ closeCommandMenu();+ };++ const handleCreateAgentTeam = async () => {+ closeCommandMenu();+ openGroupWizard({+ onCreateCustom: async (selectedAgents, hostConfig, enableSupervisor) => {+ await createGroupWithMembers(selectedAgents, undefined, hostConfig, enableSupervisor);+ },+ onCreateFromTemplate: async (+ templateId,+ hostConfig,+ enableSupervisor,+ selectedMemberTitles,+ ) => {+ await createGroupFromTemplate(+ templateId,+ hostConfig,+ enableSupervisor,+ selectedMemberTitles,+ );+ },+ });+ };+return {closeCommandMenu,- handleAskAISubmit,+ handleAIPainting,+ handleAskLobeAI,handleBack,+ handleCreateAgentTeam,+ handleCreateLibrary,+ handleCreatePage,handleCreateSession,+ handleCreateTopic,handleExternalLink,handleNavigate,handleThemeChange,hasSearch,- isAiMode,isSearching,mounted,open,diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex bdf5749a462..329f66728e1 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -10,6 +10,7 @@ import WideScreenContainer from '@/features/WideScreenContainer';import { useRegisterFilesHotkeys, useSaveDocumentHotkey } from '@/hooks/useHotkeys';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';+import { useFileStore } from '@/store/file';import Body from './Body';import Copilot from './Copilot';@@ -76,13 +77,15 @@ const PageEditor: FC<PageEditorProps> = ({knowledgeBaseId,onDocumentIdChange,onSave,- onDelete,onBack,}) => {const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);const pageAgentId = useAgentStore(builtinAgentSelectors.pageAgentId);+useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.pageAgent);+ const [deletePage] = useFileStore((s) => [s.deletePage]);+if (!pageAgentId) return <Loading debugId="PageEditor > PageAgent Init" />;return (@@ -91,7 +94,7 @@ const PageEditor: FC<PageEditorProps> = ({key={pageId}knowledgeBaseId={knowledgeBaseId}onBack={onBack}- onDelete={onDelete}+ onDelete={() => deletePage(pageId || '')}onDocumentIdChange={onDocumentIdChange}onSave={onSave}pageId={pageId}diff --git a/src/features/PageEditor/PageEditorProvider.tsx b/src/features/PageEditor/PageEditorProvider.tsxindex 1b9ee683ebb..7aaa099a4ba 100644--- a/src/features/PageEditor/PageEditorProvider.tsx+++ b/src/features/PageEditor/PageEditorProvider.tsx@@ -18,7 +18,6 @@ export const PageEditorProvider = memo<PageEditorProviderProps>(children,pageId,knowledgeBaseId,- autoSave,onDocumentIdChange,onSave,onDelete,@@ -31,7 +30,6 @@ export const PageEditorProvider = memo<PageEditorProviderProps>(<ProvidercreateStore={() =>createStore({- autoSave,editor,knowledgeBaseId,onBack,@@ -44,7 +42,6 @@ export const PageEditorProvider = memo<PageEditorProviderProps>(}><StoreUpdater- autoSave={autoSave}knowledgeBaseId={knowledgeBaseId}onBack={onBack}onDelete={onDelete}diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex 68f44723b03..4ddc4f95f65 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -1,6 +1,7 @@'use client';import { useEditorState } from '@lobehub/editor/react';+import debug from 'debug';import React, { memo, useEffect, useRef } from 'react';import { createStoreUpdater } from 'zustand-utils';@@ -10,19 +11,12 @@ import { documentSelectors } from '@/store/file/slices/document/selectors';import { PublicState, usePageEditorStore, useStoreApi } from './store';+const log = debug('page:store-updater');+export type StoreUpdaterProps = Partial<PublicState>;const StoreUpdater = memo<StoreUpdaterProps>(- ({- pageId,- knowledgeBaseId,- autoSave,- onDocumentIdChange,- onSave,- onDelete,- onBack,- parentId,- }) => {+ ({ pageId, knowledgeBaseId, onDocumentIdChange, onSave, onDelete, onBack, parentId }) => {const storeApi = useStoreApi();const useStoreUpdater = createStoreUpdater(storeApi);@@ -46,7 +40,6 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Update store with propsuseStoreUpdater('pageId', pageId);useStoreUpdater('knowledgeBaseId', knowledgeBaseId);- useStoreUpdater('autoSave', autoSave ?? true);useStoreUpdater('onDocumentIdChange', onDocumentIdChange);useStoreUpdater('onSave', onSave);useStoreUpdater('onDelete', onDelete);@@ -56,7 +49,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Fetch full document detail when pageId changesuseEffect(() => {if (pageId && pageId !== lastLoadedDocIdRef.current) {- console.log('[StoreUpdater] PageId changed, fetching detail:', pageId);+ log('PageId changed, fetching detail:', pageId);// Immediately show loading state and reset for better UXsetIsLoadingDetail(true);setContentInit(false);@@ -69,10 +62,10 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Fetch the full document detailfetchDocumentDetail(pageId).then(() => {- console.log('[StoreUpdater] Document detail fetched successfully for:', pageId);+ log('Document detail fetched successfully for:', pageId);}).finally(() => {- console.log('[StoreUpdater] Setting isLoadingDetail to false');+ log('Setting isLoadingDetail to false');setIsLoadingDetail(false);});}@@ -81,7 +74,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Initialize currentDocId and document metadata after fetch completesuseEffect(() => {if (pageId !== lastLoadedDocIdRef.current && !isLoadingDetail) {- console.log('[StoreUpdater] Initializing metadata for pageId:', pageId, {+ log('Initializing metadata for pageId:', pageId, {hasEditorData: !!currentPage?.editorData,title: currentPage?.title,});@@ -98,7 +91,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Load content into editor after initializationuseEffect(() => {- console.log('[StoreUpdater] Content loading effect check:', {+ log('Content loading effect check:', {contentInit,editorInit,hasCurrentPage: !!currentPage,@@ -113,13 +106,13 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Defer editor content loading to avoid flushSync warningqueueMicrotask(() => {try {- console.log('[StoreUpdater] Loading content for page:', pageId);+ log('Loading content for page:', pageId);// Safety check: ensure we're loading content for the current page// This prevents loading old content when currentPage has stale dataconst currentState = storeApi.getState();if (currentState.currentDocId && currentState.currentDocId !== pageId) {- console.log('[StoreUpdater] Skipping content load - currentDocId mismatch', {+ log('Skipping content load - currentDocId mismatch', {currentDocId: currentState.currentDocId,pageId,});@@ -134,12 +127,12 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Load from editorData if availableif (currentPage?.editorData && Object.keys(currentPage.editorData).length > 0) {- console.log('[StoreUpdater] Loading from editorData');+ log('Loading from editorData');editor.setDocument('json', JSON.stringify(currentPage.editorData));const textContent = currentPage.content || '';storeApi.setState({ wordCount: calculateWordCount(textContent) });} else if (currentPage?.content && currentPage.content.trim()) {- console.log('[StoreUpdater] Loading from content (markdown)');+ log('Loading from content (markdown)');// Fallback to markdown content (e.g., from Notion imports)editor.setDocument('markdown', currentPage.content);storeApi.setState({ wordCount: calculateWordCount(currentPage.content) });@@ -150,17 +143,17 @@ const StoreUpdater = memo<StoreUpdaterProps>(.join('\n\n').trim();if (pagesContent) {- console.log('[StoreUpdater] Loading from pages content');+ log('Loading from pages content');editor.setDocument('markdown', pagesContent);storeApi.setState({ wordCount: calculateWordCount(pagesContent) });} else {- console.log('[StoreUpdater] Clearing editor - empty pages');+ log('Clearing editor - empty pages');editor.setDocument('markdown', ' ');storeApi.setState({ wordCount: 0 });}} else {// Empty document or temp page - clear editor with minimal content- console.log('[StoreUpdater] Clearing editor - empty/new page');+ log('Clearing editor - empty/new page');editor.setDocument('markdown', ' ');storeApi.setState({ wordCount: 0 });}@@ -168,7 +161,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(setContentInit(true);storeApi.setState({ isLoadingContent: false });} catch (error) {- console.error('[PageEditor] Failed to initialize editor content:', error);+ log('Failed to initialize editor content:', error);storeApi.setState({ isLoadingContent: false });}});@@ -221,12 +214,11 @@ const StoreUpdater = memo<StoreUpdaterProps>(useEffect(() => {// Use currentDocId (which includes temp docs) or fallback to pageIdconst activeId = currentDocId || pageId;- console.log('[StoreUpdater] Updating currentDocId in page agent runtime:', activeId);+ log('Updating currentDocId in page agent runtime:', activeId);pageAgentRuntime.setCurrentDocId(activeId);- // Cleanup: clear currentDocId when unmountingreturn () => {- console.log('[StoreUpdater] Clearing currentDocId on unmount');+ log('Clearing currentDocId on unmount');pageAgentRuntime.setCurrentDocId(undefined);};}, [currentDocId, pageId]);diff --git a/src/features/PageEditor/store/action.ts b/src/features/PageEditor/store/action.tsindex 83d7edd724a..4dbb86add2f 100644--- a/src/features/PageEditor/store/action.ts+++ b/src/features/PageEditor/store/action.ts@@ -1,4 +1,5 @@import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';+import debug from 'debug';import { debounce } from 'es-toolkit/compat';import { StateCreator } from 'zustand';@@ -9,6 +10,8 @@ import { DocumentSourceType, LobeDocument } from '@/types/document';import { State, initialState } from './initialState';+const log = debug('page:editor');+export interface Action {flushSave: () => void;handleContentChange: () => void;@@ -35,7 +38,7 @@ const createDebouncedSave = (get: () => Store) =>try {await get().performSave();} catch (error) {- console.error('[PageEditor] Failed to auto-save:', error);+ log('Failed to auto-save:', error);}},EDITOR_DEBOUNCE_TIME,@@ -73,7 +76,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =debouncedSave();}} catch (error) {- console.error('[PageEditor] Failed to update content:', error);+ log('Failed to update content:', error);}},@@ -104,7 +107,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =onDeleteCallback?.();resolve();} catch (error) {- console.error('Failed to delete page:', error);+ log('Failed to delete page:', error);message.error(t('pageEditor.deleteError'));reject(error);}@@ -134,7 +137,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =() => currentTitle,);- console.log('[PageEditor] Connected editor to page agent runtime');+ log('Connected editor to page agent runtime');}},@@ -251,7 +254,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =});onSave?.();} catch (error) {- console.error('[PageEditor] Failed to save:', error);+ log('Failed to save:', error);set({ saveStatus: 'idle' });}},diff --git a/src/features/PageExplorer/PageExplorerPlaceholder.tsx b/src/features/PageExplorer/PageExplorerPlaceholder.tsxindex efbb852cdaa..8b3a83caccf 100644--- a/src/features/PageExplorer/PageExplorerPlaceholder.tsx+++ b/src/features/PageExplorer/PageExplorerPlaceholder.tsx@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';import NavHeader from '@/features/NavHeader';import { useFileStore } from '@/store/file';+import { DocumentSourceType } from '@/types/document';const ICON_SIZE = 80;@@ -72,19 +73,70 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(const theme = useTheme();const { styles } = useStyles();const [isUploading, setIsUploading] = useState(false);- const [createDocument, setSelectedPageId] = useFileStore((s) => [+ const [+ createNewPage,+ createDocument,+ createOptimisticDocument,+ replaceTempDocumentWithReal,+ setSelectedPageId,+ ] = useFileStore((s) => [+ s.createNewPage,s.createDocument,+ s.createOptimisticDocument,+ s.replaceTempDocumentWithReal,s.setSelectedPageId,]);const handleCreateDocument = async (content: string, title: string) => {- const newDoc = await createDocument({- content,- knowledgeBaseId,- title,- });- // Navigate to the newly created page- setSelectedPageId(newDoc.id);+ if (!content) {+ // For empty pages, use createNewPage which handles optimistic updates+ await createNewPage(title);+ return;+ }++ // For markdown uploads with content, use optimistic pattern similar to createNewPage+ const tempPageId = createOptimisticDocument(title);+ // Set selected page to temp ID immediately (with URL update disabled for temp IDs)+ setSelectedPageId(tempPageId, false);++ try {+ const newDoc = await createDocument({+ content,+ knowledgeBaseId,+ title,+ });++ // Convert to LobeDocument format+ const realPage = {+ content: newDoc.content || '',+ createdAt: newDoc.createdAt ? new Date(newDoc.createdAt) : new Date(),+ editorData:+ typeof newDoc.editorData === 'string'+ ? JSON.parse(newDoc.editorData)+ : newDoc.editorData || null,+ fileType: 'custom/document' as const,+ filename: newDoc.title || title,+ id: newDoc.id,+ metadata: newDoc.metadata || {},+ source: 'document' as const,+ sourceType: DocumentSourceType.EDITOR,+ title: newDoc.title || title,+ totalCharCount: newDoc.content?.length || 0,+ totalLineCount: 0,+ updatedAt: newDoc.updatedAt ? new Date(newDoc.updatedAt) : new Date(),+ };++ // Replace optimistic with real+ replaceTempDocumentWithReal(tempPageId, realPage);+ // Update selected page ID and URL to the real page+ setSelectedPageId(newDoc.id);+ } catch (error) {+ console.error('Failed to create page:', error);+ // Remove temp document on error+ useFileStore.getState().removeTempDocument(tempPageId);+ setSelectedPageId(null);+ throw error;+ }};const handleUploadMarkdown = async (file: File) => {diff --git a/src/features/PageExplorer/index.tsx b/src/features/PageExplorer/index.tsxindex ea8185db7ef..a8018c25fb8 100644--- a/src/features/PageExplorer/index.tsx+++ b/src/features/PageExplorer/index.tsx@@ -24,7 +24,6 @@ const PageExplorer = memo<PageExplorerProps>(({ pageId }) => {pages,fetchDocuments,fetchDocumentDetail,- deletePage,isDocumentListLoading,] = useFileStore((s) => [s.selectedPageId,@@ -57,10 +56,6 @@ const PageExplorer = memo<PageExplorerProps>(({ pageId }) => {const currentPageId = selectedPageId || pageId;- const handleDelete = (docId: string) => {- deletePage(docId);- };-// Check if the current page exists in the pages listconst currentPageExists = currentPageId && pages.some((page) => page.id === currentPageId);@@ -75,13 +70,7 @@ const PageExplorer = memo<PageExplorerProps>(({ pageId }) => {return <PageExplorerPlaceholder hasPages={pages?.length > 0} />;}- return (- <PageEditor- // knowledgeBaseId={knowledgeBaseId}- onDelete={() => handleDelete(currentPageId)}- pageId={currentPageId}- />- );+ return <PageEditor pageId={currentPageId} />;});export default PageExplorer;diff --git a/src/features/ResourceManager/components/Explorer/useFileExplorer.ts b/src/features/ResourceManager/components/Explorer/useFileExplorer.tsindex aed7c334607..b60a5779d7c 100644--- a/src/features/ResourceManager/components/Explorer/useFileExplorer.ts+++ b/src/features/ResourceManager/components/Explorer/useFileExplorer.ts@@ -301,17 +301,15 @@ export const useFileExplorer = ({ category: categoryProp, libraryId }: UseFileExisFilePreviewMode,-isLoading,// State-isMasonryReady,+ isMasonryReady,-isTransitioning,// Pagination-loadMoreKnowledgeItems,+ loadMoreKnowledgeItems,onActionClick,diff --git a/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts b/src/features/ResourceManager/components/Header/hooks/useNotionImport.tsindex 44b89ee5bf5..abc97f86b35 100644--- a/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts+++ b/src/features/ResourceManager/components/Header/hooks/useNotionImport.ts@@ -1,9 +1,12 @@+import debug from 'debug';import type { TFunction } from 'i18next';import { type ChangeEvent, useCallback, useRef, useState } from 'react';import type { DocumentAction } from '@/store/file/slices/document/action';import { unzipFile } from '@/utils/unzipFile';+const log = debug('resource:notion-import');+interface UseNotionImportOptions {createDocument: DocumentAction['createDocument'];currentFolderId?: string | null;@@ -54,7 +57,7 @@ const useNotionImport = ({// Unzip the filelet files = await unzipFile(file);- console.log(+ log('Extracted files (level 1):',files.map((f) => ({ name: f.name, type: f.type })),);@@ -63,7 +66,7 @@ const useNotionImport = ({const nestedZips = files.filter((f) => f.name.toLowerCase().endsWith('.zip'));if (nestedZips.length > 0) {- console.log(+ log('Found nested ZIPs, extracting...',nestedZips.map((z) => z.name),);@@ -72,7 +75,7 @@ const useNotionImport = ({for (const zipFile of nestedZips) {try {const nestedFiles = await unzipFile(zipFile);- console.log(+ log(`Extracted from ${zipFile.name}:`,nestedFiles.map((f) => ({ name: f.name, type: f.type })),);@@ -86,7 +89,7 @@ const useNotionImport = ({files = allNestedFiles;}- console.log(+ log('All extracted files:',files.map((f) => ({ name: f.name, type: f.type })),);@@ -103,7 +106,7 @@ const useNotionImport = ({t('header.actions.notion.noMarkdownFiles') +` (${t('header.actions.notion.foundFiles', { count: files.length })})`,);- console.warn(+ log('No markdown files found. All files:',files.map((f) => f.name),);diff --git a/src/layout/GlobalProvider/GroupWizardProvider.tsx b/src/layout/GlobalProvider/GroupWizardProvider.tsxnew file mode 100644index 00000000000..36dcd1f21de--- /dev/null+++ b/src/layout/GlobalProvider/GroupWizardProvider.tsx@@ -0,0 +1,117 @@+'use client';++import { ReactNode, Suspense, createContext, lazy, memo, useContext, useState } from 'react';++// Lazy load ChatGroupWizard to avoid bundling it globally+const ChatGroupWizard = lazy(() =>+ import('@/components/ChatGroupWizard').then((mod) => ({ default: mod.ChatGroupWizard })),+);++interface GroupWizardCallbacks {+ onCancel?: () => void;+ onCreateCustom?: (+ selectedAgents: string[],+ hostConfig?: { model?: string; provider?: string },+ enableSupervisor?: boolean,+ ) => Promise<void>;+ onCreateFromTemplate?: (+ templateId: string,+ hostConfig?: { model?: string; provider?: string },+ enableSupervisor?: boolean,+ selectedMemberTitles?: string[],+ ) => Promise<void>;+}++interface GroupWizardContextValue {+ closeGroupWizard: () => void;+ openGroupWizard: (callbacks: GroupWizardCallbacks) => void;+}++const GroupWizardContext = createContext<GroupWizardContextValue | null>(null);++export const useGroupWizard = () => {+ const context = useContext(GroupWizardContext);+ if (!context) {+ throw new Error('useGroupWizard must be used within GroupWizardProvider');+ }+ return context;+};++interface GroupWizardProviderProps {+ children: ReactNode;+}++const GroupWizardProviderInner = memo<GroupWizardProviderProps>(({ children }) => {+ const [isOpen, setIsOpen] = useState(false);+ const [callbacks, setCallbacks] = useState<GroupWizardCallbacks>({});+ const [isLoading, setIsLoading] = useState(false);++ const openGroupWizard = (customCallbacks: GroupWizardCallbacks) => {+ setCallbacks(customCallbacks);+ setIsOpen(true);+ };++ const closeGroupWizard = () => {+ setIsOpen(false);+ setIsLoading(false);+ };++ const handleCreateCustom = async (+ selectedAgents: string[],+ hostConfig?: { model?: string; provider?: string },+ enableSupervisor?: boolean,+ ) => {+ if (callbacks.onCreateCustom) {+ await callbacks.onCreateCustom(selectedAgents, hostConfig, enableSupervisor);+ closeGroupWizard();+ }+ };++ const handleCreateFromTemplate = async (+ templateId: string,+ hostConfig?: { model?: string; provider?: string },+ enableSupervisor?: boolean,+ selectedMemberTitles?: string[],+ ) => {+ if (callbacks.onCreateFromTemplate) {+ setIsLoading(true);+ try {+ await callbacks.onCreateFromTemplate(+ templateId,+ hostConfig,+ enableSupervisor,+ selectedMemberTitles,+ );+ closeGroupWizard();+ } finally {+ setIsLoading(false);+ }+ }+ };++ const handleCancel = () => {+ callbacks.onCancel?.();+ closeGroupWizard();+ };++ return (+ <GroupWizardContext.Provider value={{ closeGroupWizard, openGroupWizard }}>+ {children}+ <Suspense fallback={null}>+ {isOpen && (+ <ChatGroupWizard+ isCreatingFromTemplate={isLoading}+ onCancel={handleCancel}+ onCreateCustom={handleCreateCustom}+ onCreateFromTemplate={handleCreateFromTemplate}+ open={isOpen}+ />+ )}+ </Suspense>+ </GroupWizardContext.Provider>+ );+});++GroupWizardProviderInner.displayName = 'GroupWizardProviderInner';++export const GroupWizardProvider = GroupWizardProviderInner;diff --git a/src/layout/GlobalProvider/index.tsx b/src/layout/GlobalProvider/index.tsxindex 481f2674ac5..532e9faf3cd 100644--- a/src/layout/GlobalProvider/index.tsx+++ b/src/layout/GlobalProvider/index.tsx@@ -10,6 +10,7 @@ import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';import { getAntdLocale } from '@/utils/locale';import AppTheme from './AppTheme';+import { GroupWizardProvider } from './GroupWizardProvider';import ImportSettings from './ImportSettings';import Locale from './Locale';import QueryProvider from './Query';@@ -58,9 +59,11 @@ const GlobalLayout = async ({serverConfig={serverConfig}><QueryProvider>- <LazyMotion features={domMax}>- <LobeAnalyticsProviderWrapper>{children}</LobeAnalyticsProviderWrapper>- </LazyMotion>+ <GroupWizardProvider>+ <LazyMotion features={domMax}>+ <LobeAnalyticsProviderWrapper>{children}</LobeAnalyticsProviderWrapper>+ </LazyMotion>+ </GroupWizardProvider></QueryProvider><StoreInitialization /><Suspense>diff --git a/src/locales/default/common.ts b/src/locales/default/common.tsindex 8fe632cace3..ef8be0d4946 100644--- a/src/locales/default/common.ts+++ b/src/locales/default/common.ts@@ -143,9 +143,14 @@ export default {aiModeEmptyState: '在上方输入框中输入你的问题,开始与 AI 对话',aiModeHint: 'Enter to ask Lobe AI',aiModePlaceholder: '向 AI 提问...',+ aiPainting: 'AI 绘画',askAI: '问 AI',+ askAIHeading: '使用以下功能处理 {{query}}',+ askAIHeadingEmpty: '选择一个 AI 功能',+ askLobeAI: '问 Lobe AI',community: '社区',communitySupport: '社区支持',+ contactViaEmail: '通过邮件联系我们',context: {agent: '助手',community: '社区',@@ -165,7 +170,10 @@ export default {memory: '记忆',navigate: '导航',newAgent: '新建助手',+ newAgentTeam: '新建助手团队',newLibrary: '新建库',+ newPage: '新建文稿',+ newTopic: '在当前助手新建话题',noResults: '未找到相关结果',openSettings: '打开设置',pages: '文稿',@@ -189,7 +197,7 @@ export default {pages: '文稿',plugin: '插件',plugins: '插件',- searchMore: '搜索更多{{type}}',+ searchMore: '搜索更多{{type}}...',searching: '搜索结果',topic: '话题',topics: '话题',diff --git a/src/store/chat/slices/builtinTool/actions/pageAgent.ts b/src/store/chat/slices/builtinTool/actions/pageAgent.tsindex 501a04ecba6..fe7dbba4d3b 100644--- a/src/store/chat/slices/builtinTool/actions/pageAgent.ts+++ b/src/store/chat/slices/builtinTool/actions/pageAgent.ts@@ -1,8 +1,11 @@+import debug from 'debug';import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';import { PageAgentExecutionRuntime } from '@/tools/page-agent/ExecutionRuntime';+const log = debug('page:page-agent');+export interface PageAgentAction {// ============ Batch Operations ============batchUpdate: (id: string, params: any) => Promise<boolean>;@@ -74,19 +77,19 @@ export const pageAgentSlice: StateCreator<> = (set, get) => ({// ============ Batch Operations ============batchUpdate: async (id, params) => {- console.log('batchUpdate', id, params);+ log('batchUpdate', id, params);return true;},// ============ Snapshot Operations ============compareSnapshots: async (id, params) => {- console.log('compareSnapshots', id, params);+ log('compareSnapshots', id, params);return true;},// ============ List Operations ============convertToList: async (id, params) => {- console.log('convertToList', id, params);+ log('convertToList', id, params);return true;},@@ -157,7 +160,7 @@ export const pageAgentSlice: StateCreator<// ============ Image Operations ============cropImage: async (id, params) => {- console.log('cropImage', id, params);+ log('cropImage', id, params);return true;},@@ -226,23 +229,23 @@ export const pageAgentSlice: StateCreator<},deleteSnapshot: async (id, params) => {- console.log('deleteSnapshot', id, params);+ log('deleteSnapshot', id, params);return true;},// ============ Table Operations ============deleteTableColumn: async (id, params) => {- console.log('deleteTableColumn', id, params);+ log('deleteTableColumn', id, params);return true;},deleteTableRow: async (id, params) => {- console.log('deleteTableRow', id, params);+ log('deleteTableRow', id, params);return true;},duplicateNode: async (id, params) => {- console.log('duplicateNode', id, params);+ log('duplicateNode', id, params);return true;},@@ -377,7 +380,7 @@ export const pageAgentSlice: StateCreator<},indentListItem: async (id, params) => {- console.log('indentListItem', id, params);+ log('indentListItem', id, params);return true;},@@ -447,23 +450,23 @@ export const pageAgentSlice: StateCreator<},insertTableColumn: async (id, params) => {- console.log('insertTableColumn', id, params);+ log('insertTableColumn', id, params);return true;},insertTableRow: async (id, params) => {- console.log('insertTableRow', id, params);+ log('insertTableRow', id, params);return true;},listSnapshots: async (id, params) => {- console.log('listSnapshots', id, params);+ log('listSnapshots', id, params);return true;},// ============ Structure Operations ============mergeNodes: async (id, params) => {- console.log('mergeNodes', id, params);+ log('mergeNodes', id, params);return true;},@@ -533,12 +536,12 @@ export const pageAgentSlice: StateCreator<},moveNode: async (id, params) => {- console.log('moveNode', id, params);+ log('moveNode', id, params);return true;},outdentListItem: async (id, params) => {- console.log('outdentListItem', id, params);+ log('outdentListItem', id, params);return true;},@@ -608,42 +611,42 @@ export const pageAgentSlice: StateCreator<},resizeImage: async (id, params) => {- console.log('resizeImage', id, params);+ log('resizeImage', id, params);return true;},restoreSnapshot: async (id, params) => {- console.log('restoreSnapshot', id, params);+ log('restoreSnapshot', id, params);return true;},rotateImage: async (id, params) => {- console.log('rotateImage', id, params);+ log('rotateImage', id, params);return true;},saveSnapshot: async (id, params) => {- console.log('saveSnapshot', id, params);+ log('saveSnapshot', id, params);return true;},setImageAlt: async (id, params) => {- console.log('setImageAlt', id, params);+ log('setImageAlt', id, params);return true;},splitNode: async (id, params) => {- console.log('splitNode', id, params);+ log('splitNode', id, params);return true;},toggleListType: async (id, params) => {- console.log('toggleListType', id, params);+ log('toggleListType', id, params);return true;},unwrapNode: async (id, params) => {- console.log('unwrapNode', id, params);+ log('unwrapNode', id, params);return true;},@@ -712,7 +715,7 @@ export const pageAgentSlice: StateCreator<},wrapNodes: async (id, params) => {- console.log('wrapNodes', id, params);+ log('wrapNodes', id, params);return true;},});diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.tsindex bc068149ee9..e044a67754b 100644--- a/src/store/file/slices/document/action.ts+++ b/src/store/file/slices/document/action.ts@@ -233,11 +233,15 @@ export const createDocumentSlice: StateCreator<replaceTempDocumentWithReal(tempPageId, realPage);set({ isCreatingNew: false, selectedPageId: newPage.id }, false, n('createNewPage/success'));+ // Update URL to navigate to the new page+ updateUrl(newPage.id);+return newPage.id;} catch (error) {console.error('Failed to create page:', error);get().removeTempDocument(tempPageId);set({ isCreatingNew: false, selectedPageId: null }, false, n('createNewPage/error'));+ updateUrl(null);throw error;}},diff --git a/src/tools/page-agent/ExecutionRuntime/index.ts b/src/tools/page-agent/ExecutionRuntime/index.tsindex 8dcc2af19e1..e77c60136e2 100644--- a/src/tools/page-agent/ExecutionRuntime/index.ts+++ b/src/tools/page-agent/ExecutionRuntime/index.ts@@ -7,6 +7,7 @@ import {LITEXML_MODIFY_COMMAND,LITEXML_REMOVE_COMMAND,} from '@lobehub/editor';+import debug from 'debug';import type {BatchUpdateArgs,@@ -79,6 +80,8 @@ import type {WrapNodesState,} from '../type';+const log = debug('page:page-agent');+/*** Page Agent Execution Runtime* Handles the execution logic for all Page Agent (Document) APIs@@ -102,7 +105,7 @@ export class PageAgentExecutionRuntime {* Set the current document ID*/setCurrentDocId(docId: string | undefined) {- console.log('[PageAgentRuntime] Setting current doc ID:', docId);+ log('Setting current doc ID:', docId);this.currentDocId = docId;}@@ -249,7 +252,7 @@ export class PageAgentExecutionRuntime {// Get document in JSON formatconst docJson = editor.getDocument('json') as any;const pageXML = editor.getDocument('litexml') as any;- console.log('[getPageContent] docJson:', JSON.stringify(docJson, null, 2));+ log('docJson:', JSON.stringify(docJson, null, 2));// Prepare state objectconst state: GetPageContentState = {@@ -262,7 +265,7 @@ export class PageAgentExecutionRuntime {// Get markdown format if requestedif (format === 'markdown' || format === 'both') {const markdownRaw = editor.getDocument('markdown');- console.log('[getPageContent] markdownRaw:', markdownRaw);+ log('markdownRaw:', markdownRaw);const markdown = String(markdownRaw || '');state.markdown = markdown;}@@ -600,8 +603,8 @@ export class PageAgentExecutionRuntime {? (args as { nodes: NodeCreate[] }).nodes: [args as NodeCreate];- console.log(- '[createNode] Creating nodes:',+ log(+ 'Creating nodes:',nodeCreates.map((n) => n.type),);@@ -614,11 +617,11 @@ export class PageAgentExecutionRuntime {try {const { commandPayload, litexml } = this.buildNodeCreatePayload(nodeCreate);- console.log('[createNode] Generated LiteXML for', nodeCreate.type, ':', litexml);+ log('Generated LiteXML for', nodeCreate.type, ':', litexml);const success = editor.dispatchCommand(LITEXML_INSERT_COMMAND, commandPayload);- console.log('[createNode] Command dispatched, success:', success);+ log('Command dispatched, success:', success);// Node ID will be assigned by the editor, we track it as 'pending'const createdNodeId = 'pending';@@ -632,7 +635,7 @@ export class PageAgentExecutionRuntime {});} catch (error) {const err = error as Error;- console.error('[createNode] Error creating node:', nodeCreate.type, err.message);+ log('Error creating node:', nodeCreate.type, err.message);errors.push(`${nodeCreate.type}: ${err.message}`);results.push({@@ -742,13 +745,13 @@ export class PageAgentExecutionRuntime {? (args as { nodes: NodeUpdate[] }).nodes: [args as NodeUpdate];- console.log(- '[updateNode] Attempting to update nodes:',+ log(+ 'Attempting to update nodes:',nodeUpdates.map((n) => n.nodeId),);const pageXML = editor.getDocument('litexml') as unknown as string;- console.log('[updateNode] pageXML:', pageXML);+ log('pageXML:', pageXML);const litexmlList: string[] = [];const updatedNodeIds: string[] = [];@@ -771,7 +774,7 @@ export class PageAgentExecutionRuntime {continue;}- console.log('[updateNode] Generated LiteXML for', nodeUpdate.nodeId, ':', result.litexml);+ log('Generated LiteXML for', nodeUpdate.nodeId, ':', result.litexml);litexmlList.push(result.litexml);updatedNodeIds.push(nodeUpdate.nodeId);allUpdates.push(...result.updates);@@ -795,7 +798,7 @@ export class PageAgentExecutionRuntime {litexml: litexmlList,});- console.log('[updateNode] Command dispatched, success:', success);+ log('Command dispatched, success:', success);const updateSummary = allUpdates.length > 0 ? ` (${allUpdates.join(', ')})` : '';const nodesSummary =@@ -878,7 +881,7 @@ export class PageAgentExecutionRuntime {try {const editor = this.getEditor();- console.log('[deleteNode] Deleting node:', args.nodeId);+ log('Deleting node:', args.nodeId);// First verify the node exists in the XMLconst pageXML = editor.getDocument('litexml') as unknown as string;@@ -889,14 +892,14 @@ export class PageAgentExecutionRuntime {throw new Error(`Node ${args.nodeId} not found`);}- console.log('[deleteNode] Found node to delete:', xmlNode.tagName);+ log('Found node to delete:', xmlNode.tagName);// Use LITEXML_REMOVE_COMMAND to remove the nodeconst success = editor.dispatchCommand(LITEXML_REMOVE_COMMAND, {id: args.nodeId,});- console.log('[deleteNode] Command dispatched, success:', success);+ log('Command dispatched, success:', success);return {content: `Successfully deleted ${xmlNode.tagName} node ${args.nodeId}.`,@@ -932,11 +935,11 @@ export class PageAgentExecutionRuntime {}if (!Array.isArray(operations)) {- console.log('[modifyNodes] Converting single operation to array');+ log('Converting single operation to array');operations = [operations as any];}- console.log('[modifyNodes] Processing operations:', operations.length);+ log('Processing operations:', operations.length);// Build the command payload for LITEXML_MODIFY_COMMANDconst commandPayload: Array<@@ -995,9 +998,9 @@ export class PageAgentExecutionRuntime {}// Dispatch all operations at once- console.log('[modifyNodes] Dispatching LITEXML_MODIFY_COMMAND with payload:', commandPayload);+ log('Dispatching LITEXML_MODIFY_COMMAND with payload:', commandPayload);const success = editor.dispatchCommand(LITEXML_MODIFY_COMMAND, commandPayload);- console.log('[modifyNodes] Command dispatched, success:', success);+ log('Command dispatched, success:', success);const successCount = results.filter((r) => r.success).length;const totalCount = results.length;@@ -1269,7 +1272,7 @@ export class PageAgentExecutionRuntime {const editor = this.getEditor();const { searchText, newText, useRegex = false, replaceAll = true, nodeIds } = args;- console.log('[replaceText] Starting replacement:', {+ log('Starting replacement:', {newText,nodeIds,replaceAll,@@ -1298,7 +1301,7 @@ export class PageAgentExecutionRuntime {// Extract nodes from LiteXMLconst nodes = this.extractNodesFromLiteXML(pageXML);- console.log('[replaceText] Found nodes:', nodes.length);+ log('Found nodes:', nodes.length);// Filter nodes if nodeIds is specified and non-empty// Treat empty array as "search all nodes"@@ -1306,7 +1309,7 @@ export class PageAgentExecutionRuntime {const targetNodes = hasNodeFilter ? nodes.filter((node) => nodeIds.includes(node.id)) : nodes;if (hasNodeFilter && targetNodes.length === 0) {- console.log(+ log('[replaceText] Node IDs requested:',nodeIds,'Available IDs:',@@ -1355,7 +1358,7 @@ export class PageAgentExecutionRuntime {const updatedLitexml = `<${node.tagName} ${attributes}>${newContent}</${node.tagName}>`;litexmlUpdates.push(updatedLitexml);- console.log('[replaceText] Updated node:', node.id, 'count:', count);+ log('Updated node:', node.id, 'count:', count);// If not replacing all, stop after first replacementif (!replaceAll) {@@ -1366,11 +1369,11 @@ export class PageAgentExecutionRuntime {// Apply updates if any replacements were madeif (litexmlUpdates.length > 0) {- console.log('[replaceText] Applying updates:', litexmlUpdates.length);+ log('Applying updates:', litexmlUpdates.length);const success = editor.dispatchCommand(LITEXML_APPLY_COMMAND, {litexml: litexmlUpdates,});- console.log('[replaceText] Command dispatched, success:', success);+ log('Command dispatched, success:', success);}// Build response message