Skip to content

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

✨ feat: buildin some tools should save into docs (#10935)

Shinji-Libe4c17d4cc3a
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index 7d7025dd934..d025e90e9d5 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -1,26 +1,21 @@
'use client';
-import { Flexbox, Markdown } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { createStyles } from 'antd-style';
import { memo } from 'react';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
-import { useNotebookStore } from '@/store/notebook';
-import { notebookSelectors } from '@/store/notebook/selectors';
-const useStyles = createStyles(({ token, css }) => ({
+import { DocumentEditorProvider } from './DocumentEditorProvider';
+import EditorCanvas from './EditorCanvas';
+
+const useStyles = createStyles(({ css }) => ({
content: css`
overflow: auto;
flex: 1;
padding-inline: 12px;
`,
- description: css`
- padding: 12px;
- border-block-end: 1px solid ${token.colorBorderSecondary};
- font-size: 13px;
- color: ${token.colorTextSecondary};
- `,
}));
const DocumentBody = memo(() => {
@@ -31,16 +26,16 @@ const DocumentBody = memo(() => {
chatPortalSelectors.portalDocumentId(s),
]);
- const document = useNotebookStore(notebookSelectors.getDocumentById(topicId, documentId));
-
- if (!document) return null;
+ if (!documentId) return null;
return (
- <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
- <div className={styles.content}>
- <Markdown>{document.content || ''}</Markdown>
- </div>
- </Flexbox>
+ <DocumentEditorProvider documentId={documentId} topicId={topicId}>
+ <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
+ <div className={styles.content}>
+ <EditorCanvas />
+ </div>
+ </Flexbox>
+ </DocumentEditorProvider>
);
});
diff --git a/src/features/Portal/Document/DocumentEditorProvider.tsx b/src/features/Portal/Document/DocumentEditorProvider.tsx
new file mode 100644
index 00000000000..3574b88f9ea
--- /dev/null
+++ b/src/features/Portal/Document/DocumentEditorProvider.tsx
@@ -0,0 +1,34 @@
+'use client';
+
+import { useEditor } from '@lobehub/editor/react';
+import { ReactNode, memo } from 'react';
+
+import StoreUpdater from './StoreUpdater';
+import { DocumentEditorProvider as Provider, createStore } from './store';
+
+interface DocumentEditorProviderProps {
+ children: ReactNode;
+ documentId: string | undefined;
+ topicId: string | undefined;
+}
+
+export const DocumentEditorProvider = memo<DocumentEditorProviderProps>(
+ ({ children, documentId, topicId }) => {
+ const editor = useEditor();
+
+ return (
+ <Provider
+ createStore={() =>
+ createStore({
+ documentId,
+ editor,
+ topicId,
+ })
+ }
+ >
+ <StoreUpdater documentId={documentId} topicId={topicId} />
+ {children}
+ </Provider>
+ );
+ },
+);
diff --git a/src/features/Portal/Document/EditorCanvas.tsx b/src/features/Portal/Document/EditorCanvas.tsx
new file mode 100644
index 00000000000..2411d95e2e5
--- /dev/null
+++ b/src/features/Portal/Document/EditorCanvas.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import {
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkPlugin,
+ ReactListPlugin,
+ ReactMathPlugin,
+ ReactTablePlugin,
+} from '@lobehub/editor';
+import { Editor } from '@lobehub/editor/react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useDocumentEditorStore } from './store';
+
+const EditorCanvas = memo(() => {
+ const { t } = useTranslation('file');
+
+ const editor = useDocumentEditorStore((s) => s.editor);
+ const handleContentChange = useDocumentEditorStore((s) => s.handleContentChange);
+
+ if (!editor) return null;
+
+ return (
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ >
+ <Editor
+ content={''}
+ editor={editor}
+ lineEmptyPlaceholder={t('pageEditor.editorPlaceholder')}
+ onTextChange={handleContentChange}
+ placeholder={t('pageEditor.editorPlaceholder')}
+ plugins={[
+ ReactListPlugin,
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkPlugin,
+ ReactTablePlugin,
+ ReactMathPlugin,
+ ]}
+ style={{
+ paddingBottom: 64,
+ }}
+ type={'text'}
+ />
+ </div>
+ );
+});
+
+export default EditorCanvas;
diff --git a/src/features/Portal/Document/StoreUpdater.tsx b/src/features/Portal/Document/StoreUpdater.tsx
new file mode 100644
index 00000000000..d729f2607bf
--- /dev/null
+++ b/src/features/Portal/Document/StoreUpdater.tsx
@@ -0,0 +1,81 @@
+'use client';
+
+import debug from 'debug';
+import { memo, useEffect, useRef, useState } from 'react';
+import { createStoreUpdater } from 'zustand-utils';
+
+import { useNotebookStore } from '@/store/notebook';
+import { notebookSelectors } from '@/store/notebook/selectors';
+
+import { useDocumentEditorStore, useDocumentEditorStoreApi } from './store';
+
+const log = debug('portal:document-store-updater');
+
+interface StoreUpdaterProps {
+ documentId: string | undefined;
+ topicId: string | undefined;
+}
+
+const StoreUpdater = memo<StoreUpdaterProps>(({ documentId, topicId }) => {
+ const storeApi = useDocumentEditorStoreApi();
+ const useStoreUpdater = createStoreUpdater(storeApi);
+
+ const editor = useDocumentEditorStore((s) => s.editor);
+
+ const document = useNotebookStore(notebookSelectors.getDocumentById(topicId, documentId));
+
+ const [editorInit, setEditorInit] = useState(false);
+ const [contentInit, setContentInit] = useState(false);
+ const lastLoadedDocIdRef = useRef<string | undefined>(undefined);
+
+ // Update store with props
+ useStoreUpdater('documentId', documentId);
+ useStoreUpdater('topicId', topicId);
+
+ // Load content into editor when document changes
+ useEffect(() => {
+ if (!editorInit || !editor || !document) return;
+
+ // Skip if already initialized for this document
+ if (contentInit && lastLoadedDocIdRef.current === documentId) return;
+
+ // Reset content init when document changes
+ if (lastLoadedDocIdRef.current !== documentId) {
+ setContentInit(false);
+ }
+
+ queueMicrotask(() => {
+ try {
+ log('Loading content for document:', documentId);
+
+ if (document.content) {
+ editor.setDocument('markdown', document.content);
+ storeApi.setState({
+ lastSavedContent: document.content,
+ });
+ } else {
+ editor.setDocument('markdown', ' ');
+ storeApi.setState({
+ lastSavedContent: '',
+ });
+ }
+
+ lastLoadedDocIdRef.current = documentId;
+ setContentInit(true);
+ } catch (error) {
+ log('Failed to load editor content:', error);
+ }
+ });
+ }, [editorInit, editor, document, documentId, contentInit, storeApi]);
+
+ // Track editor initialization
+ useEffect(() => {
+ if (editor && !editorInit) {
+ setEditorInit(true);
+ }
+ }, [editor, editorInit]);
+
+ return null;
+});
+
+export default StoreUpdater;
diff --git a/src/features/Portal/Document/store/action.ts b/src/features/Portal/Document/store/action.ts
new file mode 100644
index 00000000000..d12e260fd6b
--- /dev/null
+++ b/src/features/Portal/Document/store/action.ts
@@ -0,0 +1,99 @@
+'use client';
+
+import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';
+import debug from 'debug';
+import { debounce } from 'es-toolkit/compat';
+import { StateCreator } from 'zustand';
+
+import { useNotebookStore } from '@/store/notebook';
+
+import { DocumentEditorState, initialDocumentEditorState } from './initialState';
+
+const log = debug('portal:document-editor');
+
+export interface DocumentEditorAction {
+ flushSave: () => void;
+ handleContentChange: () => void;
+ performSave: () => Promise<void>;
+}
+
+export type DocumentEditorStore = DocumentEditorState & DocumentEditorAction;
+
+const createDebouncedSave = (get: () => DocumentEditorStore) =>
+ debounce(
+ async () => {
+ try {
+ await get().performSave();
+ } catch (error) {
+ log('Failed to auto-save:', error);
+ }
+ },
+ EDITOR_DEBOUNCE_TIME,
+ { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },
+ );
+
+export const createDocumentEditorStore: (
+ initState?: Partial<DocumentEditorState>,
+) => StateCreator<DocumentEditorStore> = (initState) => (set, get) => {
+ const debouncedSave = createDebouncedSave(get);
+
+ return {
+ ...initialDocumentEditorState,
+ ...initState,
+
+ flushSave: () => {
+ debouncedSave.flush();
+ },
+
+ handleContentChange: () => {
+ const { editor, lastSavedContent } = get();
+ if (!editor) return;
+
+ try {
+ const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';
+ const contentChanged = markdownContent !== lastSavedContent;
+
+ set({ isDirty: contentChanged });
+
+ if (contentChanged) {
+ debouncedSave();
+ }
+ } catch (error) {
+ log('Failed to update content:', error);
+ }
+ },
+
+ performSave: async () => {
+ const { editor, documentId, topicId, isDirty } = get();
+
+ if (!editor || !documentId || !topicId) return;
+
+ if (!isDirty) return;
+
+ set({ saveStatus: 'saving' });
+
+ try {
+ const currentContent = (editor.getDocument('markdown') as unknown as string) || '';
+
+ await useNotebookStore.getState().updateDocument(
+ {
+ content: currentContent,
+ id: documentId,
+ },
+ topicId,
+ );
+
+ set({
+ isDirty: false,
+ lastSavedContent: currentContent,
+ saveStatus: 'saved',
+ });
+
+ log('Document saved successfully:', documentId);
+ } catch (error) {
+ log('Failed to save document:', error);
+ set({ saveStatus: 'idle' });
+ }
+ },
+ };
+};
diff --git a/src/features/Portal/Document/store/index.ts b/src/features/Portal/Document/store/index.ts
new file mode 100644
index 00000000000..5ec47aa16f7
--- /dev/null
+++ b/src/features/Portal/Document/store/index.ts
@@ -0,0 +1,21 @@
+'use client';
+
+import { StoreApiWithSelector } from '@lobechat/types';
+import { createContext } from 'zustand-utils';
+import { subscribeWithSelector } from 'zustand/middleware';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import { DocumentEditorStore, createDocumentEditorStore } from './action';
+import { DocumentEditorState } from './initialState';
+
+export type { DocumentEditorState } from './initialState';
+
+export const createStore = (initState?: Partial<DocumentEditorState>) =>
+ createWithEqualityFn(subscribeWithSelector(createDocumentEditorStore(initState)), shallow);
+
+export const {
+ useStore: useDocumentEditorStore,
+ useStoreApi: useDocumentEditorStoreApi,
+ Provider: DocumentEditorProvider,
+} = createContext<StoreApiWithSelector<DocumentEditorStore>>();
diff --git a/src/features/Portal/Document/store/initialState.ts b/src/features/Portal/Document/store/initialState.ts
new file mode 100644
index 00000000000..3389de95775
--- /dev/null
+++ b/src/features/Portal/Document/store/initialState.ts
@@ -0,0 +1,20 @@
+'use client';
+
+import { IEditor } from '@lobehub/editor';
+
+export interface DocumentEditorState {
+ documentId: string | undefined;
+ editor?: IEditor;
+ isDirty: boolean;
+ lastSavedContent: string;
+ saveStatus: 'idle' | 'saving' | 'saved';
+ topicId: string | undefined;
+}
+
+export const initialDocumentEditorState: DocumentEditorState = {
+ documentId: undefined,
+ isDirty: false,
+ lastSavedContent: '',
+ saveStatus: 'idle',
+ topicId: undefined,
+};
diff --git a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts b/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts
index 705babd94d6..4657232d178 100644
--- a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts
@@ -3,9 +3,16 @@
*
* Handles web search and page crawling tool calls.
*/
-import { CrawlMultiPagesQuery, SEARCH_SEARXNG_NOT_CONFIG, SearchQuery } from '@lobechat/types';
+import {
+ CrawlMultiPagesQuery,
+ CrawlPluginState,
+ SEARCH_SEARXNG_NOT_CONFIG,
+ SearchQuery,
+} from '@lobechat/types';
import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
+import { CrawlSuccessResult } from '@lobechat/web-crawler';
+import { notebookService } from '@/services/notebook';
import { searchService } from '@/services/search';
import { WebBrowsingApiName, WebBrowsingManifest } from '@/tools/web-browsing';
import { WebBrowsingExecutionRuntime } from '@/tools/web-browsing/ExecutionRuntime';
@@ -102,9 +109,57 @@ class WebBrowsingExecutor extends BaseExecutor<typeof WebBrowsingApiName> {
const result = await runtime.crawlMultiPages(params);
if (result.success) {
+ // Save crawled pages as documents if topicId is available
+ const savedDocuments: Array<{ id: string; title: string; url: string }> = [];
+
+ if (ctx.topicId) {
+ const crawlState = result.state as CrawlPluginState;
+
+ // Create documents for each successfully crawled page
+ await Promise.all(
+ crawlState.results.map(async (crawlResult) => {
+ // Skip if there's an error
+ if ('errorMessage' in crawlResult.data) return;
+
+ const pageData = crawlResult.data as CrawlSuccessResult;
+ if (!pageData.content) return;
+
+ try {
+ const document = await notebookService.createDocument({
+ content: pageData.content,
+ description: pageData.description || `Crawled from ${pageData.url}`,
+ title: pageData.title || pageData.url,
+ topicId: ctx.topicId!,
+ type: 'article',
+ });
+
+ savedDocuments.push({
+ id: document.id,
+ title: document.title || pageData.url,
+ url: pageData.url,
+ });
+ } catch {
+ // Silently ignore document creation errors to not block the main flow
+ }
+ }),
+ );
+ }
+
+ // Append saved documents info to content
+ let content = result.content;
+ if (savedDocuments.length > 0) {
+ const savedDocsInfo = savedDocuments
+ .map((doc) => `- "${doc.title}" (ID: ${doc.id})`)
+ .join('\n');
+ content += `\n\n<saved_documents>\nThe crawled content has been saved as documents for future reference:\n${savedDocsInfo}\n</saved_documents>`;
+ }
+
return {
- content: result.content,
- state: result.state,
+ content,
+ state: {
+ ...result.state,
+ savedDocuments,
+ },
success: true,
};
}