🤯 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: Import from PDF
Rene Wang84350b3ffcf8
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 0d6f35d4131..ec4c4ec82d4 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -76,7 +76,7 @@"pageEditor.editorPlaceholder": "输入文稿内容,按 / 打开命令菜单","pageEditor.empty.createNewDocument": "创建新文稿","pageEditor.empty.title": "选择一个文稿以开始",- "pageEditor.empty.uploadMarkdown": "上传 Markdown 文件",+ "pageEditor.empty.uploadFiles": "上传文件","pageEditor.linkCopied": "链接已复制","pageEditor.menu.copyLink": "复制链接","pageEditor.menu.exportDocument": "导出文稿",diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex 2267a148837..b4f6f40e835 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -125,15 +125,21 @@ const StoreUpdater = memo<StoreUpdaterProps>(storeApi.setState({ lastUpdatedTime: null });+ // Check if editorData is valid and non-empty+ const hasValidEditorData =+ currentPage?.editorData &&+ typeof currentPage.editorData === 'object' &&+ Object.keys(currentPage.editorData).length > 0;+// Load from editorData if available- if (currentPage?.editorData && Object.keys(currentPage.editorData).length > 0) {+ if (hasValidEditorData) {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()) {- log('Loading from content (markdown)');- // Fallback to markdown content (e.g., from Notion imports)+ log('Loading from content - no valid editorData found');+ // Fallback to content (markdown or plain text from parsed files)editor.setDocument('markdown', currentPage.content);storeApi.setState({ wordCount: calculateWordCount(currentPage.content) });} else if (currentPage?.pages) {diff --git a/src/features/PageExplorer/PageExplorerPlaceholder.tsx b/src/features/PageExplorer/PageExplorerPlaceholder.tsxindex 8b98af6ac23..17566483ff3 100644--- a/src/features/PageExplorer/PageExplorerPlaceholder.tsx+++ b/src/features/PageExplorer/PageExplorerPlaceholder.tsx@@ -167,17 +167,79 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(}};- const handleUploadMarkdown = async (file: File) => {+ const handleUploadFile = async (file: File) => {try {setIsUploading(true);- // Read markdown file content- const content = await file.text();+ const fileExtension = file.name.split('.').pop()?.toLowerCase();- // Create page with markdown content- await handleCreateDocument(content, file.name.replace(/\.md$|\.markdown$/i, ''));+ // For markdown files, read content directly+ if (fileExtension === 'md' || fileExtension === 'markdown') {+ const content = await file.text();+ await handleCreateDocument(content, file.name.replace(/\.md$|\.markdown$/i, ''));+ }+ // For PDF and DOCX files, upload to server and parse+ else if (fileExtension === 'pdf' || fileExtension === 'docx') {+ // Create optimistic document first+ const fileName = file.name.replace(/\.(pdf|docx)$/i, '');+ const tempPageId = createOptimisticDocument(fileName);+ setSelectedPageId(tempPageId, false);++ try {+ // Upload file to server+ const uploadResult = await useFileStore.getState().uploadWithProgress({+ file,+ knowledgeBaseId,+ });++ if (!uploadResult) {+ throw new Error('Failed to upload file');+ }++ // Parse file as document on server - this creates a clean document from the file+ const { lambdaClient } = await import('@/libs/trpc/client');+ const parsedDocument = await lambdaClient.document.parseDocument.mutate({+ id: uploadResult.id,+ });++ // Convert to LobeDocument format+ const realPage = {+ content: parsedDocument.content || '',+ createdAt: parsedDocument.createdAt+ ? new Date(parsedDocument.createdAt)+ : new Date(),+ editorData:+ typeof parsedDocument.editorData === 'string'+ ? JSON.parse(parsedDocument.editorData)+ : parsedDocument.editorData || null,+ fileType: parsedDocument.fileType || 'custom/document',+ filename: parsedDocument.filename || fileName,+ id: parsedDocument.id,+ metadata: parsedDocument.metadata || {},+ source: parsedDocument.source || 'document',+ sourceType: parsedDocument.sourceType || 'file',+ title: parsedDocument.title || fileName,+ totalCharCount: parsedDocument.totalCharCount || 0,+ totalLineCount: parsedDocument.totalLineCount || 0,+ updatedAt: parsedDocument.updatedAt+ ? new Date(parsedDocument.updatedAt)+ : new Date(),+ };++ // Replace optimistic with real document+ replaceTempDocumentWithReal(tempPageId, realPage);+ // Update selected page ID to the real page+ setSelectedPageId(parsedDocument.id);+ } catch (error) {+ console.error('Failed to upload and parse file:', error);+ // Remove temp document on error+ useFileStore.getState().removeTempDocument(tempPageId);+ setSelectedPageId(null);+ throw error;+ }+ }} catch (error) {- console.error('Failed to upload markdown:', error);+ console.error('Failed to upload file:', error);} finally {setIsUploading(false);}@@ -212,10 +274,10 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(/></Flexbox>- {/* Upload Markdown File */}+ {/* Upload Files (PDF, DOCX, Markdown) */}<Upload- accept=".md,.markdown"- beforeUpload={handleUploadMarkdown}+ accept=".md,.markdown,.pdf,.docx"+ beforeUpload={handleUploadFile}disabled={isUploading}multiple={false}showUploadList={false}@@ -226,7 +288,7 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(style={{ opacity: isUploading ? 0.5 : 1 }}><span className={styles.actionTitle}>- {isUploading ? 'Uploading...' : t('pageEditor.empty.uploadMarkdown')}+ {isUploading ? 'Uploading...' : t('pageEditor.empty.uploadFiles')}</span><div className={styles.glow} style={{ background: theme.gold }} /><FileTypeIcondiff --git a/src/locales/default/file.ts b/src/locales/default/file.tsindex 08ca6f11d57..4b1fab01f0c 100644--- a/src/locales/default/file.ts+++ b/src/locales/default/file.ts@@ -87,7 +87,7 @@ export default {'pageEditor.empty.createNewDocument': 'Create New Page','pageEditor.empty.importNotion': 'Import from Notion','pageEditor.empty.title': 'Select a page to get started',- 'pageEditor.empty.uploadMarkdown': 'Upload Markdown File',+ 'pageEditor.empty.uploadFiles': 'Upload Files','pageEditor.linkCopied': 'Link copied','pageEditor.menu.copyLink': 'Copy Link','pageEditor.menu.exportDocument': 'Export Page',diff --git a/src/server/routers/lambda/document.ts b/src/server/routers/lambda/document.tsindex 8adde853838..c586a0b796d 100644--- a/src/server/routers/lambda/document.ts+++ b/src/server/routers/lambda/document.ts@@ -98,6 +98,18 @@ export const documentRouter = router({return chain;}),+ parseDocument: documentProcedure+ .input(+ z.object({+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const lobeDocument = await ctx.documentService.parseDocument(input.id);++ return lobeDocument;+ }),+parseFileContent: documentProcedure.input(z.object({diff --git a/src/server/services/document/index.ts b/src/server/services/document/index.tsindex dc030a4a4fb..8187e125b22 100644--- a/src/server/services/document/index.ts+++ b/src/server/services/document/index.ts@@ -223,6 +223,59 @@ export class DocumentService {return result;}+ /**+ * Parse file and create a document for page editor (without page tags)+ */+ async parseDocument(fileId: string): Promise<LobeDocument> {+ const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(fileId);++ const logPrefix = `[${file.name}]`;+ log(`${logPrefix} 开始解析文件为文档, 路径: ${filePath}`);++ try {+ // 使用loadFile加载文件内容+ const fileDocument = await loadFile(filePath);++ log(`${logPrefix} 文件解析成功 %O`, {+ fileType: fileDocument.fileType,+ size: fileDocument.content.length,+ });++ // Extract title from metadata or use file name (remove extension)+ const title =+ fileDocument.metadata?.title ||+ file.name.replace(/\.(pdf|docx?|md|markdown)$/i, '') ||+ 'Untitled';++ // Clean up content - remove <page> tags if present+ let cleanContent = fileDocument.content;+ if (cleanContent.includes('<page')) {+ cleanContent = cleanContent.replace(/<page[^>]*>([\s\S]*?)<\/page>/g, '$1').trim();+ }++ const document = await this.documentModel.create({+ content: cleanContent,+ fileId,+ fileType: 'custom/document',+ filename: title,+ metadata: fileDocument.metadata,+ parentId: file.parentId,+ source: file.url,+ sourceType: 'file',+ title,+ totalCharCount: cleanContent.length,+ totalLineCount: cleanContent.split('\n').length,+ });++ return document as LobeDocument;+ } catch (error) {+ console.error(`${logPrefix} 文件解析失败:`, error);+ throw error;+ } finally {+ cleanup();+ }+ }+/*** 解析文件内容*@@ -242,16 +295,23 @@ export class DocumentService {size: fileDocument.content.length,});+ // Extract title from metadata or use file name (remove extension)+ const title =+ fileDocument.metadata?.title ||+ file.name.replace(/\.(pdf|docx?|md|markdown)$/i, '') ||+ 'Untitled';+const document = await this.documentModel.create({content: fileDocument.content,fileId,- fileType: file.fileType,+ fileType: 'custom/document', // Use custom/document for all parsed files+ filename: title,metadata: fileDocument.metadata,pages: fileDocument.pages,parentId: file.parentId,source: file.url,sourceType: 'file',- title: fileDocument.metadata?.title,+ title,totalCharCount: fileDocument.totalCharCount,totalLineCount: fileDocument.totalLineCount,});