🤯 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: Create Pages in Knowledge Base (#9895)
René Wangf46edeb2d12d
diff --git a/locales/ar/common.json b/locales/ar/common.jsonindex a8e1e20dfcb..93253f701ae 100644--- a/locales/ar/common.json+++ b/locales/ar/common.json@@ -286,6 +286,7 @@"oauth": "تسجيل الدخول SSO","officialSite": "الموقع الرسمي","ok": "موافق",+ "or": "أو","password": "كلمة المرور","pin": "تثبيت في الأعلى","pinOff": "إلغاء التثبيت",diff --git a/locales/ar/file.json b/locales/ar/file.jsonindex d7cd2353840..6c7f50e79a3 100644--- a/locales/ar/file.json+++ b/locales/ar/file.json@@ -1,5 +1,7 @@{- "desc": "إدارة معرفتك",+ "addKnowledge": "إضافة معرفة",+ "addPage": "إنشاء مستند",+ "desc": "نظّم معرفتك في العمل، الدراسة والحياة.","detail": {"basic": {"createdAt": "تاريخ الإنشاء",@@ -21,6 +23,44 @@"embeddingStatus": "تحويل إلى متجهات"}},+ "documentEditor": {+ "addIcon": "إضافة أيقونة",+ "autoSaveMessage": "يتم حفظ المستند تلقائيًا، لا حاجة للحفظ اليدوي",+ "chooseIcon": "اختر أيقونة",+ "deleteConfirm": {+ "content": "سيتم حذف هذا المستند، ولا يمكن استعادته بعد الحذف. يرجى توخي الحذر.",+ "title": "حذف المستند"+ },+ "deleteError": "فشل في حذف المستند",+ "deleteSuccess": "تم حذف المستند بنجاح",+ "editedAt": "آخر تعديل في {{time}}",+ "editedBy": "آخر من عدّل: {{name}}",+ "editorPlaceholder": "أدخل محتوى المستند، اضغط / لفتح قائمة الأوامر",+ "empty": {+ "createNewDocument": "إنشاء مستند جديد",+ "title": "اختر مستندًا للبدء",+ "uploadMarkdown": "رفع ملف Markdown"+ },+ "linkCopied": "تم نسخ الرابط",+ "menu": {+ "copyLink": "نسخ الرابط",+ "exportDocument": "تصدير المستند",+ "importDocument": "استيراد مستند",+ "pin": "تثبيت المستند"+ },+ "saving": "جارٍ الحفظ...",+ "titlePlaceholder": "بدون عنوان",+ "wordCount": "{{wordCount}} كلمة"+ },+ "documentList": {+ "copyContent": "نسخ المحتوى الكامل",+ "documentCount": "إجمالي {{count}} مستند",+ "duplicate": "إنشاء نسخة",+ "empty": "لا توجد مستندات حاليًا، انقر على الزر أعلاه لإنشاء أول مستند لك",+ "noResults": "لم يتم العثور على مستندات مطابقة",+ "selectNote": "اختر مستندًا للبدء في التحرير",+ "untitled": "بدون عنوان"+ },"empty": "لا توجد ملفات/مجلدات تم تحميلها بعد","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "رفع ملف","uploadFolder": "رفع مجلد"},+ "newDocumentButton": "مستند جديد",+ "newNoteDialog": {+ "cancel": "إلغاء",+ "editTitle": "تحرير المستند",+ "emptyContent": "لا يمكن أن يكون محتوى المستند فارغًا",+ "loadError": "فشل في تحميل المستند، يرجى المحاولة مرة أخرى",+ "loading": "جارٍ التحميل...",+ "save": "حفظ",+ "saveError": "فشل في حفظ المستند، يرجى المحاولة مرة أخرى",+ "saveSuccess": "تم حفظ المستند بنجاح",+ "title": "مستند جديد",+ "updateSuccess": "تم تحديث المستند بنجاح"+ },"uploadButton": "رفع"},+ "home": {+ "getStarted": "ابدأ الآن",+ "greeting": "ابدأ",+ "quickActions": "إجراءات سريعة",+ "recentDocuments": "المستندات الأخيرة",+ "recentFiles": "الملفات الأخيرة",+ "subtitle": "مرحبًا بك في قاعدة المعرفة، ابدأ من هنا لإدارة مستنداتك وملاحظاتك",+ "uploadEntries": {+ "files": {+ "title": "رفع ملفات"+ },+ "folder": {+ "title": "رفع مجلد"+ },+ "knowledgeBase": {+ "title": "قاعدة معرفة جديدة"+ },+ "newDocument": {+ "title": "مستند جديد"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "سيتم حذف هذه المكتبة المعرفية، ولن يتم حذف الملفات الموجودة بها، بل ستنتقل إلى جميع الملفات. بعد حذف المكتبة المعرفية، لن يمكن استعادتها، يرجى توخي الحذر.",@@ -38,6 +113,10 @@"new": "إنشاء مكتبة معرفية جديدة","title": "المكتبة المعرفية"},+ "menu": {+ "allDocuments": "جميع المستندات",+ "allFiles": "جميع الملفات"+ },"networkError": "فشل في الحصول على قاعدة المعرفة، يرجى التحقق من اتصال الشبكة ثم إعادة المحاولة","notSupportGuide": {"desc": "الوضع الحالي للنشر هو وضع قاعدة بيانات العميل، ولا يمكن استخدام وظيفة إدارة الملفات. يرجى التبديل إلى <1>وضع نشر قاعدة بيانات الخادم</1>، أو استخدام <3>LobeChat Cloud</3> مباشرة.",@@ -61,12 +140,16 @@"downloadFile": "تحميل الملف","unsupportedFileAndContact": "هذا التنسيق من الملفات غير مدعوم للمعاينة عبر الإنترنت، إذا كان لديك طلب للمعاينة، فلا تتردد في <1>إبلاغنا</1>"},+ "searchDocumentPlaceholder": "ابحث في المستندات","searchFilePlaceholder": "بحث عن ملف","tab": {- "all": "جميع الملفات",+ "all": "الكل","audios": "الصوتيات","documents": "المستندات",+ "home": "الرئيسية","images": "الصور",+ "moreTypes": "أنواع أخرى",+ "pages": "المستندات","videos": "الفيديوهات","websites": "المواقع"},diff --git a/locales/bg-BG/common.json b/locales/bg-BG/common.jsonindex 559ebcbe706..c7a9eae7291 100644--- a/locales/bg-BG/common.json+++ b/locales/bg-BG/common.json@@ -286,6 +286,7 @@"oauth": "SSO Вход","officialSite": "Официален сайт","ok": "Добре",+ "or": "или","password": "Парола","pin": "Закачи","pinOff": "Откачи",diff --git a/locales/bg-BG/file.json b/locales/bg-BG/file.jsonindex 18c56963110..066f3808c4d 100644--- a/locales/bg-BG/file.json+++ b/locales/bg-BG/file.json@@ -1,5 +1,7 @@{- "desc": "Управлявайте своите знания",+ "addKnowledge": "Добавяне на знание",+ "addPage": "Създаване на документ",+ "desc": "Управлявайте знанията си за работа, учене и живот.","detail": {"basic": {"createdAt": "Дата на създаване",@@ -21,6 +23,44 @@"embeddingStatus": "Векторизация"}},+ "documentEditor": {+ "addIcon": "Добавяне на икона",+ "autoSaveMessage": "Документът се запазва автоматично, не е необходимо ръчно запазване",+ "chooseIcon": "Избор на икона",+ "deleteConfirm": {+ "content": "Документът ще бъде изтрит и няма да може да бъде възстановен. Моля, бъдете внимателни.",+ "title": "Изтриване на документ"+ },+ "deleteError": "Неуспешно изтриване на документа",+ "deleteSuccess": "Документът беше изтрит успешно",+ "editedAt": "Последна редакция на {{time}}",+ "editedBy": "Последно редактиран от {{name}}",+ "editorPlaceholder": "Въведете съдържанието на документа, натиснете / за меню с команди",+ "empty": {+ "createNewDocument": "Създаване на нов документ",+ "title": "Изберете документ, за да започнете",+ "uploadMarkdown": "Качване на Markdown файл"+ },+ "linkCopied": "Връзката е копирана",+ "menu": {+ "copyLink": "Копиране на връзка",+ "exportDocument": "Експортиране на документ",+ "importDocument": "Импортиране на документ",+ "pin": "Закачане на документа"+ },+ "saving": "Запазване...",+ "titlePlaceholder": "Без заглавие",+ "wordCount": "{{wordCount}} думи"+ },+ "documentList": {+ "copyContent": "Копиране на цялото съдържание",+ "documentCount": "Общо {{count}} документа",+ "duplicate": "Създаване на копие",+ "empty": "Все още няма документи. Натиснете бутона по-горе, за да създадете първия си документ",+ "noResults": "Няма намерени съвпадащи документи",+ "selectNote": "Изберете документ, за да започнете редактиране",+ "untitled": "Без заглавие"+ },"empty": "Няма качени файлове/папки","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Качване на файл","uploadFolder": "Качване на папка"},+ "newDocumentButton": "Нов документ",+ "newNoteDialog": {+ "cancel": "Отказ",+ "editTitle": "Редактиране на документ",+ "emptyContent": "Съдържанието на документа не може да бъде празно",+ "loadError": "Неуспешно зареждане на документа, моля опитайте отново",+ "loading": "Зареждане...",+ "save": "Запази",+ "saveError": "Неуспешно запазване на документа, моля опитайте отново",+ "saveSuccess": "Документът беше запазен успешно",+ "title": "Нов документ",+ "updateSuccess": "Документът беше обновен успешно"+ },"uploadButton": "Качване"},+ "home": {+ "getStarted": "Започнете",+ "greeting": "Начало",+ "quickActions": "Бързи действия",+ "recentDocuments": "Скорошни документи",+ "recentFiles": "Скорошни файлове",+ "subtitle": "Добре дошли в базата знания. Започнете да управлявате вашите документи оттук",+ "uploadEntries": {+ "files": {+ "title": "Качване на файлове"+ },+ "folder": {+ "title": "Качване на папка"+ },+ "knowledgeBase": {+ "title": "Създай база знания"+ },+ "newDocument": {+ "title": "Създай нов документ"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Сигурни ли сте, че искате да изтриете тази база знания? Файловете в нея няма да бъдат изтрити, а ще бъдат преместени в общите файлове. След изтриването на базата знания, тя не може да бъде възстановена, моля, действайте внимателно.",@@ -38,6 +113,10 @@"new": "Нова база знания","title": "База знания"},+ "menu": {+ "allDocuments": "Всички документи",+ "allFiles": "Всички файлове"+ },"networkError": "Неуспешно получаване на базата от знания, моля, проверете интернет връзката и опитайте отново","notSupportGuide": {"desc": "Текущият инстанс е в режим на клиентска база данни и не поддържа функцията за управление на файлове. Моля, превключете на <1>режим на сървърна база данни</1> или използвайте директно <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Изтеглете файла","unsupportedFileAndContact": "Този формат на файла не поддържа онлайн преглед. Ако имате нужда от преглед, моля, <1>свържете се с нас</1>."},+ "searchDocumentPlaceholder": "Търсене на документи","searchFilePlaceholder": "Търсене на файл","tab": {- "all": "Всички файлове",+ "all": "Всички","audios": "Аудио","documents": "Документи",+ "home": "Начало","images": "Снимки",+ "moreTypes": "Още типове",+ "pages": "Документи","videos": "Видеа","websites": "Уебсайтове"},diff --git a/locales/de-DE/common.json b/locales/de-DE/common.jsonindex 3e7ce7f8f85..ed65c3a143e 100644--- a/locales/de-DE/common.json+++ b/locales/de-DE/common.json@@ -286,6 +286,7 @@"oauth": "SSO-Anmeldung","officialSite": "Offizielle Website","ok": "OK",+ "or": "oder","password": "Passwort","pin": "Anheften","pinOff": "Anheften aufheben",diff --git a/locales/de-DE/file.json b/locales/de-DE/file.jsonindex c39e03655ac..f796fe9da92 100644--- a/locales/de-DE/file.json+++ b/locales/de-DE/file.json@@ -1,5 +1,7 @@{- "desc": "Verwalte dein Wissen",+ "addKnowledge": "Wissen hinzufügen",+ "addPage": "Dokument erstellen",+ "desc": "Verwalte dein Wissen für Arbeit, Studium und Alltag.","detail": {"basic": {"createdAt": "Erstellungszeit",@@ -21,6 +23,44 @@"embeddingStatus": "Vektorisierung"}},+ "documentEditor": {+ "addIcon": "Symbol hinzufügen",+ "autoSaveMessage": "Das Dokument wird automatisch gespeichert, ein manuelles Speichern ist nicht erforderlich.",+ "chooseIcon": "Symbol auswählen",+ "deleteConfirm": {+ "content": "Dieses Dokument wird gelöscht und kann danach nicht wiederhergestellt werden. Bitte seien Sie vorsichtig.",+ "title": "Dokument löschen"+ },+ "deleteError": "Löschen des Dokuments fehlgeschlagen",+ "deleteSuccess": "Dokument erfolgreich gelöscht",+ "editedAt": "Zuletzt bearbeitet am {{time}}",+ "editedBy": "Zuletzt bearbeitet von {{name}}",+ "editorPlaceholder": "Geben Sie den Dokumentinhalt ein, drücken Sie / für das Befehlsmenü",+ "empty": {+ "createNewDocument": "Neues Dokument erstellen",+ "title": "Wählen Sie ein Dokument, um zu beginnen",+ "uploadMarkdown": "Markdown-Datei hochladen"+ },+ "linkCopied": "Link wurde kopiert",+ "menu": {+ "copyLink": "Link kopieren",+ "exportDocument": "Dokument exportieren",+ "importDocument": "Dokument importieren",+ "pin": "Dokument anheften"+ },+ "saving": "Speichern...",+ "titlePlaceholder": "Ohne Titel",+ "wordCount": "{{wordCount}} Wörter"+ },+ "documentList": {+ "copyContent": "Gesamten Inhalt kopieren",+ "documentCount": "Insgesamt {{count}} Dokumente",+ "duplicate": "Kopie erstellen",+ "empty": "Noch keine Dokumente vorhanden. Klicken Sie oben, um Ihr erstes Dokument zu erstellen.",+ "noResults": "Keine passenden Dokumente gefunden",+ "selectNote": "Wählen Sie ein Dokument zum Bearbeiten",+ "untitled": "Ohne Titel"+ },"empty": "Keine hochgeladenen Dateien/Ordner vorhanden","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Datei hochladen","uploadFolder": "Ordner hochladen"},+ "newDocumentButton": "Neues Dokument",+ "newNoteDialog": {+ "cancel": "Abbrechen",+ "editTitle": "Dokument bearbeiten",+ "emptyContent": "Der Dokumentinhalt darf nicht leer sein",+ "loadError": "Fehler beim Laden des Dokuments. Bitte versuchen Sie es erneut.",+ "loading": "Wird geladen...",+ "save": "Speichern",+ "saveError": "Fehler beim Speichern des Dokuments. Bitte versuchen Sie es erneut.",+ "saveSuccess": "Dokument erfolgreich gespeichert",+ "title": "Neues Dokument",+ "updateSuccess": "Dokument erfolgreich aktualisiert"+ },"uploadButton": "Hochladen"},+ "home": {+ "getStarted": "Loslegen",+ "greeting": "Loslegen",+ "quickActions": "Schnellaktionen",+ "recentDocuments": "Kürzlich verwendete Dokumente",+ "recentFiles": "Kürzlich verwendete Dateien",+ "subtitle": "Willkommen im Wissensspeicher. Beginnen Sie hier mit der Verwaltung Ihrer Dokumente.",+ "uploadEntries": {+ "files": {+ "title": "Dateien hochladen"+ },+ "folder": {+ "title": "Ordner hochladen"+ },+ "knowledgeBase": {+ "title": "Neue Wissensdatenbank"+ },+ "newDocument": {+ "title": "Neues Dokument"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Die Wissensdatenbank wird gelöscht, die darin enthaltenen Dateien werden nicht gelöscht, sondern in den gesamten Dateien verschoben. Nach dem Löschen der Wissensdatenbank kann sie nicht wiederhergestellt werden, bitte vorsichtig vorgehen.",@@ -38,6 +113,10 @@"new": "Neue Wissensdatenbank","title": "Wissensdatenbank"},+ "menu": {+ "allDocuments": "Alle Dokumente",+ "allFiles": "Alle Dateien"+ },"networkError": "Fehler beim Abrufen der Wissensdatenbank. Bitte überprüfen Sie Ihre Netzwerkverbindung und versuchen Sie es erneut.","notSupportGuide": {"desc": "Die aktuelle Bereitstellung ist im Client-Datenbankmodus und unterstützt keine Dateiverwaltungsfunktionen. Bitte wechseln Sie zu <1>Server-Datenbank-Bereitstellungsmodus</1> oder verwenden Sie direkt <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Datei herunterladen","unsupportedFileAndContact": "Dieses Dateiformat wird derzeit nicht für die Online-Vorschau unterstützt. Wenn Sie eine Vorschau wünschen, können Sie uns gerne <1>Feedback geben</1>."},+ "searchDocumentPlaceholder": "Dokumente durchsuchen","searchFilePlaceholder": "Datei suchen","tab": {- "all": "Alle Dateien",+ "all": "Alle","audios": "Audio","documents": "Dokumente",+ "home": "Startseite","images": "Bilder",+ "moreTypes": "Weitere Typen",+ "pages": "Dokumente","videos": "Videos","websites": "Webseiten"},diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 6209d0402ea..d50bebcea03 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -286,6 +286,7 @@"oauth": "SSO Login","officialSite": "Official Website","ok": "OK",+ "or": "or","password": "Password","pin": "Pin","pinOff": "Unpin",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex cdead05eb75..4c5f36403c7 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -1,5 +1,7 @@{- "desc": "Manage your knowledge",+ "addKnowledge": "Add Knowledge",+ "addPage": "Create Document",+ "desc": "Manage your knowledge for work, study, and life.","detail": {"basic": {"createdAt": "Creation Time",@@ -21,6 +23,44 @@"embeddingStatus": "embedding"}},+ "documentEditor": {+ "addIcon": "Add Icon",+ "autoSaveMessage": "Document auto-saves, no manual save needed",+ "chooseIcon": "Choose Icon",+ "deleteConfirm": {+ "content": "This document will be deleted permanently and cannot be recovered. Please proceed with caution.",+ "title": "Delete Document"+ },+ "deleteError": "Failed to delete document",+ "deleteSuccess": "Document deleted successfully",+ "editedAt": "Edited {{time}}",+ "editedBy": "Edited by {{name}}",+ "editorPlaceholder": "Type document content, press / to open command menu",+ "empty": {+ "createNewDocument": "Create New Document",+ "title": "Select a document to start",+ "uploadMarkdown": "Upload Markdown File"+ },+ "linkCopied": "Link copied",+ "menu": {+ "copyLink": "Copy Link",+ "exportDocument": "Export Document",+ "importDocument": "Import Document",+ "pin": "Pin Document"+ },+ "saving": "Saving...",+ "titlePlaceholder": "Untitled",+ "wordCount": "{{wordCount}} words"+ },+ "documentList": {+ "copyContent": "Copy All",+ "documentCount": "Total {{count}} documents",+ "duplicate": "Duplicate",+ "empty": "No documents yet. Click the button above to create your first one.",+ "noResults": "No matching documents found.",+ "selectNote": "Select a document to start editing.",+ "untitled": "Untitled"+ },"empty": "No files or folders have been uploaded yet.","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Upload File","uploadFolder": "Upload Folder"},+ "newDocumentButton": "New Document",+ "newNoteDialog": {+ "cancel": "Cancel",+ "editTitle": "Edit Document",+ "emptyContent": "Document content cannot be empty.",+ "loadError": "Failed to load the document. Please try again.",+ "loading": "Loading...",+ "save": "Save",+ "saveError": "Failed to save the document. Please try again.",+ "saveSuccess": "Document saved successfully.",+ "title": "New Document",+ "updateSuccess": "Document updated successfully."+ },"uploadButton": "Upload"},+ "home": {+ "getStarted": "Get Started",+ "greeting": "Get Started",+ "quickActions": "Quick Actions",+ "recentDocuments": "Recent Documents",+ "recentFiles": "Recent Files",+ "subtitle": "Welcome to your knowledge base. Start managing your documents here.",+ "uploadEntries": {+ "files": {+ "title": "Upload Files"+ },+ "folder": {+ "title": "Upload Folder"+ },+ "knowledgeBase": {+ "title": "Create Knowledge Base"+ },+ "newDocument": {+ "title": "Create Document"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "You are about to delete this knowledge base. The files within will not be deleted and will be moved to All Files. Once deleted, the knowledge base cannot be recovered. Please proceed with caution.",@@ -38,6 +113,10 @@"new": "New Knowledge Base","title": "Knowledge Base"},+ "menu": {+ "allDocuments": "All Documents",+ "allFiles": "All Files"+ },"networkError": "Failed to retrieve the knowledge base. Please check your network connection and try again.","notSupportGuide": {"desc": "The current deployment instance is in client database mode, and file management features are not available. Please switch to <1>server database deployment mode</1>, or use <3>LobeChat Cloud</3> directly.",@@ -61,12 +140,16 @@"downloadFile": "Download File","unsupportedFileAndContact": "This file format is not currently supported for online preview. If you have a request for previewing, feel free to <1>contact us</1>."},+ "searchDocumentPlaceholder": "Search documents","searchFilePlaceholder": "Search Files","tab": {- "all": "All Files",+ "all": "All","audios": "Audio","documents": "Documents",+ "home": "Home","images": "Images",+ "moreTypes": "More Types",+ "pages": "Pages","videos": "Videos","websites": "Websites"},diff --git a/locales/es-ES/common.json b/locales/es-ES/common.jsonindex 5e948a02234..c8ed9e60444 100644--- a/locales/es-ES/common.json+++ b/locales/es-ES/common.json@@ -286,6 +286,7 @@"oauth": "Inicio de sesión SSO","officialSite": "Sitio oficial","ok": "Aceptar",+ "or": "o","password": "Contraseña","pin": "Fijar","pinOff": "Quitar fijación",diff --git a/locales/es-ES/file.json b/locales/es-ES/file.jsonindex 4f4ee670f94..728aab41ef9 100644--- a/locales/es-ES/file.json+++ b/locales/es-ES/file.json@@ -1,5 +1,7 @@{- "desc": "Gestiona tu conocimiento",+ "addKnowledge": "Agregar conocimiento",+ "addPage": "Crear documento",+ "desc": "Gestiona tus conocimientos de trabajo, estudio y vida.","detail": {"basic": {"createdAt": "Fecha de creación",@@ -21,6 +23,44 @@"embeddingStatus": "Vectorización"}},+ "documentEditor": {+ "addIcon": "Agregar ícono",+ "autoSaveMessage": "El documento se guarda automáticamente, no es necesario guardarlo manualmente",+ "chooseIcon": "Elegir ícono",+ "deleteConfirm": {+ "content": "Estás a punto de eliminar este documento. Una vez eliminado, no se podrá recuperar. Procede con precaución.",+ "title": "Eliminar documento"+ },+ "deleteError": "Error al eliminar el documento",+ "deleteSuccess": "Documento eliminado con éxito",+ "editedAt": "Última edición el {{time}}",+ "editedBy": "Editado por última vez por {{name}}",+ "editorPlaceholder": "Escribe el contenido del documento, pulsa / para abrir el menú de comandos",+ "empty": {+ "createNewDocument": "Crear nuevo documento",+ "title": "Selecciona un documento para comenzar",+ "uploadMarkdown": "Subir archivo Markdown"+ },+ "linkCopied": "Enlace copiado",+ "menu": {+ "copyLink": "Copiar enlace",+ "exportDocument": "Exportar documento",+ "importDocument": "Importar documento",+ "pin": "Fijar documento"+ },+ "saving": "Guardando...",+ "titlePlaceholder": "Sin título",+ "wordCount": "{{wordCount}} palabras"+ },+ "documentList": {+ "copyContent": "Copiar todo el contenido",+ "documentCount": "Total de {{count}} documentos",+ "duplicate": "Crear una copia",+ "empty": "No hay documentos. Haz clic en el botón de arriba para crear tu primer documento",+ "noResults": "No se encontraron documentos coincidentes",+ "selectNote": "Selecciona un documento para comenzar a editar",+ "untitled": "Sin título"+ },"empty": "No hay archivos/carpetas subidos aún","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Subir archivo","uploadFolder": "Subir carpeta"},+ "newDocumentButton": "Nuevo documento",+ "newNoteDialog": {+ "cancel": "Cancelar",+ "editTitle": "Editar documento",+ "emptyContent": "El contenido del documento no puede estar vacío",+ "loadError": "Error al cargar el documento, por favor intenta de nuevo",+ "loading": "Cargando...",+ "save": "Guardar",+ "saveError": "Error al guardar el documento, por favor intenta de nuevo",+ "saveSuccess": "Documento guardado con éxito",+ "title": "Nuevo documento",+ "updateSuccess": "Documento actualizado con éxito"+ },"uploadButton": "Subir"},+ "home": {+ "getStarted": "Comenzar",+ "greeting": "Comenzar",+ "quickActions": "Acciones rápidas",+ "recentDocuments": "Documentos recientes",+ "recentFiles": "Archivos recientes",+ "subtitle": "Bienvenido a tu base de conocimientos. Comienza aquí a gestionar tus documentos y notas",+ "uploadEntries": {+ "files": {+ "title": "Subir archivos"+ },+ "folder": {+ "title": "Subir carpeta"+ },+ "knowledgeBase": {+ "title": "Nueva base de conocimientos"+ },+ "newDocument": {+ "title": "Nuevo documento"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Estás a punto de eliminar esta base de conocimientos. Los archivos no se eliminarán, se moverán a Todos los archivos. Una vez eliminada, la base de conocimientos no se podrá recuperar, por favor actúa con precaución.",@@ -38,6 +113,10 @@"new": "Nueva base de conocimientos","title": "Base de conocimientos"},+ "menu": {+ "allDocuments": "Todos los documentos",+ "allFiles": "Todos los archivos"+ },"networkError": "Error al obtener la base de conocimientos, por favor verifica la conexión a internet y vuelve a intentarlo","notSupportGuide": {"desc": "La instancia de despliegue actual está en modo de base de datos cliente, no se puede utilizar la función de gestión de archivos. Por favor, cambia a <1>modo de despliegue de base de datos en servidor</1>, o utiliza directamente <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Descargar archivo","unsupportedFileAndContact": "Este formato de archivo no es compatible con la vista previa en línea. Si desea solicitar una vista previa, no dude en <1>contactarnos</1>."},+ "searchDocumentPlaceholder": "Buscar documentos","searchFilePlaceholder": "Buscar archivo","tab": {- "all": "Todos los archivos",+ "all": "Todo","audios": "Audios","documents": "Documentos",+ "home": "Inicio","images": "Imágenes",+ "moreTypes": "Más tipos",+ "pages": "Documentos","videos": "Videos","websites": "Sitios web"},diff --git a/locales/fa-IR/common.json b/locales/fa-IR/common.jsonindex 4fbf75b5ea6..32aaa64a81a 100644--- a/locales/fa-IR/common.json+++ b/locales/fa-IR/common.json@@ -286,6 +286,7 @@"oauth": "ورود با SSO","officialSite": "وبسایت رسمی","ok": "تأیید",+ "or": "یا","password": "رمز عبور","pin": "سنجاق کردن","pinOff": "لغو سنجاق کردن",diff --git a/locales/fa-IR/file.json b/locales/fa-IR/file.jsonindex 7202b1cff98..d3b3a136b56 100644--- a/locales/fa-IR/file.json+++ b/locales/fa-IR/file.json@@ -1,5 +1,7 @@{- "desc": "مدیریت دانش شما",+ "addKnowledge": "افزودن دانش",+ "addPage": "ایجاد سند",+ "desc": "مدیریت دانش کاری، تحصیلی و زندگی شما.","detail": {"basic": {"createdAt": "زمان ایجاد",@@ -21,6 +23,44 @@"embeddingStatus": "برداریسازی"}},+ "documentEditor": {+ "addIcon": "افزودن آیکون",+ "autoSaveMessage": "سند بهصورت خودکار ذخیره میشود، نیازی به ذخیره دستی نیست",+ "chooseIcon": "انتخاب آیکون",+ "deleteConfirm": {+ "content": "در شرف حذف این سند هستید. پس از حذف، قابل بازیابی نخواهد بود. لطفاً با احتیاط عمل کنید.",+ "title": "حذف سند"+ },+ "deleteError": "حذف سند ناموفق بود",+ "deleteSuccess": "سند با موفقیت حذف شد",+ "editedAt": "آخرین ویرایش در {{time}}",+ "editedBy": "آخرین ویرایش توسط {{name}}",+ "editorPlaceholder": "محتوای سند را وارد کنید، برای باز کردن منوی دستورات / را فشار دهید",+ "empty": {+ "createNewDocument": "ایجاد سند جدید",+ "title": "برای شروع یک سند انتخاب کنید",+ "uploadMarkdown": "بارگذاری فایل Markdown"+ },+ "linkCopied": "پیوند کپی شد",+ "menu": {+ "copyLink": "کپی پیوند",+ "exportDocument": "صادرات سند",+ "importDocument": "وارد کردن سند",+ "pin": "سند را سنجاق کن"+ },+ "saving": "در حال ذخیرهسازی...",+ "titlePlaceholder": "بدون عنوان",+ "wordCount": "{{wordCount}} کلمه"+ },+ "documentList": {+ "copyContent": "کپی کل محتوا",+ "documentCount": "مجموع {{count}} سند",+ "duplicate": "ایجاد نسخه مشابه",+ "empty": "هیچ سندی موجود نیست، برای ایجاد اولین سند خود روی دکمه بالا کلیک کنید",+ "noResults": "سندی مطابق با جستجو یافت نشد",+ "selectNote": "برای ویرایش یک سند انتخاب کنید",+ "untitled": "بدون عنوان"+ },"empty": "هیچ فایل/پوشهای بارگذاری نشده است","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "بارگذاری فایل","uploadFolder": "بارگذاری پوشه"},+ "newDocumentButton": "سند جدید",+ "newNoteDialog": {+ "cancel": "لغو",+ "editTitle": "ویرایش سند",+ "emptyContent": "محتوای سند نمیتواند خالی باشد",+ "loadError": "بارگذاری سند ناموفق بود، لطفاً دوباره تلاش کنید",+ "loading": "در حال بارگذاری...",+ "save": "ذخیره",+ "saveError": "ذخیره سند ناموفق بود، لطفاً دوباره تلاش کنید",+ "saveSuccess": "سند با موفقیت ذخیره شد",+ "title": "سند جدید",+ "updateSuccess": "سند با موفقیت بهروزرسانی شد"+ },"uploadButton": "بارگذاری"},+ "home": {+ "getStarted": "شروع کنید",+ "greeting": "شروع",+ "quickActions": "دسترسی سریع",+ "recentDocuments": "اسناد اخیر",+ "recentFiles": "فایلهای اخیر",+ "subtitle": "به پایگاه دانش خوش آمدید، از اینجا مدیریت اسناد خود را آغاز کنید",+ "uploadEntries": {+ "files": {+ "title": "بارگذاری فایل"+ },+ "folder": {+ "title": "بارگذاری پوشه"+ },+ "knowledgeBase": {+ "title": "ایجاد پایگاه دانش جدید"+ },+ "newDocument": {+ "title": "ایجاد سند جدید"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "این پایگاه دانش به زودی حذف خواهد شد، اما فایلهای آن حذف نخواهند شد و به بخش همه فایلها منتقل میشوند. پس از حذف پایگاه دانش، امکان بازیابی آن وجود نخواهد داشت، لطفاً با دقت عمل کنید.",@@ -38,6 +113,10 @@"new": "ایجاد پایگاه دانش جدید","title": "پایگاه دانش"},+ "menu": {+ "allDocuments": "همه اسناد",+ "allFiles": "تمام فایلها"+ },"networkError": "دریافت مخزن دانش ناموفق بود، لطفاً پس از بررسی اتصال شبکه دوباره تلاش کنید.","notSupportGuide": {"desc": "استقرار فعلی در حالت پایگاه داده کلاینت است و امکان استفاده از قابلیت مدیریت فایل وجود ندارد. لطفاً به <1>حالت استقرار پایگاه داده سرور</1> تغییر دهید، یا مستقیماً از <3>LobeChat Cloud</3> استفاده کنید.",@@ -61,12 +140,16 @@"downloadFile": "دانلود فایل","unsupportedFileAndContact": "فرمت این فایل در حال حاضر از پیشنمایش آنلاین پشتیبانی نمیکند. در صورت نیاز به پیشنمایش، لطفاً <1>به ما بازخورد دهید</1>."},+ "searchDocumentPlaceholder": "جستجوی سند","searchFilePlaceholder": "جستجوی فایل","tab": {- "all": "همه فایلها",+ "all": "همه","audios": "صداها","documents": "اسناد",+ "home": "خانه","images": "تصاویر",+ "moreTypes": "انواع بیشتر",+ "pages": "اسناد","videos": "ویدیوها","websites": "وبسایتها"},diff --git a/locales/fr-FR/common.json b/locales/fr-FR/common.jsonindex ee32cba923f..9c767538ec9 100644--- a/locales/fr-FR/common.json+++ b/locales/fr-FR/common.json@@ -286,6 +286,7 @@"oauth": "Connexion SSO","officialSite": "Site officiel","ok": "OK",+ "or": "ou","password": "Mot de passe","pin": "Épingler","pinOff": "Désactiver l'épinglage",diff --git a/locales/fr-FR/file.json b/locales/fr-FR/file.jsonindex 0356d92adf3..8d5c57a9fea 100644--- a/locales/fr-FR/file.json+++ b/locales/fr-FR/file.json@@ -1,5 +1,7 @@{- "desc": "Gérez vos connaissances",+ "addKnowledge": "Ajouter des connaissances",+ "addPage": "Créer un document",+ "desc": "Gérez vos connaissances liées au travail, aux études et à la vie quotidienne.","detail": {"basic": {"createdAt": "Date de création",@@ -21,6 +23,44 @@"embeddingStatus": "Vectorisation"}},+ "documentEditor": {+ "addIcon": "Ajouter une icône",+ "autoSaveMessage": "Le document est enregistré automatiquement, aucune action manuelle requise",+ "chooseIcon": "Choisir une icône",+ "deleteConfirm": {+ "content": "Ce document va être supprimé. Cette action est irréversible, veuillez procéder avec prudence.",+ "title": "Supprimer le document"+ },+ "deleteError": "Échec de la suppression du document",+ "deleteSuccess": "Document supprimé avec succès",+ "editedAt": "Dernière modification le {{time}}",+ "editedBy": "Dernière modification par {{name}}",+ "editorPlaceholder": "Saisissez le contenu du document, appuyez sur / pour ouvrir le menu de commandes",+ "empty": {+ "createNewDocument": "Créer un nouveau document",+ "title": "Sélectionnez un document pour commencer",+ "uploadMarkdown": "Téléverser un fichier Markdown"+ },+ "linkCopied": "Lien copié",+ "menu": {+ "copyLink": "Copier le lien",+ "exportDocument": "Exporter le document",+ "importDocument": "Importer un document",+ "pin": "Épingler le document"+ },+ "saving": "Enregistrement en cours...",+ "titlePlaceholder": "Sans titre",+ "wordCount": "{{wordCount}} mots"+ },+ "documentList": {+ "copyContent": "Copier tout le contenu",+ "documentCount": "{{count}} documents au total",+ "duplicate": "Créer une copie",+ "empty": "Aucun document pour le moment, cliquez sur le bouton ci-dessus pour créer votre premier document",+ "noResults": "Aucun document correspondant trouvé",+ "selectNote": "Sélectionnez un document pour commencer l’édition",+ "untitled": "Sans titre"+ },"empty": "Aucun fichier/dossier téléchargé pour le moment","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Télécharger un fichier","uploadFolder": "Télécharger un dossier"},+ "newDocumentButton": "Nouveau document",+ "newNoteDialog": {+ "cancel": "Annuler",+ "editTitle": "Modifier le document",+ "emptyContent": "Le contenu du document ne peut pas être vide",+ "loadError": "Échec du chargement du document, veuillez réessayer",+ "loading": "Chargement...",+ "save": "Enregistrer",+ "saveError": "Échec de l’enregistrement du document, veuillez réessayer",+ "saveSuccess": "Document enregistré avec succès",+ "title": "Nouveau document",+ "updateSuccess": "Document mis à jour avec succès"+ },"uploadButton": "Télécharger"},+ "home": {+ "getStarted": "Commencer",+ "greeting": "Commencer",+ "quickActions": "Actions rapides",+ "recentDocuments": "Documents récents",+ "recentFiles": "Fichiers récents",+ "subtitle": "Bienvenue dans votre base de connaissances, commencez ici à gérer vos documents",+ "uploadEntries": {+ "files": {+ "title": "Téléverser des fichiers"+ },+ "folder": {+ "title": "Téléverser un dossier"+ },+ "knowledgeBase": {+ "title": "Créer une base de connaissances"+ },+ "newDocument": {+ "title": "Nouveau document"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Vous allez supprimer cette base de connaissances. Les fichiers ne seront pas supprimés, mais déplacés dans tous les fichiers. La suppression de la base de connaissances est irréversible, veuillez agir avec prudence.",@@ -38,6 +113,10 @@"new": "Nouvelle base de connaissances","title": "Base de connaissances"},+ "menu": {+ "allDocuments": "Tous les documents",+ "allFiles": "Tous les fichiers"+ },"networkError": "Échec de l'accès à la base de connaissances, veuillez vérifier votre connexion réseau et réessayer","notSupportGuide": {"desc": "L'instance déployée actuellement est en mode base de données client, la fonction de gestion des fichiers n'est pas disponible. Veuillez passer en <1>mode de déploiement de base de données serveur</1>, ou utilisez directement <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Télécharger le fichier","unsupportedFileAndContact": "Ce format de fichier n'est pas encore pris en charge pour l'aperçu en ligne. Si vous souhaitez un aperçu, n'hésitez pas à <1>nous contacter</1>."},+ "searchDocumentPlaceholder": "Rechercher un document","searchFilePlaceholder": "Rechercher un fichier","tab": {- "all": "Tous les fichiers",+ "all": "Tout","audios": "Audio","documents": "Documents",+ "home": "Accueil","images": "Images",+ "moreTypes": "Plus de types",+ "pages": "Documents","videos": "Vidéos","websites": "Sites web"},diff --git a/locales/it-IT/common.json b/locales/it-IT/common.jsonindex b77039fd467..e226b5a6b02 100644--- a/locales/it-IT/common.json+++ b/locales/it-IT/common.json@@ -286,6 +286,7 @@"oauth": "Accesso SSO","officialSite": "Sito ufficiale","ok": "OK",+ "or": "o","password": "Password","pin": "Fissa in alto","pinOff": "Annulla fissaggio",diff --git a/locales/it-IT/file.json b/locales/it-IT/file.jsonindex e6ffb23c052..c737ffc38c1 100644--- a/locales/it-IT/file.json+++ b/locales/it-IT/file.json@@ -1,5 +1,7 @@{- "desc": "Gestisci le tue conoscenze",+ "addKnowledge": "Aggiungi conoscenza",+ "addPage": "Crea documento",+ "desc": "Gestisci le tue conoscenze su lavoro, studio e vita.","detail": {"basic": {"createdAt": "Data di creazione",@@ -21,6 +23,44 @@"embeddingStatus": "Vettorizzazione"}},+ "documentEditor": {+ "addIcon": "Aggiungi icona",+ "autoSaveMessage": "Il documento viene salvato automaticamente, non è necessario salvarlo manualmente",+ "chooseIcon": "Scegli icona",+ "deleteConfirm": {+ "content": "Stai per eliminare questo documento. Una volta eliminato, non potrà essere recuperato. Procedi con cautela.",+ "title": "Elimina documento"+ },+ "deleteError": "Eliminazione del documento non riuscita",+ "deleteSuccess": "Documento eliminato con successo",+ "editedAt": "Ultima modifica il {{time}}",+ "editedBy": "Ultima modifica di {{name}}",+ "editorPlaceholder": "Inserisci il contenuto del documento, premi / per aprire il menu dei comandi",+ "empty": {+ "createNewDocument": "Crea un nuovo documento",+ "title": "Seleziona un documento per iniziare",+ "uploadMarkdown": "Carica un file Markdown"+ },+ "linkCopied": "Link copiato",+ "menu": {+ "copyLink": "Copia link",+ "exportDocument": "Esporta documento",+ "importDocument": "Importa documento",+ "pin": "Fissa documento"+ },+ "saving": "Salvataggio in corso...",+ "titlePlaceholder": "Senza titolo",+ "wordCount": "{{wordCount}} parole"+ },+ "documentList": {+ "copyContent": "Copia tutto il contenuto",+ "documentCount": "Totale {{count}} documenti",+ "duplicate": "Crea una copia",+ "empty": "Nessun documento disponibile. Clicca sul pulsante in alto per creare il tuo primo documento",+ "noResults": "Nessun documento corrispondente trovato",+ "selectNote": "Seleziona un documento per iniziare a modificare",+ "untitled": "Senza titolo"+ },"empty": "Nessun file/cartella caricato","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Carica file","uploadFolder": "Carica cartella"},+ "newDocumentButton": "Nuovo documento",+ "newNoteDialog": {+ "cancel": "Annulla",+ "editTitle": "Modifica documento",+ "emptyContent": "Il contenuto del documento non può essere vuoto",+ "loadError": "Caricamento del documento non riuscito, riprova",+ "loading": "Caricamento in corso...",+ "save": "Salva",+ "saveError": "Salvataggio del documento non riuscito, riprova",+ "saveSuccess": "Documento salvato con successo",+ "title": "Nuovo documento",+ "updateSuccess": "Documento aggiornato con successo"+ },"uploadButton": "Carica"},+ "home": {+ "getStarted": "Inizia subito",+ "greeting": "Inizia",+ "quickActions": "Azioni rapide",+ "recentDocuments": "Documenti recenti",+ "recentFiles": "File recenti",+ "subtitle": "Benvenuto nel tuo archivio di conoscenza, inizia a gestire i tuoi documenti da qui",+ "uploadEntries": {+ "files": {+ "title": "Carica file"+ },+ "folder": {+ "title": "Carica cartella"+ },+ "knowledgeBase": {+ "title": "Crea nuova base di conoscenza"+ },+ "newDocument": {+ "title": "Crea nuovo documento"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Stai per eliminare questa knowledge base. I file al suo interno non verranno eliminati, ma spostati in 'Tutti i file'. Una volta eliminata, la knowledge base non potrà essere recuperata, procedi con cautela.",@@ -38,6 +113,10 @@"new": "Nuova knowledge base","title": "Knowledge Base"},+ "menu": {+ "allDocuments": "Tutti i documenti",+ "allFiles": "Tutti i file"+ },"networkError": "Impossibile ottenere la knowledge base, controlla la connessione di rete e riprova","notSupportGuide": {"desc": "L'istanza attuale è in modalità database client e non supporta la gestione dei file. Passa a <1>modalità di distribuzione del database server</1>, oppure utilizza direttamente <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Scarica file","unsupportedFileAndContact": "Questo formato di file non è attualmente supportato per la visualizzazione online. Se hai bisogno di una visualizzazione, ti preghiamo di <1>contattarci</1>."},+ "searchDocumentPlaceholder": "Cerca documenti","searchFilePlaceholder": "Cerca file","tab": {- "all": "Tutti i file",+ "all": "Tutti","audios": "Audio","documents": "Documenti",+ "home": "Home","images": "Immagini",+ "moreTypes": "Altri tipi",+ "pages": "Documenti","videos": "Video","websites": "Siti web"},diff --git a/locales/ja-JP/common.json b/locales/ja-JP/common.jsonindex 0f6f14e5aad..de4beab882d 100644--- a/locales/ja-JP/common.json+++ b/locales/ja-JP/common.json@@ -286,6 +286,7 @@"oauth": "SSO ログイン","officialSite": "公式サイト","ok": "OK",+ "or": "または","password": "パスワード","pin": "ピン留め","pinOff": "ピン留め解除",diff --git a/locales/ja-JP/file.json b/locales/ja-JP/file.jsonindex a9237f93c48..48479efa689 100644--- a/locales/ja-JP/file.json+++ b/locales/ja-JP/file.json@@ -1,5 +1,7 @@{- "desc": "あなたの知識を管理する",+ "addKnowledge": "知識を追加",+ "addPage": "ドキュメントを作成",+ "desc": "仕事、学習、生活の知識を管理しましょう。","detail": {"basic": {"createdAt": "作成日時",@@ -21,6 +23,44 @@"embeddingStatus": "ベクトル化"}},+ "documentEditor": {+ "addIcon": "アイコンを追加",+ "autoSaveMessage": "ドキュメントは自動的に保存されます。手動で保存する必要はありません。",+ "chooseIcon": "アイコンを選択",+ "deleteConfirm": {+ "content": "このドキュメントを削除しようとしています。削除後は復元できませんので、ご注意ください。",+ "title": "ドキュメントの削除"+ },+ "deleteError": "ドキュメントの削除に失敗しました",+ "deleteSuccess": "ドキュメントを削除しました",+ "editedAt": "最終編集:{{time}}",+ "editedBy": "最終編集者:{{name}}",+ "editorPlaceholder": "ドキュメントの内容を入力し、「/」でコマンドメニューを開く",+ "empty": {+ "createNewDocument": "新しいドキュメントを作成",+ "title": "ドキュメントを選択して開始",+ "uploadMarkdown": "Markdownファイルをアップロード"+ },+ "linkCopied": "リンクをコピーしました",+ "menu": {+ "copyLink": "リンクをコピー",+ "exportDocument": "ドキュメントをエクスポート",+ "importDocument": "ドキュメントをインポート",+ "pin": "ドキュメントをピン留め"+ },+ "saving": "保存中...",+ "titlePlaceholder": "無題",+ "wordCount": "{{wordCount}} 文字"+ },+ "documentList": {+ "copyContent": "全文をコピー",+ "documentCount": "全{{count}}件のドキュメント",+ "duplicate": "複製を作成",+ "empty": "ドキュメントがありません。上のボタンをクリックして最初のドキュメントを作成しましょう。",+ "noResults": "一致するドキュメントが見つかりませんでした",+ "selectNote": "ドキュメントを選択して編集を開始",+ "untitled": "無題"+ },"empty": "アップロードされたファイル/フォルダーはありません","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "ファイルをアップロード","uploadFolder": "フォルダーをアップロード"},+ "newDocumentButton": "新規ドキュメント",+ "newNoteDialog": {+ "cancel": "キャンセル",+ "editTitle": "ドキュメントを編集",+ "emptyContent": "ドキュメントの内容は空にできません",+ "loadError": "ドキュメントの読み込みに失敗しました。再試行してください。",+ "loading": "読み込み中...",+ "save": "保存",+ "saveError": "ドキュメントの保存に失敗しました。再試行してください。",+ "saveSuccess": "ドキュメントを保存しました",+ "title": "新規ドキュメント",+ "updateSuccess": "ドキュメントを更新しました"+ },"uploadButton": "アップロード"},+ "home": {+ "getStarted": "はじめに",+ "greeting": "はじめに",+ "quickActions": "クイック操作",+ "recentDocuments": "最近のドキュメント",+ "recentFiles": "最近のファイル",+ "subtitle": "ナレッジベースへようこそ。ここからドキュメントの管理を始めましょう。",+ "uploadEntries": {+ "files": {+ "title": "ファイルをアップロード"+ },+ "folder": {+ "title": "フォルダをアップロード"+ },+ "knowledgeBase": {+ "title": "新しいナレッジベースを作成"+ },+ "newDocument": {+ "title": "新規ドキュメント"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "この知識ベースを削除しようとしています。ファイルは削除されず、すべてのファイルに移動されます。知識ベースを削除すると復元できませんので、慎重に操作してください。",@@ -38,6 +113,10 @@"new": "新しい知識ベース","title": "知識ベース"},+ "menu": {+ "allDocuments": "すべてのドキュメント",+ "allFiles": "すべてのファイル"+ },"networkError": "知識ベースの取得に失敗しました。ネットワーク接続を確認してから再試行してください","notSupportGuide": {"desc": "現在のデプロイメントインスタンスはクライアントデータベースモードであり、ファイル管理機能を使用できません。<1>サーバーデータベースデプロイメントモード</1>に切り替えるか、直接 <3>LobeChat Cloud</3> を使用してください。",@@ -61,12 +140,16 @@"downloadFile": "ファイルをダウンロード","unsupportedFileAndContact": "このファイル形式はオンラインプレビューをサポートしていません。プレビューのリクエストがある場合は、ぜひ<1>ご連絡ください</1>。"},+ "searchDocumentPlaceholder": "ドキュメントを検索","searchFilePlaceholder": "ファイルを検索","tab": {- "all": "すべてのファイル",+ "all": "すべて","audios": "音声","documents": "文書",+ "home": "ホーム","images": "画像",+ "moreTypes": "その他の種類",+ "pages": "ドキュメント","videos": "動画","websites": "ウェブサイト"},diff --git a/locales/ko-KR/common.json b/locales/ko-KR/common.jsonindex 4b95306cebc..611d337f024 100644--- a/locales/ko-KR/common.json+++ b/locales/ko-KR/common.json@@ -286,6 +286,7 @@"oauth": "SSO 로그인","officialSite": "공식 웹사이트","ok": "확인",+ "or": "또는","password": "비밀번호","pin": "상단 고정","pinOff": "고정 해제",diff --git a/locales/ko-KR/file.json b/locales/ko-KR/file.jsonindex eeb57b50ad7..74ccc2e3f08 100644--- a/locales/ko-KR/file.json+++ b/locales/ko-KR/file.json@@ -1,5 +1,7 @@{- "desc": "지식을 관리하세요",+ "addKnowledge": "지식 추가",+ "addPage": "문서 생성",+ "desc": "작업, 학습 및 생활 지식을 관리하세요.","detail": {"basic": {"createdAt": "생성 시간",@@ -21,6 +23,44 @@"embeddingStatus": "벡터화 상태"}},+ "documentEditor": {+ "addIcon": "아이콘 추가",+ "autoSaveMessage": "문서는 자동으로 저장되며, 수동 저장이 필요하지 않습니다",+ "chooseIcon": "아이콘 선택",+ "deleteConfirm": {+ "content": "이 문서를 삭제하려고 합니다. 삭제 후에는 복구할 수 없으니 신중히 진행해 주세요.",+ "title": "문서 삭제"+ },+ "deleteError": "문서 삭제에 실패했습니다",+ "deleteSuccess": "문서가 성공적으로 삭제되었습니다",+ "editedAt": "{{time}}에 마지막으로 편집됨",+ "editedBy": "마지막 편집자: {{name}}",+ "editorPlaceholder": "문서 내용을 입력하세요. / 키를 눌러 명령 메뉴를 엽니다",+ "empty": {+ "createNewDocument": "새 문서 만들기",+ "title": "문서를 선택하여 시작하세요",+ "uploadMarkdown": "Markdown 파일 업로드"+ },+ "linkCopied": "링크가 복사되었습니다",+ "menu": {+ "copyLink": "링크 복사",+ "exportDocument": "문서 내보내기",+ "importDocument": "문서 가져오기",+ "pin": "문서 상단 고정"+ },+ "saving": "저장 중...",+ "titlePlaceholder": "제목 없음",+ "wordCount": "{{wordCount}}자"+ },+ "documentList": {+ "copyContent": "전체 내용 복사",+ "documentCount": "총 {{count}}개의 문서",+ "duplicate": "복사본 만들기",+ "empty": "아직 문서가 없습니다. 위 버튼을 클릭하여 첫 문서를 작성해 보세요",+ "noResults": "일치하는 문서를 찾을 수 없습니다",+ "selectNote": "편집할 문서를 선택하세요",+ "untitled": "제목 없음"+ },"empty": "업로드된 파일/폴더가 없습니다","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "파일 업로드","uploadFolder": "폴더 업로드"},+ "newDocumentButton": "새 문서",+ "newNoteDialog": {+ "cancel": "취소",+ "editTitle": "문서 편집",+ "emptyContent": "문서 내용은 비워둘 수 없습니다",+ "loadError": "문서 불러오기에 실패했습니다. 다시 시도해 주세요",+ "loading": "불러오는 중...",+ "save": "저장",+ "saveError": "문서 저장에 실패했습니다. 다시 시도해 주세요",+ "saveSuccess": "문서가 성공적으로 저장되었습니다",+ "title": "새 문서 만들기",+ "updateSuccess": "문서가 성공적으로 업데이트되었습니다"+ },"uploadButton": "업로드"},+ "home": {+ "getStarted": "시작하기",+ "greeting": "시작하기",+ "quickActions": "빠른 작업",+ "recentDocuments": "최근 문서",+ "recentFiles": "최근 파일",+ "subtitle": "지식 관리 시스템에 오신 것을 환영합니다. 여기서 문서를 관리해 보세요",+ "uploadEntries": {+ "files": {+ "title": "파일 업로드"+ },+ "folder": {+ "title": "폴더 업로드"+ },+ "knowledgeBase": {+ "title": "새 지식베이스 만들기"+ },+ "newDocument": {+ "title": "새 문서 만들기"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "이 지식베이스를 삭제하려고 합니다. 포함된 파일은 삭제되지 않으며 전체 파일로 이동됩니다. 삭제된 지식베이스는 복구할 수 없으니 신중히 진행해 주세요.",@@ -38,6 +113,10 @@"new": "새 지식베이스","title": "지식베이스"},+ "menu": {+ "allDocuments": "모든 문서",+ "allFiles": "모든 파일"+ },"networkError": "지식베이스를 불러오지 못했습니다. 네트워크 연결을 확인한 후 다시 시도해 주세요","notSupportGuide": {"desc": "현재 배포 인스턴스는 클라이언트 데이터베이스 모드로, 파일 관리 기능을 사용할 수 없습니다. <1>서버 데이터베이스 배포 모드</1>로 전환하거나 <3>LobeChat Cloud</3>를 이용해 주세요",@@ -61,12 +140,16 @@"downloadFile": "파일 다운로드","unsupportedFileAndContact": "이 파일 형식은 온라인 미리보기를 지원하지 않습니다. 미리보기 기능이 필요하시면 <1>의견을 보내주세요</1>"},+ "searchDocumentPlaceholder": "문서 검색","searchFilePlaceholder": "파일 검색","tab": {- "all": "전체 파일",+ "all": "전체","audios": "오디오","documents": "문서",+ "home": "홈","images": "이미지",+ "moreTypes": "더 많은 유형",+ "pages": "문서","videos": "비디오","websites": "웹사이트"},diff --git a/locales/nl-NL/common.json b/locales/nl-NL/common.jsonindex 769e25c0a60..01373dd8cce 100644--- a/locales/nl-NL/common.json+++ b/locales/nl-NL/common.json@@ -286,6 +286,7 @@"oauth": "SSO inloggen","officialSite": "Officiële website","ok": "Oké",+ "or": "of","password": "Wachtwoord","pin": "Vastzetten","pinOff": "Vastzetten uitschakelen",diff --git a/locales/nl-NL/file.json b/locales/nl-NL/file.jsonindex 095428b2c85..5827bf300e6 100644--- a/locales/nl-NL/file.json+++ b/locales/nl-NL/file.json@@ -1,5 +1,7 @@{- "desc": "Beheer je kennis",+ "addKnowledge": "Kennis toevoegen",+ "addPage": "Document aanmaken",+ "desc": "Beheer je kennis over werk, studie en leven.","detail": {"basic": {"createdAt": "Aanmaakdatum",@@ -21,6 +23,44 @@"embeddingStatus": "Vectorisatie"}},+ "documentEditor": {+ "addIcon": "Pictogram toevoegen",+ "autoSaveMessage": "Documenten worden automatisch opgeslagen, handmatig opslaan is niet nodig",+ "chooseIcon": "Pictogram kiezen",+ "deleteConfirm": {+ "content": "Je staat op het punt dit document te verwijderen. Dit kan niet ongedaan worden gemaakt. Wees voorzichtig.",+ "title": "Document verwijderen"+ },+ "deleteError": "Verwijderen van document mislukt",+ "deleteSuccess": "Document succesvol verwijderd",+ "editedAt": "Laatst bewerkt op {{time}}",+ "editedBy": "Laatst bewerkt door {{name}}",+ "editorPlaceholder": "Voer documentinhoud in, druk op / om het opdrachtmenu te openen",+ "empty": {+ "createNewDocument": "Nieuw document aanmaken",+ "title": "Selecteer een document om te beginnen",+ "uploadMarkdown": "Markdown-bestand uploaden"+ },+ "linkCopied": "Link gekopieerd",+ "menu": {+ "copyLink": "Link kopiëren",+ "exportDocument": "Document exporteren",+ "importDocument": "Document importeren",+ "pin": "Document vastzetten"+ },+ "saving": "Bezig met opslaan...",+ "titlePlaceholder": "Zonder titel",+ "wordCount": "{{wordCount}} woorden"+ },+ "documentList": {+ "copyContent": "Volledige inhoud kopiëren",+ "documentCount": "Totaal {{count}} documenten",+ "duplicate": "Kopie maken",+ "empty": "Nog geen documenten. Klik op de knop hierboven om je eerste document aan te maken",+ "noResults": "Geen overeenkomende documenten gevonden",+ "selectNote": "Selecteer een document om te beginnen met bewerken",+ "untitled": "Zonder titel"+ },"empty": "Geen bestanden/mappen geüpload","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Bestand uploaden","uploadFolder": "Map uploaden"},+ "newDocumentButton": "Nieuw document",+ "newNoteDialog": {+ "cancel": "Annuleren",+ "editTitle": "Document bewerken",+ "emptyContent": "Documentinhoud mag niet leeg zijn",+ "loadError": "Laden van document mislukt, probeer het opnieuw",+ "loading": "Bezig met laden...",+ "save": "Opslaan",+ "saveError": "Opslaan van document mislukt, probeer het opnieuw",+ "saveSuccess": "Document succesvol opgeslagen",+ "title": "Nieuw document",+ "updateSuccess": "Document succesvol bijgewerkt"+ },"uploadButton": "Uploaden"},+ "home": {+ "getStarted": "Aan de slag",+ "greeting": "Aan de slag",+ "quickActions": "Snelle acties",+ "recentDocuments": "Recente documenten",+ "recentFiles": "Recente bestanden",+ "subtitle": "Welkom bij je kennisbank. Begin hier met het beheren van je documenten",+ "uploadEntries": {+ "files": {+ "title": "Bestanden uploaden"+ },+ "folder": {+ "title": "Map uploaden"+ },+ "knowledgeBase": {+ "title": "Nieuwe kennisbank"+ },+ "newDocument": {+ "title": "Nieuw document"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Je staat op het punt deze kennisbank te verwijderen. De bestanden hierin worden niet verwijderd, maar verplaatst naar 'Alle bestanden'. Een verwijderde kennisbank kan niet worden hersteld, wees voorzichtig.",@@ -38,6 +113,10 @@"new": "Nieuwe kennisbank","title": "Kennisbank"},+ "menu": {+ "allDocuments": "Alle documenten",+ "allFiles": "Alle bestanden"+ },"networkError": "Kon de kennisbank niet ophalen, controleer uw netwerkverbinding en probeer het opnieuw","notSupportGuide": {"desc": "De huidige implementatie is in client-database modus, waardoor de bestandsbeheerfunctie niet beschikbaar is. Schakel over naar <1>server-database implementatiemodus</1>, of gebruik direct <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Bestand downloaden","unsupportedFileAndContact": "Dit bestandsformaat wordt momenteel niet ondersteund voor online preview. Als u een preview wilt, neem dan gerust <1>contact met ons op</1>."},+ "searchDocumentPlaceholder": "Documenten zoeken","searchFilePlaceholder": "Zoek bestand","tab": {- "all": "Alle bestanden",+ "all": "Alles","audios": "Audio's","documents": "Documenten",+ "home": "Startpagina","images": "Afbeeldingen",+ "moreTypes": "Meer typen",+ "pages": "Documenten","videos": "Video's","websites": "Websites"},diff --git a/locales/pl-PL/common.json b/locales/pl-PL/common.jsonindex a71bf90140c..5f007df1fcd 100644--- a/locales/pl-PL/common.json+++ b/locales/pl-PL/common.json@@ -286,6 +286,7 @@"oauth": "Logowanie SSO","officialSite": "Oficjalna strona internetowa","ok": "OK",+ "or": "lub","password": "Hasło","pin": "Przypnij","pinOff": "Odepnij",diff --git a/locales/pl-PL/file.json b/locales/pl-PL/file.jsonindex 57ca16787a1..d3614bba055 100644--- a/locales/pl-PL/file.json+++ b/locales/pl-PL/file.json@@ -1,5 +1,7 @@{- "desc": "Zarządzaj swoją wiedzą",+ "addKnowledge": "Dodaj wiedzę",+ "addPage": "Utwórz dokument",+ "desc": "Zarządzaj swoją wiedzą z pracy, nauki i życia.","detail": {"basic": {"createdAt": "Data utworzenia",@@ -21,6 +23,44 @@"embeddingStatus": "Indeksowanie"}},+ "documentEditor": {+ "addIcon": "Dodaj ikonę",+ "autoSaveMessage": "Dokument jest zapisywany automatycznie, nie ma potrzeby zapisywania ręcznego",+ "chooseIcon": "Wybierz ikonę",+ "deleteConfirm": {+ "content": "Zamierzasz usunąć ten dokument. Po usunięciu nie będzie można go odzyskać. Proszę postępować ostrożnie.",+ "title": "Usuń dokument"+ },+ "deleteError": "Nie udało się usunąć dokumentu",+ "deleteSuccess": "Dokument został pomyślnie usunięty",+ "editedAt": "Ostatnia edycja: {{time}}",+ "editedBy": "Ostatnio edytował: {{name}}",+ "editorPlaceholder": "Wpisz treść dokumentu, naciśnij / aby otworzyć menu poleceń",+ "empty": {+ "createNewDocument": "Utwórz nowy dokument",+ "title": "Wybierz dokument, aby rozpocząć",+ "uploadMarkdown": "Prześlij plik Markdown"+ },+ "linkCopied": "Link został skopiowany",+ "menu": {+ "copyLink": "Kopiuj link",+ "exportDocument": "Eksportuj dokument",+ "importDocument": "Importuj dokument",+ "pin": "Przypnij dokument"+ },+ "saving": "Zapisywanie...",+ "titlePlaceholder": "Bez tytułu",+ "wordCount": "{{wordCount}} słów"+ },+ "documentList": {+ "copyContent": "Kopiuj całą treść",+ "documentCount": "Łącznie {{count}} dokumentów",+ "duplicate": "Utwórz kopię",+ "empty": "Brak dokumentów. Kliknij przycisk powyżej, aby utworzyć pierwszy dokument",+ "noResults": "Nie znaleziono pasujących dokumentów",+ "selectNote": "Wybierz dokument, aby rozpocząć edycję",+ "untitled": "Bez tytułu"+ },"empty": "Brak przesłanych plików/folderów","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Prześlij plik","uploadFolder": "Prześlij folder"},+ "newDocumentButton": "Nowy dokument",+ "newNoteDialog": {+ "cancel": "Anuluj",+ "editTitle": "Edytuj dokument",+ "emptyContent": "Treść dokumentu nie może być pusta",+ "loadError": "Nie udało się załadować dokumentu, spróbuj ponownie",+ "loading": "Ładowanie...",+ "save": "Zapisz",+ "saveError": "Nie udało się zapisać dokumentu, spróbuj ponownie",+ "saveSuccess": "Dokument został zapisany pomyślnie",+ "title": "Nowy dokument",+ "updateSuccess": "Dokument został zaktualizowany pomyślnie"+ },"uploadButton": "Prześlij"},+ "home": {+ "getStarted": "Rozpocznij",+ "greeting": "Zaczynamy",+ "quickActions": "Szybkie akcje",+ "recentDocuments": "Ostatnie dokumenty",+ "recentFiles": "Ostatnie pliki",+ "subtitle": "Witamy w bazie wiedzy. Zacznij zarządzać swoimi dokumentami już teraz",+ "uploadEntries": {+ "files": {+ "title": "Prześlij pliki"+ },+ "folder": {+ "title": "Prześlij folder"+ },+ "knowledgeBase": {+ "title": "Nowa baza wiedzy"+ },+ "newDocument": {+ "title": "Nowy dokument"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Zaraz usuniesz tę bazę wiedzy, pliki w niej zawarte nie zostaną usunięte, a zostaną przeniesione do folderu wszystkich plików. Po usunięciu bazy wiedzy nie będzie można jej przywrócić, proszę działać ostrożnie.",@@ -38,6 +113,10 @@"new": "Nowa baza wiedzy","title": "Baza wiedzy"},+ "menu": {+ "allDocuments": "Wszystkie dokumenty",+ "allFiles": "Wszystkie pliki"+ },"networkError": "Nie udało się uzyskać dostępu do bazy wiedzy, proszę sprawdzić połączenie sieciowe i spróbować ponownie","notSupportGuide": {"desc": "Obecna instancja wdrożeniowa jest w trybie bazy danych klienta, co uniemożliwia korzystanie z funkcji zarządzania plikami. Proszę przełączyć się na <1>tryb wdrożenia bazy danych serwera</1> lub bezpośrednio korzystać z <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Pobierz plik","unsupportedFileAndContact": "Ten format pliku nie jest obecnie obsługiwany w podglądzie online. Jeśli chcesz uzyskać podgląd, zachęcamy do <1>skontaktowania się z nami</1>."},+ "searchDocumentPlaceholder": "Szukaj dokumentu","searchFilePlaceholder": "Szukaj pliku","tab": {- "all": "Wszystkie pliki",+ "all": "Wszystko","audios": "Audio","documents": "Dokumenty",+ "home": "Strona główna","images": "Obrazy",+ "moreTypes": "Więcej typów",+ "pages": "Dokumenty","videos": "Wideo","websites": "Strony internetowe"},diff --git a/locales/pt-BR/common.json b/locales/pt-BR/common.jsonindex bab01de7dfb..b174e2a284b 100644--- a/locales/pt-BR/common.json+++ b/locales/pt-BR/common.json@@ -286,6 +286,7 @@"oauth": "Login SSO","officialSite": "Site Oficial","ok": "OK",+ "or": "ou","password": "Senha","pin": "Fixar","pinOff": "Desafixar",diff --git a/locales/pt-BR/file.json b/locales/pt-BR/file.jsonindex a7d07c3e921..f3cf16d6920 100644--- a/locales/pt-BR/file.json+++ b/locales/pt-BR/file.json@@ -1,5 +1,7 @@{- "desc": "Gerencie seu conhecimento",+ "addKnowledge": "Adicionar conhecimento",+ "addPage": "Criar documento",+ "desc": "Gerencie seus conhecimentos de trabalho, estudo e vida.","detail": {"basic": {"createdAt": "Data de criação",@@ -21,6 +23,44 @@"embeddingStatus": "Vetorização"}},+ "documentEditor": {+ "addIcon": "Adicionar ícone",+ "autoSaveMessage": "O documento é salvo automaticamente, não é necessário salvar manualmente",+ "chooseIcon": "Escolher ícone",+ "deleteConfirm": {+ "content": "Este documento será excluído permanentemente e não poderá ser recuperado. Por favor, tenha cuidado.",+ "title": "Excluir documento"+ },+ "deleteError": "Falha ao excluir o documento",+ "deleteSuccess": "Documento excluído com sucesso",+ "editedAt": "Última edição em {{time}}",+ "editedBy": "Última edição por {{name}}",+ "editorPlaceholder": "Digite o conteúdo do documento, pressione / para abrir o menu de comandos",+ "empty": {+ "createNewDocument": "Criar novo documento",+ "title": "Selecione um documento para começar",+ "uploadMarkdown": "Carregar arquivo Markdown"+ },+ "linkCopied": "Link copiado",+ "menu": {+ "copyLink": "Copiar link",+ "exportDocument": "Exportar documento",+ "importDocument": "Importar documento",+ "pin": "Fixar documento"+ },+ "saving": "Salvando...",+ "titlePlaceholder": "Sem título",+ "wordCount": "{{wordCount}} palavras"+ },+ "documentList": {+ "copyContent": "Copiar conteúdo completo",+ "documentCount": "Total de {{count}} documentos",+ "duplicate": "Criar uma cópia",+ "empty": "Nenhum documento disponível. Clique no botão acima para criar seu primeiro documento",+ "noResults": "Nenhum documento correspondente encontrado",+ "selectNote": "Selecione um documento para começar a editar",+ "untitled": "Sem título"+ },"empty": "Nenhum arquivo/pasta enviado até o momento","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Enviar arquivo","uploadFolder": "Enviar pasta"},+ "newDocumentButton": "Novo documento",+ "newNoteDialog": {+ "cancel": "Cancelar",+ "editTitle": "Editar documento",+ "emptyContent": "O conteúdo do documento não pode estar vazio",+ "loadError": "Falha ao carregar o documento, tente novamente",+ "loading": "Carregando...",+ "save": "Salvar",+ "saveError": "Falha ao salvar o documento, tente novamente",+ "saveSuccess": "Documento salvo com sucesso",+ "title": "Novo documento",+ "updateSuccess": "Documento atualizado com sucesso"+ },"uploadButton": "Enviar"},+ "home": {+ "getStarted": "Começar",+ "greeting": "Início",+ "quickActions": "Ações Rápidas",+ "recentDocuments": "Documentos Recentes",+ "recentFiles": "Arquivos Recentes",+ "subtitle": "Bem-vindo ao seu repositório de conhecimento. Comece a gerenciar seus documentos aqui",+ "uploadEntries": {+ "files": {+ "title": "Enviar Arquivos"+ },+ "folder": {+ "title": "Enviar Pasta"+ },+ "knowledgeBase": {+ "title": "Nova Base de Conhecimento"+ },+ "newDocument": {+ "title": "Novo Documento"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Você está prestes a excluir este repositório de conhecimento. Os arquivos não serão excluídos, mas serão movidos para 'Todos os arquivos'. Após a exclusão, o repositório não poderá ser recuperado, por favor, proceda com cautela.",@@ -38,6 +113,10 @@"new": "Novo repositório de conhecimento","title": "Repositório de conhecimento"},+ "menu": {+ "allDocuments": "Todos os Documentos",+ "allFiles": "Todos os arquivos"+ },"networkError": "Falha ao acessar a base de conhecimento, por favor verifique a conexão de rede e tente novamente","notSupportGuide": {"desc": "A instância atual está no modo de banco de dados cliente e não pode usar a funcionalidade de gerenciamento de arquivos. Por favor, mude para <1>modo de banco de dados servidor</1>, ou use diretamente <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Baixar arquivo","unsupportedFileAndContact": "Este formato de arquivo não é suportado para visualização online. Se você tiver interesse em visualizar, sinta-se à vontade para <1>nos enviar um feedback</1>."},+ "searchDocumentPlaceholder": "Pesquisar documentos","searchFilePlaceholder": "Pesquisar arquivo","tab": {- "all": "Todos os arquivos",+ "all": "Todos","audios": "Áudios","documents": "Documentos",+ "home": "Início","images": "Imagens",+ "moreTypes": "Mais Tipos",+ "pages": "Documentos","videos": "Vídeos","websites": "Sites"},diff --git a/locales/ru-RU/common.json b/locales/ru-RU/common.jsonindex 09157b56386..70b7e7ba4ee 100644--- a/locales/ru-RU/common.json+++ b/locales/ru-RU/common.json@@ -286,6 +286,7 @@"oauth": "Вход через единую учетную запись (SSO)","officialSite": "Официальный сайт","ok": "ОК",+ "or": "или","password": "Пароль","pin": "Закрепить","pinOff": "Открепить",diff --git a/locales/ru-RU/file.json b/locales/ru-RU/file.jsonindex e294cdd535e..57c394dcfaa 100644--- a/locales/ru-RU/file.json+++ b/locales/ru-RU/file.json@@ -1,5 +1,7 @@{- "desc": "Управляйте своими знаниями",+ "addKnowledge": "Добавить знание",+ "addPage": "Создать документ",+ "desc": "Управляйте своими знаниями в работе, учебе и жизни.","detail": {"basic": {"createdAt": "Дата создания",@@ -21,6 +23,44 @@"embeddingStatus": "Векторизация"}},+ "documentEditor": {+ "addIcon": "Добавить значок",+ "autoSaveMessage": "Документ сохраняется автоматически, ручное сохранение не требуется",+ "chooseIcon": "Выбрать значок",+ "deleteConfirm": {+ "content": "Вы собираетесь удалить этот документ. После удаления восстановление будет невозможно. Пожалуйста, будьте осторожны.",+ "title": "Удалить документ"+ },+ "deleteError": "Не удалось удалить документ",+ "deleteSuccess": "Документ успешно удалён",+ "editedAt": "Последнее редактирование: {{time}}",+ "editedBy": "Последний редактор: {{name}}",+ "editorPlaceholder": "Введите содержимое документа, нажмите / для открытия меню команд",+ "empty": {+ "createNewDocument": "Создать новый документ",+ "title": "Выберите документ, чтобы начать",+ "uploadMarkdown": "Загрузить файл Markdown"+ },+ "linkCopied": "Ссылка скопирована",+ "menu": {+ "copyLink": "Скопировать ссылку",+ "exportDocument": "Экспортировать документ",+ "importDocument": "Импортировать документ",+ "pin": "Закрепить документ"+ },+ "saving": "Сохранение...",+ "titlePlaceholder": "Без названия",+ "wordCount": "{{wordCount}} слов"+ },+ "documentList": {+ "copyContent": "Скопировать всё содержимое",+ "documentCount": "Всего {{count}} документов",+ "duplicate": "Создать копию",+ "empty": "Документов пока нет. Нажмите кнопку выше, чтобы создать первый документ",+ "noResults": "Совпадающих документов не найдено",+ "selectNote": "Выберите документ для редактирования",+ "untitled": "Без названия"+ },"empty": "Нет загруженных файлов/папок","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Загрузить файл","uploadFolder": "Загрузить папку"},+ "newDocumentButton": "Новый документ",+ "newNoteDialog": {+ "cancel": "Отмена",+ "editTitle": "Редактировать документ",+ "emptyContent": "Содержимое документа не может быть пустым",+ "loadError": "Не удалось загрузить документ, попробуйте ещё раз",+ "loading": "Загрузка...",+ "save": "Сохранить",+ "saveError": "Не удалось сохранить документ, попробуйте ещё раз",+ "saveSuccess": "Документ успешно сохранён",+ "title": "Создать новый документ",+ "updateSuccess": "Документ успешно обновлён"+ },"uploadButton": "Загрузить"},+ "home": {+ "getStarted": "Начать",+ "greeting": "Начало",+ "quickActions": "Быстрые действия",+ "recentDocuments": "Недавние документы",+ "recentFiles": "Недавние файлы",+ "subtitle": "Добро пожаловать в базу знаний. Начните управлять своими документами отсюда",+ "uploadEntries": {+ "files": {+ "title": "Загрузить файлы"+ },+ "folder": {+ "title": "Загрузить папку"+ },+ "knowledgeBase": {+ "title": "Создать базу знаний"+ },+ "newDocument": {+ "title": "Создать документ"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Вы собираетесь удалить эту базу знаний. Файлы в ней не будут удалены и будут перемещены в общие файлы. После удаления база знаний не может быть восстановлена, пожалуйста, будьте осторожны.",@@ -38,6 +113,10 @@"new": "Создать базу знаний","title": "База знаний"},+ "menu": {+ "allDocuments": "Все документы",+ "allFiles": "Все файлы"+ },"networkError": "Не удалось получить базу знаний, пожалуйста, проверьте сетевое соединение и попробуйте снова","notSupportGuide": {"desc": "Текущий развертываемый экземпляр находится в режиме клиентской базы данных, функции управления файлами недоступны. Пожалуйста, переключитесь на <1>режим серверной базы данных</1> или используйте <3>LobeChat Cloud</3> напрямую.",@@ -61,12 +140,16 @@"downloadFile": "Скачать файл","unsupportedFileAndContact": "Этот формат файла в настоящее время не поддерживает онлайн-просмотр. Если у вас есть запрос на просмотр, пожалуйста, <1>сообщите нам</1>."},+ "searchDocumentPlaceholder": "Поиск документов","searchFilePlaceholder": "Поиск файла","tab": {- "all": "Все файлы",+ "all": "Все","audios": "Аудио","documents": "Документы",+ "home": "Главная","images": "Изображения",+ "moreTypes": "Больше типов",+ "pages": "Документы","videos": "Видео","websites": "Веб-сайты"},diff --git a/locales/tr-TR/common.json b/locales/tr-TR/common.jsonindex ba3b2b398da..958c6db4920 100644--- a/locales/tr-TR/common.json+++ b/locales/tr-TR/common.json@@ -286,6 +286,7 @@"oauth": "SSO Girişi","officialSite": "Resmi Site","ok": "Tamam",+ "or": "veya","password": "Password","pin": "Pin","pinOff": "Unpin",diff --git a/locales/tr-TR/file.json b/locales/tr-TR/file.jsonindex f47b45ceabe..05b7fb7a81c 100644--- a/locales/tr-TR/file.json+++ b/locales/tr-TR/file.json@@ -1,5 +1,7 @@{- "desc": "Bilgini yönet",+ "addKnowledge": "Bilgi Ekle",+ "addPage": "Belge Oluştur",+ "desc": "Çalışma, öğrenme ve yaşam bilginizi yönetin.","detail": {"basic": {"createdAt": "Oluşturulma Zamanı",@@ -21,6 +23,44 @@"embeddingStatus": "Vektörleştirme"}},+ "documentEditor": {+ "addIcon": "Simge Ekle",+ "autoSaveMessage": "Belge otomatik olarak kaydedilir, manuel kaydetmeye gerek yoktur",+ "chooseIcon": "Simge Seç",+ "deleteConfirm": {+ "content": "Bu belge silinmek üzere. Silindikten sonra geri alınamaz, lütfen dikkatli olun.",+ "title": "Belgeyi Sil"+ },+ "deleteError": "Belge silinemedi",+ "deleteSuccess": "Belge başarıyla silindi",+ "editedAt": "Son düzenleme: {{time}}",+ "editedBy": "Son düzenleyen: {{name}}",+ "editorPlaceholder": "Belge içeriğini girin, komut menüsünü açmak için / tuşuna basın",+ "empty": {+ "createNewDocument": "Yeni Belge Oluştur",+ "title": "Başlamak için bir belge seçin",+ "uploadMarkdown": "Markdown Dosyası Yükle"+ },+ "linkCopied": "Bağlantı kopyalandı",+ "menu": {+ "copyLink": "Bağlantıyı Kopyala",+ "exportDocument": "Belgeyi Dışa Aktar",+ "importDocument": "Belgeyi İçe Aktar",+ "pin": "Belgeyi Sabitle"+ },+ "saving": "Kaydediliyor...",+ "titlePlaceholder": "Başlıksız",+ "wordCount": "{{wordCount}} kelime"+ },+ "documentList": {+ "copyContent": "Tüm İçeriği Kopyala",+ "documentCount": "Toplam {{count}} belge",+ "duplicate": "Kopyasını Oluştur",+ "empty": "Henüz belge yok, ilk belgenizi oluşturmak için yukarıdaki butona tıklayın",+ "noResults": "Eşleşen belge bulunamadı",+ "selectNote": "Düzenlemeye başlamak için bir belge seçin",+ "untitled": "Başlıksız"+ },"empty": "Henüz yüklenmiş dosya/klasör yok","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Dosya Yükle","uploadFolder": "Klasör Yükle"},+ "newDocumentButton": "Yeni Belge",+ "newNoteDialog": {+ "cancel": "İptal",+ "editTitle": "Belgeyi Düzenle",+ "emptyContent": "Belge içeriği boş olamaz",+ "loadError": "Belge yüklenemedi, lütfen tekrar deneyin",+ "loading": "Yükleniyor...",+ "save": "Kaydet",+ "saveError": "Belge kaydedilemedi, lütfen tekrar deneyin",+ "saveSuccess": "Belge başarıyla kaydedildi",+ "title": "Yeni Belge",+ "updateSuccess": "Belge başarıyla güncellendi"+ },"uploadButton": "Yükle"},+ "home": {+ "getStarted": "Başlarken",+ "greeting": "Başla",+ "quickActions": "Hızlı İşlemler",+ "recentDocuments": "Son Belgeler",+ "recentFiles": "Son Dosyalar",+ "subtitle": "Bilgi tabanına hoş geldiniz, belgelerinizi buradan yönetin",+ "uploadEntries": {+ "files": {+ "title": "Dosya Yükle"+ },+ "folder": {+ "title": "Klasör Yükle"+ },+ "knowledgeBase": {+ "title": "Yeni Bilgi Tabanı"+ },+ "newDocument": {+ "title": "Yeni Belge"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Bu bilgi tabanı silinecek, içindeki dosyalar silinmeyecek, tüm dosyalar içine taşınacaktır. Bilgi tabanı silindikten sonra geri alınamaz, lütfen dikkatli olun.",@@ -38,6 +113,10 @@"new": "Yeni Bilgi Tabanı","title": "Bilgi Tabanı"},+ "menu": {+ "allDocuments": "Tüm Belgeler",+ "allFiles": "Tüm Dosyalar"+ },"networkError": "Bilgi bankası alınamadı, lütfen ağ bağlantınızı kontrol edip tekrar deneyin","notSupportGuide": {"desc": "Mevcut dağıtım örneği istemci veritabanı modunda, dosya yönetim işlevini kullanamazsınız. Lütfen <1>sunucu veritabanı dağıtım moduna</1> geçin veya doğrudan <3>LobeChat Cloud</3> kullanın.",@@ -61,12 +140,16 @@"downloadFile": "Dosyayı İndir","unsupportedFileAndContact": "Bu dosya formatı çevrimiçi önizleme için desteklenmiyor. Önizleme talebiniz varsa, lütfen <1>bize geri bildirimde bulunun</1>."},+ "searchDocumentPlaceholder": "Belge ara","searchFilePlaceholder": "Dosya Ara","tab": {- "all": "Tüm Dosyalar",+ "all": "Tümü","audios": "Sesler","documents": "Belgeler",+ "home": "Ana Sayfa","images": "Görseller",+ "moreTypes": "Daha Fazla Tür",+ "pages": "Belgeler","videos": "Videolar","websites": "Web Siteleri"},diff --git a/locales/vi-VN/common.json b/locales/vi-VN/common.jsonindex 3b69ec63527..6fc543f8791 100644--- a/locales/vi-VN/common.json+++ b/locales/vi-VN/common.json@@ -286,6 +286,7 @@"oauth": "Đăng nhập SSO","officialSite": "Trang web chính thức","ok": "Đồng ý",+ "or": "hoặc","password": "Mật khẩu","pin": "Ghim","pinOff": "Bỏ ghim",diff --git a/locales/vi-VN/file.json b/locales/vi-VN/file.jsonindex e0c53b276f2..efda65d4d4a 100644--- a/locales/vi-VN/file.json+++ b/locales/vi-VN/file.json@@ -1,5 +1,7 @@{- "desc": "Quản lý kiến thức của bạn",+ "addKnowledge": "Thêm kiến thức",+ "addPage": "Tạo tài liệu",+ "desc": "Quản lý kiến thức công việc, học tập và cuộc sống của bạn.","detail": {"basic": {"createdAt": "Thời gian tạo",@@ -21,6 +23,44 @@"embeddingStatus": "Trạng thái vector hóa"}},+ "documentEditor": {+ "addIcon": "Thêm biểu tượng",+ "autoSaveMessage": "Tài liệu sẽ được tự động lưu, không cần lưu thủ công",+ "chooseIcon": "Chọn biểu tượng",+ "deleteConfirm": {+ "content": "Tài liệu này sẽ bị xóa và không thể khôi phục. Vui lòng cẩn trọng.",+ "title": "Xóa tài liệu"+ },+ "deleteError": "Xóa tài liệu thất bại",+ "deleteSuccess": "Xóa tài liệu thành công",+ "editedAt": "Chỉnh sửa lần cuối vào {{time}}",+ "editedBy": "Người chỉnh sửa cuối cùng: {{name}}",+ "editorPlaceholder": "Nhập nội dung tài liệu, nhấn / để mở menu lệnh",+ "empty": {+ "createNewDocument": "Tạo tài liệu mới",+ "title": "Chọn một tài liệu để bắt đầu",+ "uploadMarkdown": "Tải lên tệp Markdown"+ },+ "linkCopied": "Đã sao chép liên kết",+ "menu": {+ "copyLink": "Sao chép liên kết",+ "exportDocument": "Xuất tài liệu",+ "importDocument": "Nhập tài liệu",+ "pin": "Ghim tài liệu"+ },+ "saving": "Đang lưu...",+ "titlePlaceholder": "Không có tiêu đề",+ "wordCount": "{{wordCount}} từ"+ },+ "documentList": {+ "copyContent": "Sao chép toàn bộ nội dung",+ "documentCount": "Tổng cộng {{count}} tài liệu",+ "duplicate": "Tạo bản sao",+ "empty": "Chưa có tài liệu nào, nhấn nút phía trên để tạo tài liệu đầu tiên của bạn",+ "noResults": "Không tìm thấy tài liệu phù hợp",+ "selectNote": "Chọn một tài liệu để bắt đầu chỉnh sửa",+ "untitled": "Không có tiêu đề"+ },"empty": "Chưa có tệp/tệp tin nào được tải lên","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "Tải tệp lên","uploadFolder": "Tải thư mục lên"},+ "newDocumentButton": "Tạo tài liệu mới",+ "newNoteDialog": {+ "cancel": "Hủy",+ "editTitle": "Chỉnh sửa tài liệu",+ "emptyContent": "Nội dung tài liệu không được để trống",+ "loadError": "Tải tài liệu thất bại, vui lòng thử lại",+ "loading": "Đang tải...",+ "save": "Lưu",+ "saveError": "Lưu tài liệu thất bại, vui lòng thử lại",+ "saveSuccess": "Lưu tài liệu thành công",+ "title": "Tạo tài liệu mới",+ "updateSuccess": "Cập nhật tài liệu thành công"+ },"uploadButton": "Tải lên"},+ "home": {+ "getStarted": "Bắt đầu",+ "greeting": "Bắt đầu",+ "quickActions": "Hành động nhanh",+ "recentDocuments": "Tài liệu gần đây",+ "recentFiles": "Tệp gần đây",+ "subtitle": "Chào mừng đến với kho tri thức, bắt đầu quản lý tài liệu của bạn từ đây",+ "uploadEntries": {+ "files": {+ "title": "Tải lên tệp"+ },+ "folder": {+ "title": "Tải lên thư mục"+ },+ "knowledgeBase": {+ "title": "Tạo kho kiến thức mới"+ },+ "newDocument": {+ "title": "Tạo tài liệu mới"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "Bạn sắp xóa kho tri thức này, các tệp trong đó sẽ không bị xóa mà sẽ được chuyển vào tất cả tệp. Kho tri thức sau khi xóa sẽ không thể khôi phục, vui lòng cẩn thận khi thực hiện.",@@ -38,6 +113,10 @@"new": "Tạo kho tri thức mới","title": "Kho tri thức"},+ "menu": {+ "allDocuments": "Tất cả tài liệu",+ "allFiles": "Tất cả tệp"+ },"networkError": "Không thể lấy kho tri thức, vui lòng kiểm tra kết nối mạng và thử lại","notSupportGuide": {"desc": "Phiên bản triển khai hiện tại là chế độ cơ sở dữ liệu khách hàng, không thể sử dụng chức năng quản lý tệp. Vui lòng chuyển sang <1>chế độ triển khai cơ sở dữ liệu máy chủ</1>, hoặc sử dụng trực tiếp <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "Tải tệp","unsupportedFileAndContact": "Định dạng tệp này hiện không hỗ trợ xem trước trực tuyến. Nếu bạn có yêu cầu xem trước, vui lòng <1>phản hồi cho chúng tôi</1>"},+ "searchDocumentPlaceholder": "Tìm kiếm tài liệu","searchFilePlaceholder": "Tìm kiếm tệp","tab": {- "all": "Tất cả tệp",+ "all": "Tất cả","audios": "Âm thanh","documents": "Tài liệu",+ "home": "Trang chủ","images": "Hình ảnh",+ "moreTypes": "Thêm loại",+ "pages": "Bản thảo","videos": "Video","websites": "Trang web"},diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 1f55cd09910..acaf1f8a22d 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -286,6 +286,7 @@"oauth": "SSO 登录","officialSite": "官方网站","ok": "确定",+ "or": "或","password": "密码","pin": "置顶","pinOff": "取消置顶",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 96f5cd7fc4b..0d9272ead46 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -1,5 +1,7 @@{- "desc": "管理你的知识",+ "addKnowledge": "添加知识",+ "addPage": "创建文稿",+ "desc": "管理你的工作、学习与生活知识。","detail": {"basic": {"createdAt": "创建时间",@@ -21,6 +23,44 @@"embeddingStatus": "向量化"}},+ "documentEditor": {+ "addIcon": "添加图标",+ "autoSaveMessage": "文档会自动保存,无需手动保存",+ "chooseIcon": "选择图标",+ "deleteConfirm": {+ "content": "即将删除该文档,删除后将不可恢复,请谨慎操作。",+ "title": "删除文档"+ },+ "deleteError": "删除文档失败",+ "deleteSuccess": "文档删除成功",+ "editedAt": "最后编辑于 {{time}}",+ "editedBy": "最后编辑者 {{name}}",+ "editorPlaceholder": "输入文档内容,按 / 打开命令菜单",+ "empty": {+ "createNewDocument": "创建新文档",+ "title": "选择一个文档以开始",+ "uploadMarkdown": "上传 Markdown 文件"+ },+ "linkCopied": "链接已复制",+ "menu": {+ "copyLink": "复制链接",+ "exportDocument": "导出文档",+ "importDocument": "导入文档",+ "pin": "置顶文档"+ },+ "saving": "保存中...",+ "titlePlaceholder": "无标题",+ "wordCount": "{{wordCount}} 字"+ },+ "documentList": {+ "copyContent": "复制全文",+ "documentCount": "共 {{count}} 个文档",+ "duplicate": "创建副本",+ "empty": "暂无文档,点击上方按钮创建你的第一篇文档",+ "noResults": "未找到匹配的文档",+ "selectNote": "选择一个文档开始编辑",+ "untitled": "无标题"+ },"empty": "暂无已上传文件/文件夹","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "上传文件","uploadFolder": "上传文件夹"},+ "newDocumentButton": "新建文档",+ "newNoteDialog": {+ "cancel": "取消",+ "editTitle": "编辑文档",+ "emptyContent": "文档内容不能为空",+ "loadError": "加载文档失败,请重试",+ "loading": "加载中...",+ "save": "保存",+ "saveError": "保存文档失败,请重试",+ "saveSuccess": "文档保存成功",+ "title": "新建文档",+ "updateSuccess": "文档更新成功"+ },"uploadButton": "上传"},+ "home": {+ "getStarted": "开始使用",+ "greeting": "开始",+ "quickActions": "快捷操作",+ "recentDocuments": "最近文档",+ "recentFiles": "最近文件",+ "subtitle": "欢迎使用知识库,从这里开始管理你的文档和文档",+ "uploadEntries": {+ "files": {+ "title": "上传文件"+ },+ "folder": {+ "title": "上传文件夹"+ },+ "knowledgeBase": {+ "title": "新建知识库"+ },+ "newDocument": {+ "title": "新建文档"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "即将删除该知识库,其中的文件不会删除,将移入全部文件中。知识库删除后将不可恢复,请谨慎操作。",@@ -38,6 +113,10 @@"new": "新建知识库","title": "知识库"},+ "menu": {+ "allDocuments": "全部文档",+ "allFiles": "全部文件"+ },"networkError": "获取知识库失败,请检测网络连接后重试","notSupportGuide": {"desc": "当前部署实例为客户端数据库模式,无法使用文件管理功能。请切换到<1>服务端数据库部署模式</1>,或直接使用 <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "下载文件","unsupportedFileAndContact": "此文件格式暂不支持在线预览,如有预览诉求,欢迎<1>反馈给我们</1>"},+ "searchDocumentPlaceholder": "搜索文档","searchFilePlaceholder": "搜索文件","tab": {- "all": "全部文件",+ "all": "全部","audios": "语音","documents": "文档",+ "home": "首页","images": "图片",+ "moreTypes": "更多类型",+ "pages": "文稿","videos": "视频","websites": "网页"},diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.jsonindex 1f0835705b6..7ce31269bd1 100644--- a/locales/zh-TW/common.json+++ b/locales/zh-TW/common.json@@ -286,6 +286,7 @@"oauth": "單一登錄(SSO)","officialSite": "官方網站","ok": "確定",+ "or": "或","password": "密碼","pin": "置頂","pinOff": "取消置頂",diff --git a/locales/zh-TW/file.json b/locales/zh-TW/file.jsonindex 2784c53bec0..d602f43382d 100644--- a/locales/zh-TW/file.json+++ b/locales/zh-TW/file.json@@ -1,5 +1,7 @@{- "desc": "管理你的知識",+ "addKnowledge": "新增知識",+ "addPage": "建立文稿",+ "desc": "管理你的工作、學習與生活知識。","detail": {"basic": {"createdAt": "創建時間",@@ -21,6 +23,44 @@"embeddingStatus": "向量化"}},+ "documentEditor": {+ "addIcon": "新增圖示",+ "autoSaveMessage": "文件會自動儲存,無需手動儲存",+ "chooseIcon": "選擇圖示",+ "deleteConfirm": {+ "content": "即將刪除此文件,刪除後將無法恢復,請謹慎操作。",+ "title": "刪除文件"+ },+ "deleteError": "刪除文件失敗",+ "deleteSuccess": "文件刪除成功",+ "editedAt": "最後編輯於 {{time}}",+ "editedBy": "最後編輯者 {{name}}",+ "editorPlaceholder": "輸入文件內容,按 / 開啟指令選單",+ "empty": {+ "createNewDocument": "建立新文件",+ "title": "選擇一個文件以開始",+ "uploadMarkdown": "上傳 Markdown 檔案"+ },+ "linkCopied": "連結已複製",+ "menu": {+ "copyLink": "複製連結",+ "exportDocument": "匯出文件",+ "importDocument": "匯入文件",+ "pin": "置頂文件"+ },+ "saving": "儲存中...",+ "titlePlaceholder": "無標題",+ "wordCount": "{{wordCount}} 字"+ },+ "documentList": {+ "copyContent": "複製全文",+ "documentCount": "共 {{count}} 筆文件",+ "duplicate": "建立副本",+ "empty": "尚無文件,點擊上方按鈕建立你的第一篇文件",+ "noResults": "找不到符合的文件",+ "selectNote": "選擇一個文件開始編輯",+ "untitled": "無標題"+ },"empty": "暫無已上傳文件/文件夾","header": {"actions": {@@ -28,8 +68,43 @@"uploadFile": "上傳檔案","uploadFolder": "上傳資料夾"},+ "newDocumentButton": "新增文件",+ "newNoteDialog": {+ "cancel": "取消",+ "editTitle": "編輯文件",+ "emptyContent": "文件內容不可為空",+ "loadError": "載入文件失敗,請重試",+ "loading": "載入中...",+ "save": "儲存",+ "saveError": "儲存文件失敗,請重試",+ "saveSuccess": "文件儲存成功",+ "title": "新增文件",+ "updateSuccess": "文件更新成功"+ },"uploadButton": "上傳"},+ "home": {+ "getStarted": "開始使用",+ "greeting": "開始",+ "quickActions": "快速操作",+ "recentDocuments": "最近文件",+ "recentFiles": "最近檔案",+ "subtitle": "歡迎使用知識庫,從這裡開始管理你的文件與資料",+ "uploadEntries": {+ "files": {+ "title": "上傳檔案"+ },+ "folder": {+ "title": "上傳資料夾"+ },+ "knowledgeBase": {+ "title": "新增知識庫"+ },+ "newDocument": {+ "title": "新增文件"+ }+ }+ },"knowledgeBase": {"list": {"confirmRemoveKnowledgeBase": "即將刪除該知識庫,其中的檔案不會刪除,將移入全部檔案中。知識庫刪除後將不可恢復,請謹慎操作。",@@ -38,6 +113,10 @@"new": "新建知識庫","title": "知識庫"},+ "menu": {+ "allDocuments": "全部文件",+ "allFiles": "所有檔案"+ },"networkError": "獲取知識庫失敗,請檢查網路連接後重試","notSupportGuide": {"desc": "當前部署實例為客戶端資料庫模式,無法使用檔案管理功能。請切換到<1>伺服器端資料庫部署模式</1>,或直接使用 <3>LobeChat Cloud</3>",@@ -61,12 +140,16 @@"downloadFile": "下載檔案","unsupportedFileAndContact": "此檔案格式暫不支援線上預覽,如有預覽需求,歡迎<1>反饋給我們</1>"},+ "searchDocumentPlaceholder": "搜尋文件","searchFilePlaceholder": "搜索檔案","tab": {- "all": "全部檔案",+ "all": "全部","audios": "語音","documents": "文檔",+ "home": "首頁","images": "圖片",+ "moreTypes": "更多類型",+ "pages": "文稿","videos": "視頻","websites": "網頁"},diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.tsindex 91a1582f738..f7859ecf26a 100644--- a/packages/database/src/models/__tests__/file.test.ts+++ b/packages/database/src/models/__tests__/file.test.ts@@ -4,7 +4,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { FilesTabs, SortType } from '@/types/files';-import { chunks, embeddings, fileChunks, files, globalFiles, knowledgeBaseFiles, knowledgeBases, users } from '../../schemas';+import {+ chunks,+ embeddings,+ fileChunks,+ files,+ globalFiles,+ knowledgeBaseFiles,+ knowledgeBases,+ users,+} from '../../schemas';import { LobeChatDatabase } from '../../type';import { FileModel } from '../file';import { getTestDB } from './_util';@@ -340,13 +349,15 @@ describe('FileModel', () => {];it('should query files for the user', async () => {- await fileModel.create({+ const file1 = await fileModel.create({name: 'test-file-1.txt',url: 'https://example.com/test-file-1.txt',size: 100,fileType: 'text/plain',});- await fileModel.create({+ // Add a small delay to ensure different timestamps+ await new Promise((resolve) => setTimeout(resolve, 10));+ const file2 = await fileModel.create({name: 'test-file-2.txt',url: 'https://example.com/test-file-2.txt',size: 200,@@ -362,8 +373,9 @@ describe('FileModel', () => {const userFiles = await fileModel.query();expect(userFiles).toHaveLength(2);- expect(userFiles[0].name).toBe('test-file-2.txt');- expect(userFiles[1].name).toBe('test-file-1.txt');+ // file2 should be first since it was created more recently+ expect(userFiles[0].id).toBe(file2.id);+ expect(userFiles[1].id).toBe(file1.id);});it('should filter files by name', async () => {@@ -381,6 +393,14 @@ describe('FileModel', () => {expect(imageFiles[0].name).toBe('image.jpg');});+ it('should filter audio files by category', async () => {+ await serverDB.insert(files).values(sharedFileList);++ const audioFiles = await fileModel.query({ category: FilesTabs.Audios });+ expect(audioFiles).toHaveLength(1);+ expect(audioFiles[0].name).toBe('audio.mp3');+ });+it('should sort files by name in ascending order', async () => {await serverDB.insert(files).values(sharedFileList);@@ -1022,8 +1042,58 @@ describe('FileModel', () => {});describe('private getFileTypePrefix method', () => {+ beforeEach(async () => {+ // Create test files for all categories+ await serverDB.insert(files).values([+ {+ id: 'video-file',+ name: 'video.mp4',+ url: 'https://example.com/video.mp4',+ size: 1000,+ fileType: 'video/mp4',+ userId,+ },+ {+ id: 'page-file',+ name: 'page.html',+ url: 'https://example.com/page.html',+ size: 500,+ fileType: 'text/html',+ userId,+ },+ {+ id: 'unknown-file',+ name: 'unknown.xyz',+ url: 'https://example.com/unknown.xyz',+ size: 200,+ fileType: 'application/xyz',+ userId,+ },+ ]);+ });++ it('should filter video files correctly', async () => {+ const result = await fileModel.query({ category: FilesTabs.Videos });+ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('video-file');+ });++ it('should filter website/page files correctly', async () => {+ const result = await fileModel.query({ category: FilesTabs.Websites });+ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('page-file');+ });++ it('should handle Pages category (should use text/html like Websites)', async () => {+ // FilesTabs.Pages is not explicitly handled in switch, falls to default+ // which returns empty string, so it won't filter by file type+ const result = await fileModel.query({ category: FilesTabs.Pages });+ // Should return all files since default case returns empty string+ expect(result.length).toBeGreaterThan(0);+ });+it('should handle unknown file category', async () => {- // This tests the default case in switch statement (line 312-313)+ // This tests the default case in switch statementconst unknownCategory = 'unknown' as FilesTabs;// We need to access the private method indirectly by testing the query method@@ -1059,7 +1129,7 @@ describe('FileModel', () => {// Note: This is a simplified test since we can't easily create 3000+ chunks// But it will still exercise the batch deletion code path- // Insert chunks (this might need to be done through proper API)+ // Insert chunks (this might need to be done through proper API)// For testing purposes, we'll delete the file which should trigger the batch deletionawait fileModel.delete(fileId, true);@@ -1112,9 +1182,9 @@ describe('FileModel', () => {// 插入embeddings (1024维向量)const testEmbedding = new Array(1024).fill(0.1);- await serverDB.insert(embeddings).values([- { chunkId: chunkId1, embeddings: testEmbedding, model: 'test-model', userId },- ]);+ await serverDB+ .insert(embeddings)+ .values([{ chunkId: chunkId1, embeddings: testEmbedding, model: 'test-model', userId }]);// 跳过 documentChunks 测试,因为需要先创建 documents 记录@@ -1163,20 +1233,18 @@ describe('FileModel', () => {const chunkId = '550e8400-e29b-41d4-a716-446655440003';// 插入chunk- await serverDB.insert(chunks).values([- { id: chunkId, text: 'complete test chunk', userId, type: 'text' },- ]);+ await serverDB+ .insert(chunks)+ .values([{ id: chunkId, text: 'complete test chunk', userId, type: 'text' }]);// 插入fileChunks关联- await serverDB.insert(fileChunks).values([- { fileId, chunkId, userId },- ]);+ await serverDB.insert(fileChunks).values([{ fileId, chunkId, userId }]);// 插入embeddingsconst testEmbedding = new Array(1024).fill(0.1);- await serverDB.insert(embeddings).values([- { chunkId, embeddings: testEmbedding, model: 'test-model', userId },- ]);+ await serverDB+ .insert(embeddings)+ .values([{ chunkId, embeddings: testEmbedding, model: 'test-model', userId }]);// 删除文件await fileModel.delete(fileId, true);@@ -1206,7 +1274,6 @@ describe('FileModel', () => {expect(remainingFileChunks).toHaveLength(0);});-it('should delete files that are in knowledge bases (removed protection)', async () => {// 测试修复后的逻辑:知识库中的文件也应该被删除const testFile = {@@ -1223,19 +1290,17 @@ describe('FileModel', () => {const chunkId = '550e8400-e29b-41d4-a716-446655440007';// 插入chunk和关联数据- await serverDB.insert(chunks).values([- { id: chunkId, text: 'knowledge base chunk', userId, type: 'text' },- ]);+ await serverDB+ .insert(chunks)+ .values([{ id: chunkId, text: 'knowledge base chunk', userId, type: 'text' }]);- await serverDB.insert(fileChunks).values([- { fileId, chunkId, userId },- ]);+ await serverDB.insert(fileChunks).values([{ fileId, chunkId, userId }]);// 插入embeddings (1024维向量)const testEmbedding = new Array(1024).fill(0.1);- await serverDB.insert(embeddings).values([- { chunkId, embeddings: testEmbedding, model: 'test-model', userId },- ]);+ await serverDB+ .insert(embeddings)+ .values([{ chunkId, embeddings: testEmbedding, model: 'test-model', userId }]);// 验证文件确实在知识库中const kbFile = await serverDB.query.knowledgeBaseFiles.findFirst({diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex 27d2a2cda31..eb03c74ccfe 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -211,9 +211,17 @@ export class FileModel {q ? ilike(files.name, `%${q}%`) : undefined,eq(files.userId, this.userId),);- if (category && category !== FilesTabs.All) {+ if (category && category !== FilesTabs.All && category !== FilesTabs.Home) {const fileTypePrefix = this.getFileTypePrefix(category as FilesTabs);- whereClause = and(whereClause, ilike(files.fileType, `${fileTypePrefix}%`));+ if (Array.isArray(fileTypePrefix)) {+ // For multiple file types (e.g., Documents includes 'application' and 'custom')+ whereClause = and(+ whereClause,+ or(...fileTypePrefix.map((prefix) => ilike(files.fileType, `${prefix}%`))),+ );+ } else {+ whereClause = and(whereClause, ilike(files.fileType, `${fileTypePrefix}%`));+ }}// 2. order part@@ -308,13 +316,13 @@ export class FileModel {/*** get the corresponding file type prefix according to FilesTabs*/- private getFileTypePrefix = (category: FilesTabs): string => {+ private getFileTypePrefix = (category: FilesTabs): string | string[] => {switch (category) {case FilesTabs.Audios: {return 'audio';}case FilesTabs.Documents: {- return 'application';+ return ['application', 'custom'];}case FilesTabs.Images: {return 'image';@@ -322,6 +330,9 @@ export class FileModel {case FilesTabs.Videos: {return 'video';}+ case FilesTabs.Websites: {+ return 'text/html';+ }default: {return '';}diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.tsnew file mode 100644index 00000000000..59a4c96b853--- /dev/null+++ b/packages/database/src/repositories/knowledge/index.test.ts@@ -0,0 +1,300 @@+// @vitest-environment node+import { FilesTabs } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../models/__tests__/_util';+import { NewDocument, documents } from '../../schemas/document';+import { NewFile, files } from '../../schemas/file';+import { users } from '../../schemas/user';+import { LobeChatDatabase } from '../../type';+import { KnowledgeRepo } from './index';++const userId = 'knowledge-test-user';+const otherUserId = 'other-knowledge-user';++let knowledgeRepo: KnowledgeRepo;++const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ // Clean up+ await serverDB.delete(users);++ // Create test users+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ // Initialize repo+ knowledgeRepo = new KnowledgeRepo(serverDB, userId);+});++describe('KnowledgeRepo', () => {+ describe('query - Documents category filtering', () => {+ beforeEach(async () => {+ // Create test files+ const testFiles: NewFile[] = [+ {+ fileType: 'application/pdf',+ name: 'regular-pdf-file.pdf',+ size: 1024,+ url: 'file-pdf-url',+ userId,+ },+ {+ fileType: 'custom/other',+ name: 'custom-file.txt',+ size: 512,+ url: 'custom-file-url',+ userId,+ },+ ];++ await serverDB.insert(files).values(testFiles);++ // Create test documents+ const testDocuments: NewDocument[] = [+ // This should be EXCLUDED (sourceType='file')+ {+ content: 'PDF from file upload',+ fileType: 'application/pdf',+ filename: 'uploaded-pdf.pdf',+ source: 'upload-source',+ sourceType: 'file',+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ },+ // This should be EXCLUDED (fileType='custom/document')+ {+ content: 'Editor document',+ fileType: 'custom/document',+ filename: 'editor-doc.md',+ source: 'editor-source',+ sourceType: 'file',+ totalCharCount: 200,+ totalLineCount: 20,+ userId,+ },+ // This should be INCLUDED (application/pdf with sourceType='api')+ {+ content: 'PDF from API',+ fileType: 'application/pdf',+ filename: 'api-pdf.pdf',+ source: 'api-source',+ sourceType: 'api',+ totalCharCount: 300,+ totalLineCount: 30,+ userId,+ },+ // This should be INCLUDED (custom/other with sourceType='web')+ {+ content: 'Custom web document',+ fileType: 'custom/other',+ filename: 'web-doc.txt',+ source: 'web-source',+ sourceType: 'web',+ totalCharCount: 400,+ totalLineCount: 40,+ userId,+ },+ ];++ await serverDB.insert(documents).values(testDocuments);+ });++ it('should exclude documents with fileType="custom/document" from Documents category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Documents });++ // Should not include editor document (custom/document)+ const editorDoc = results.find((item) => item.name === 'editor-doc.md');+ expect(editorDoc).toBeUndefined();+ });++ it('should exclude documents with sourceType="file" from Documents category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Documents });++ // Should not include uploaded PDF document (sourceType='file')+ const uploadedPdf = results.find((item) => item.name === 'uploaded-pdf.pdf');+ expect(uploadedPdf).toBeUndefined();+ });++ it('should include documents with sourceType="api" in Documents category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Documents });++ // Should include API PDF (application/pdf with sourceType='api')+ const apiPdf = results.find((item) => item.name === 'api-pdf.pdf');+ expect(apiPdf).toBeDefined();+ expect(apiPdf?.sourceType).toBe('document');+ expect(apiPdf?.fileType).toBe('application/pdf');+ });++ it('should include documents with sourceType="web" in Documents category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Documents });++ // Should include web document (custom/other with sourceType='web')+ const webDoc = results.find((item) => item.name === 'web-doc.txt');+ expect(webDoc).toBeDefined();+ expect(webDoc?.sourceType).toBe('document');+ expect(webDoc?.fileType).toBe('custom/other');+ });++ it('should include files from files table in Documents category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Documents });++ // Should include regular files+ const regularFile = results.find((item) => item.name === 'regular-pdf-file.pdf');+ expect(regularFile).toBeDefined();+ expect(regularFile?.sourceType).toBe('file');+ });++ it('should show all documents in All category (no filtering)', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.All });++ // All category should include everything+ expect(results.length).toBeGreaterThanOrEqual(6); // 2 files + 4 documents++ const editorDoc = results.find((item) => item.name === 'editor-doc.md');+ const uploadedPdf = results.find((item) => item.name === 'uploaded-pdf.pdf');++ expect(editorDoc).toBeDefined();+ expect(uploadedPdf).toBeDefined();+ });++ it('should apply both filters together in Documents category', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.Documents });++ // Count documents with sourceType='document'+ const documentTypeItems = results.filter((item) => item.sourceType === 'document');++ // Should have exactly 2 documents (api-pdf and web-doc)+ // Excluded: uploaded-pdf (sourceType='file') and editor-doc (fileType='custom/document')+ expect(documentTypeItems).toHaveLength(2);++ const names = documentTypeItems.map((item) => item.name).sort();+ expect(names).toEqual(['api-pdf.pdf', 'web-doc.txt']);+ });+ });++ describe('query - user isolation', () => {+ beforeEach(async () => {+ // Create files for current user+ await serverDB.insert(files).values({+ fileType: 'application/pdf',+ name: 'user-file.pdf',+ size: 1024,+ url: 'user-file-url',+ userId,+ });++ // Create files for other user+ await serverDB.insert(files).values({+ fileType: 'application/pdf',+ name: 'other-user-file.pdf',+ size: 1024,+ url: 'other-file-url',+ userId: otherUserId,+ });++ // Create documents for current user+ await serverDB.insert(documents).values({+ content: 'User document',+ fileType: 'application/pdf',+ filename: 'user-doc.pdf',+ source: 'user-source',+ sourceType: 'api',+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ });++ // Create documents for other user+ await serverDB.insert(documents).values({+ content: 'Other user document',+ fileType: 'application/pdf',+ filename: 'other-doc.pdf',+ source: 'other-source',+ sourceType: 'api',+ totalCharCount: 100,+ totalLineCount: 10,+ userId: otherUserId,+ });+ });++ it('should only return current user items', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.All });++ // Should only have items from current user+ expect(results).toHaveLength(2);++ const names = results.map((item) => item.name).sort();+ expect(names).toEqual(['user-doc.pdf', 'user-file.pdf']);++ // Should not include other user's items+ const otherUserFile = results.find((item) => item.name === 'other-user-file.pdf');+ const otherUserDoc = results.find((item) => item.name === 'other-doc.pdf');++ expect(otherUserFile).toBeUndefined();+ expect(otherUserDoc).toBeUndefined();+ });+ });++ describe('query - search filtering', () => {+ beforeEach(async () => {+ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ name: 'report-2024.pdf',+ size: 1024,+ url: 'report-url',+ userId,+ },+ {+ fileType: 'application/pdf',+ name: 'invoice.pdf',+ size: 512,+ url: 'invoice-url',+ userId,+ },+ ]);++ await serverDB.insert(documents).values([+ {+ content: 'Annual report content',+ fileType: 'application/pdf',+ filename: 'annual-report.pdf',+ source: 'api-source',+ sourceType: 'api',+ title: 'Annual Report',+ totalCharCount: 1000,+ totalLineCount: 100,+ userId,+ },+ {+ content: 'Meeting notes',+ fileType: 'custom/other',+ filename: 'notes.txt',+ source: 'web-source',+ sourceType: 'web',+ title: 'Meeting Notes',+ totalCharCount: 500,+ totalLineCount: 50,+ userId,+ },+ ]);+ });++ it('should filter by search query in file names', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.All, q: 'report' });++ expect(results).toHaveLength(2);+ const names = results.map((item) => item.name).sort();+ expect(names).toEqual(['Annual Report', 'report-2024.pdf']);+ });++ it('should filter by search query in document titles', async () => {+ const results = await knowledgeRepo.query({ category: FilesTabs.All, q: 'meeting' });++ expect(results).toHaveLength(1);+ expect(results[0].name).toBe('Meeting Notes');+ });+ });+});diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.tsnew file mode 100644index 00000000000..66b2bfd0ce4--- /dev/null+++ b/packages/database/src/repositories/knowledge/index.ts@@ -0,0 +1,420 @@+import { FilesTabs, QueryFileListParams, SortType } from '@lobechat/types';+import { sql } from 'drizzle-orm';++import { DocumentModel } from '../../models/document';+import { FileModel } from '../../models/file';+import { documents, files, knowledgeBaseFiles } from '../../schemas';+import { LobeChatDatabase } from '../../type';++export interface KnowledgeItem {+ chunkTaskId?: string | null;+ content?: string | null;+ createdAt: Date;+ editorData?: Record<string, any> | null;+ embeddingTaskId?: string | null;+ fileType: string;+ id: string;+ metadata?: Record<string, any> | null;+ name: string;+ size: number;+ /**+ * Source type to distinguish between files and documents+ * - 'file': from files table+ * - 'document': from documents table+ */+ sourceType: 'file' | 'document';+ updatedAt: Date;+ url?: string;+}++/**+ * Knowledge Repository - combines files and documents into a unified interface+ */+export class KnowledgeRepo {+ private userId: string;+ private db: LobeChatDatabase;+ private fileModel: FileModel;+ private documentModel: DocumentModel;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ this.fileModel = new FileModel(db, userId);+ this.documentModel = new DocumentModel(db, userId);+ }++ /**+ * Query combined results from files and documents tables+ */+ async query({+ category,+ q,+ sortType,+ sorter,+ knowledgeBaseId,+ showFilesInKnowledgeBase,+ }: QueryFileListParams = {}): Promise<KnowledgeItem[]> {+ // Build file query+ const fileQuery = this.buildFileQuery({+ category,+ knowledgeBaseId,+ q,+ showFilesInKnowledgeBase,+ sortType,+ sorter,+ });++ // Build document query (notes)+ const documentQuery = this.buildDocumentQuery({+ category,+ knowledgeBaseId,+ q,+ sortType,+ sorter,+ });++ // Combine both queries with UNION ALL+ const combinedQuery = sql`+ (${fileQuery})+ UNION ALL+ (${documentQuery})+ `;++ // Add final ordering+ const orderClause = this.buildOrderClause(sortType, sorter);+ const finalQuery = sql`+ SELECT * FROM (${combinedQuery}) as combined+ ORDER BY ${orderClause}+ `;++ const result = await this.db.execute(finalQuery);++ const mappedResults = result.rows.map((row: any) => {+ // Parse editor_data if it's a string (raw SQL returns JSONB as string)+ let editorData = row.editor_data;+ if (typeof editorData === 'string') {+ try {+ editorData = JSON.parse(editorData);+ } catch (e) {+ console.error('[KnowledgeRepo] Failed to parse editor_data:', e);+ editorData = null;+ }+ }++ // Parse metadata if it's a string (raw SQL returns JSONB as string)+ let metadata = row.metadata;+ if (typeof metadata === 'string') {+ try {+ metadata = JSON.parse(metadata);+ } catch (e) {+ console.error('[KnowledgeRepo] Failed to parse metadata:', e);+ metadata = null;+ }+ }++ return {+ chunkTaskId: row.chunk_task_id,+ content: row.content,+ createdAt: new Date(row.created_at),+ editorData,+ embeddingTaskId: row.embedding_task_id,+ fileType: row.file_type,+ id: row.id,+ metadata,+ name: row.name,+ size: Number(row.size),+ sourceType: row.source_type,+ updatedAt: new Date(row.updated_at),+ url: row.url,+ };+ });++ console.log('[KnowledgeRepo.query] Fetched items:', {+ count: mappedResults.length,+ documents: mappedResults.filter((item) => item.sourceType === 'document'),+ sampleEditorData: mappedResults.find((item) => item.sourceType === 'document')?.editorData,+ });++ return mappedResults;+ }++ /**+ * Delete item by id - routes to appropriate model based on sourceType+ */+ async deleteItem(id: string, sourceType: 'file' | 'document'): Promise<void> {+ if (sourceType === 'file') {+ await this.fileModel.delete(id);+ } else {+ await this.documentModel.delete(id);+ }+ }++ /**+ * Batch delete items+ */+ async deleteMany(items: Array<{ id: string; sourceType: 'file' | 'document' }>): Promise<void> {+ const fileIds = items.filter((item) => item.sourceType === 'file').map((item) => item.id);+ const documentIds = items+ .filter((item) => item.sourceType === 'document')+ .map((item) => item.id);++ await Promise.all([+ fileIds.length > 0 ? this.fileModel.deleteMany(fileIds) : Promise.resolve(),+ documentIds.length > 0+ ? Promise.all(documentIds.map((id) => this.documentModel.delete(id)))+ : Promise.resolve(),+ ]);+ }++ /**+ * Find item by id+ */+ async findById(id: string, sourceType: 'file' | 'document'): Promise<any> {+ if (sourceType === 'file') {+ return this.fileModel.findById(id);+ } else {+ return this.documentModel.findById(id);+ }+ }++ private buildFileQuery({+ category,+ q,+ knowledgeBaseId,+ showFilesInKnowledgeBase,+ }: QueryFileListParams = {}): ReturnType<typeof sql> {+ let whereConditions: any[] = [sql`${files.userId} = ${this.userId}`];++ // Search filter+ if (q) {+ whereConditions.push(sql`${files.name} ILIKE ${`%${q}%`}`);+ }++ // Category filter+ if (category && category !== FilesTabs.All && category !== FilesTabs.Home) {+ const fileTypePrefix = this.getFileTypePrefix(category as FilesTabs);+ if (Array.isArray(fileTypePrefix)) {+ // For multiple file types (e.g., Documents includes 'application' and 'custom')+ const orConditions = fileTypePrefix.map(+ (prefix) => sql`${files.fileType} ILIKE ${`${prefix}%`}`,+ );+ whereConditions.push(sql`(${sql.join(orConditions, sql` OR `)})`);+ } else {+ whereConditions.push(sql`${files.fileType} ILIKE ${`${fileTypePrefix}%`}`);+ }+ }++ // Knowledge base filter+ if (knowledgeBaseId) {+ // Build where conditions using proper table references (f.column instead of files.column)+ const kbWhereConditions: any[] = [sql`f.user_id = ${this.userId}`];++ // Search filter+ if (q) {+ kbWhereConditions.push(sql`f.name ILIKE ${`%${q}%`}`);+ }++ // Category filter+ if (category && category !== FilesTabs.All && category !== FilesTabs.Home) {+ const fileTypePrefix = this.getFileTypePrefix(category as FilesTabs);+ if (Array.isArray(fileTypePrefix)) {+ const orConditions = fileTypePrefix.map(+ (prefix) => sql`f.file_type ILIKE ${`${prefix}%`}`,+ );+ kbWhereConditions.push(sql`(${sql.join(orConditions, sql` OR `)})`);+ } else {+ kbWhereConditions.push(sql`f.file_type ILIKE ${`${fileTypePrefix}%`}`);+ }+ }++ return sql`+ SELECT+ f.id,+ f.name,+ f.file_type,+ f.size,+ f.url,+ f.created_at,+ f.updated_at,+ f.chunk_task_id,+ f.embedding_task_id,+ NULL as editor_data,+ NULL as content,+ NULL as metadata,+ 'file' as source_type+ FROM ${files} f+ INNER JOIN ${knowledgeBaseFiles} kbf+ ON f.id = kbf.file_id+ AND kbf.knowledge_base_id = ${knowledgeBaseId}+ WHERE ${sql.join(kbWhereConditions, sql` AND `)}+ `;+ }++ // Exclude files in knowledge base if needed+ if (!showFilesInKnowledgeBase) {+ whereConditions.push(+ sql`+ NOT EXISTS (+ SELECT 1 FROM ${knowledgeBaseFiles}+ WHERE ${knowledgeBaseFiles.fileId} = ${files.id}+ )+ `,+ );+ }++ return sql`+ SELECT+ id,+ name,+ file_type,+ size,+ url,+ created_at,+ updated_at,+ chunk_task_id,+ embedding_task_id,+ NULL as editor_data,+ NULL as content,+ NULL as metadata,+ 'file' as source_type+ FROM ${files}+ WHERE ${sql.join(whereConditions, sql` AND `)}+ `;+ }++ private buildDocumentQuery({+ category,+ q,+ knowledgeBaseId,+ }: QueryFileListParams = {}): ReturnType<typeof sql> {+ let whereConditions: any[] = [sql`${documents.userId} = ${this.userId}`];++ // Search filter+ if (q) {+ whereConditions.push(+ sql`(${documents.title} ILIKE ${`%${q}%`} OR ${documents.filename} ILIKE ${`%${q}%`})`,+ );+ }++ // Category filter - match documents by fileType prefix+ if (category && category !== FilesTabs.All && category !== FilesTabs.Home) {+ const fileTypePrefix = this.getFileTypePrefix(category as FilesTabs);+ if (Array.isArray(fileTypePrefix)) {+ // For multiple file types (e.g., Documents includes 'application' and 'custom')+ const orConditions = fileTypePrefix.map(+ (prefix) => sql`${documents.fileType} ILIKE ${`${prefix}%`}`,+ );+ whereConditions.push(sql`(${sql.join(orConditions, sql` OR `)})`);++ // Exclude custom/document and source_type='file' from Documents category+ if (category === FilesTabs.Documents) {+ whereConditions.push(sql`${documents.fileType} != ${'custom/document'}`, sql`${documents.sourceType} != ${'file'}`);+ }+ } else if (fileTypePrefix) {+ whereConditions.push(sql`${documents.fileType} ILIKE ${`${fileTypePrefix}%`}`);+ } else {+ // Exclude documents from other categories (Images, Videos, Audios, Websites)+ return sql`+ SELECT+ NULL::varchar(30) as id,+ NULL::text as name,+ NULL::varchar(255) as file_type,+ NULL::integer as size,+ NULL::text as url,+ NULL::timestamp with time zone as created_at,+ NULL::timestamp with time zone as updated_at,+ NULL::uuid as chunk_task_id,+ NULL::uuid as embedding_task_id,+ NULL::jsonb as editor_data,+ NULL::text as content,+ NULL::jsonb as metadata,+ NULL::text as source_type+ WHERE false+ `;+ }+ }++ // Knowledge base filter for documents+ // Documents don't have knowledge base association currently, so skip if knowledgeBaseId is set+ if (knowledgeBaseId) {+ return sql`+ SELECT+ NULL::varchar(30) as id,+ NULL::text as name,+ NULL::varchar(255) as file_type,+ NULL::integer as size,+ NULL::text as url,+ NULL::timestamp with time zone as created_at,+ NULL::timestamp with time zone as updated_at,+ NULL::uuid as chunk_task_id,+ NULL::uuid as embedding_task_id,+ NULL::jsonb as editor_data,+ NULL::text as content,+ NULL::jsonb as metadata,+ NULL::text as source_type+ WHERE false+ `;+ }++ return sql`+ SELECT+ id,+ COALESCE(title, filename, 'Untitled') as name,+ file_type,+ total_char_count as size,+ source as url,+ created_at,+ updated_at,+ NULL as chunk_task_id,+ NULL as embedding_task_id,+ editor_data,+ content,+ metadata,+ 'document' as source_type+ FROM ${documents}+ WHERE ${sql.join(whereConditions, sql` AND `)}+ `;+ }++ private buildOrderClause(+ sortType?: string,+ sorter?: string,+ ): ReturnType<typeof sql.raw> | ReturnType<typeof sql> {+ const sortableFields: Record<string, string> = {+ createdAt: 'created_at',+ name: 'name',+ size: 'size',+ updatedAt: 'updated_at',+ };++ if (sorter && sortType && sorter in sortableFields) {+ const direction = sortType.toLowerCase() === SortType.Asc ? 'ASC' : 'DESC';+ return sql.raw(`${sortableFields[sorter]} ${direction}`);+ }++ return sql.raw('created_at DESC');+ }++ private getFileTypePrefix(category: FilesTabs): string | string[] {+ switch (category) {+ case FilesTabs.Audios: {+ return 'audio';+ }+ case FilesTabs.Documents: {+ return ['application', 'custom'];+ }+ case FilesTabs.Images: {+ return 'image';+ }+ case FilesTabs.Videos: {+ return 'video';+ }+ case FilesTabs.Websites: {+ return 'text/html';+ }+ default: {+ return '';+ }+ }+ }+}diff --git a/packages/types/src/document/index.ts b/packages/types/src/document/index.tsindex cd9ce4fc4cd..1cbd4a13535 100644--- a/packages/types/src/document/index.ts+++ b/packages/types/src/document/index.ts@@ -11,6 +11,8 @@ export interface LobeDocument {*/createdAt: Date;+ editorData: Record<string, any> | null;+/*** File type or extension*/@@ -54,7 +56,12 @@ export interface LobeDocument {source: string;/**- * Document title (if available)+ * 文档来源类型+ */+ sourceType: DocumentSourceType;++ /**+ * 文档标题 (如果可用)。*/title?: string;@@ -161,7 +168,12 @@ export enum DocumentSourceType {API = 'api',/**- * Local or uploaded files+ * 编辑器创建的文档+ */+ EDITOR = 'editor',++ /**+ * 本地或上传的文件*/FILE = 'file',diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex 99b81f7ee5d..c9b9bd12a88 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -2,7 +2,9 @@ export enum FilesTabs {All = 'all',Audios = 'audios',Documents = 'documents',+ Home = 'home',Images = 'images',+ Pages = 'pages',Videos = 'videos',Websites = 'websites',}diff --git a/packages/types/src/files/list.ts b/packages/types/src/files/list.tsindex caeb3b08eee..6f2fe282fb5 100644--- a/packages/types/src/files/list.ts+++ b/packages/types/src/files/list.ts@@ -6,14 +6,24 @@ export interface FileListItem {chunkCount: number | null;chunkingError: any | null;chunkingStatus?: AsyncTaskStatus | null;+ /**+ * Text content of the document (for notes/documents)+ */+ content?: string | null;createdAt: Date;+ editorData?: Record<string, any> | null;embeddingError: any | null;embeddingStatus?: AsyncTaskStatus | null;fileType: string;finishEmbedding: boolean;id: string;+ /**+ * Metadata (for notes/documents)+ */+ metadata?: Record<string, any> | null;name: string;size: number;+ sourceType: string;updatedAt: Date;url: string;}diff --git a/src/app/[variants]/(main)/knowledge/KnowledgeRouter.tsx b/src/app/[variants]/(main)/knowledge/KnowledgeRouter.tsxindex dc19b8641e9..ca0c0820a52 100644--- a/src/app/[variants]/(main)/knowledge/KnowledgeRouter.tsx+++ b/src/app/[variants]/(main)/knowledge/KnowledgeRouter.tsx@@ -53,8 +53,9 @@ const KnowledgeRouter = memo(() => {<MemoryRouter initialEntries={[getInitialPath()]} initialIndex={0}><UrlSynchronizer /><Routes>- {/* Knowledge home - file list page */}+ {/* Knowledge home */}<Route element={<KnowledgeHomePage />} path="/" />+ <Route element={<KnowledgeHomePage />} path="/:id" />{/* Knowledge bases routes */}<Route element={<KnowledgeBasesListPage />} path="/bases" />diff --git a/src/app/[variants]/(main)/knowledge/components/KnowledgeBaseItem/index.tsx b/src/app/[variants]/(main)/knowledge/components/KnowledgeBaseItem/index.tsxindex 89700033f09..36734a53602 100644--- a/src/app/[variants]/(main)/knowledge/components/KnowledgeBaseItem/index.tsx+++ b/src/app/[variants]/(main)/knowledge/components/KnowledgeBaseItem/index.tsx@@ -17,7 +17,6 @@ const useStyles = createStyles(({ css, token, isDarkMode }) => ({container: css`cursor: pointer;- margin-inline: 8px;padding-block: 4px;padding-inline: 8px;border-radius: ${token.borderRadius}px;diff --git a/src/app/[variants]/(main)/knowledge/hooks/useFileCategory.ts b/src/app/[variants]/(main)/knowledge/hooks/useFileCategory.tsindex 7c9f0a02e80..ea74de6bd49 100644--- a/src/app/[variants]/(main)/knowledge/hooks/useFileCategory.ts+++ b/src/app/[variants]/(main)/knowledge/hooks/useFileCategory.ts@@ -1,4 +1,4 @@-import { useSearchParams } from 'react-router-dom';+import { useParams, useSearchParams } from 'react-router-dom';import { FilesTabs } from '@/types/files';@@ -8,15 +8,18 @@ import { FilesTabs } from '@/types/files';*/export const useFileCategory = (): [string, (value: string) => void] => {const [searchParams, setSearchParams] = useSearchParams();+ const { id } = useParams<{ id: string }>();- const category = searchParams.get('category') ?? FilesTabs.All;+ // If there's an ID in the path, default to Pages instead of Home+ const defaultCategory = id ? FilesTabs.Pages : FilesTabs.Home;+ const category = searchParams.get('category') ?? defaultCategory;const setCategory = (value: string) => {setSearchParams((prev) => {const newParams = new URLSearchParams(prev);- if (value === FilesTabs.All) {+ if (value === FilesTabs.Home) {// Clear on defaultnewParams.delete('category');} else {diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/index.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/index.tsxindex a08d11fce36..3dcf24f7af4 100644--- a/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/index.tsx+++ b/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/index.tsx@@ -6,8 +6,8 @@ import { useParams } from 'react-router-dom';import FileModalQueryRoute from '@/app/[variants]/(main)/knowledge/shared/FileModalQueryRoute';import { useSetFileModalId } from '@/app/[variants]/(main)/knowledge/shared/useFileQueryParam';-import FileManager from '@/features/FileManager';import FilePanel from '@/features/FileSidePanel';+import KnowledgeItemManager from '@/features/KnowledgeManager';import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/knowledgeBase';import { useKnowledgeBaseItem } from '../../hooks/useKnowledgeItem';@@ -35,7 +35,7 @@ const KnowledgeBaseDetailPage = memo(() => {<Menu id={id} /></FilePanel><Flexbox flex={1} style={{ overflow: 'hidden', position: 'relative' }}>- <FileManager knowledgeBaseId={id} onOpenFile={setFileModalId} title={name} />+ <KnowledgeItemManager knowledgeBaseId={id} onOpenFile={setFileModalId} title={name} /></Flexbox><FileModalQueryRoute /></>diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/MenuItems.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/CategoryMenu.tsxsimilarity index 87%rename from src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/MenuItems.tsxrename to src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/CategoryMenu.tsxindex 56f0f05ecab..35be2f3b81c 100644--- a/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/MenuItems.tsx+++ b/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/CategoryMenu.tsx@@ -9,7 +9,7 @@ import { Flexbox } from 'react-layout-kit';import Menu from '@/components/Menu';import type { MenuProps } from '@/components/Menu';-const MenuItems = () => {+const CategoryMenu = () => {const { t } = useTranslation('knowledgeBase');const items: MenuProps['items'] = useMemo(@@ -30,6 +30,6 @@ const MenuItems = () => {);};-MenuItems.displayName = 'MenuItems';+CategoryMenu.displayName = 'MenuItems';-export default MenuItems;+export default CategoryMenu;diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/Menu.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/Menu.tsxindex 6744e06703f..6e7ae99bd39 100644--- a/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/Menu.tsx+++ b/src/app/[variants]/(main)/knowledge/routes/KnowledgeBaseDetail/menu/Menu.tsx@@ -3,14 +3,14 @@import { memo } from 'react';import { Flexbox } from 'react-layout-kit';+import CategoryMenu from './CategoryMenu';import Head from './Head';-import MenuItems from './MenuItems';const Menu = memo<{ id: string }>(({ id }) => {return (<Flexbox gap={16} height={'100%'} paddingInline={12} style={{ paddingTop: 12 }}><Head id={id} />- <MenuItems />+ <CategoryMenu /></Flexbox>);});diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/index.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/index.tsxindex 3335fe8f367..bd6c5a671c2 100644--- a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/index.tsx+++ b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/index.tsx@@ -5,11 +5,13 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { Flexbox } from 'react-layout-kit';import { useMediaQuery } from 'react-responsive';+import { useParams } from 'react-router-dom';import NProgress from '@/components/NProgress';import PanelTitle from '@/components/PanelTitle';-import FileManager from '@/features/FileManager';import FilePanel from '@/features/FileSidePanel';+import KnowledgeItemManager from '@/features/KnowledgeManager';+import TogglePanelButton from '@/features/KnowledgeManager/Header/TogglePanelButton';import { useShowMobileWorkspace } from '@/hooks/useShowMobileWorkspace';import { FilesTabs } from '@/types/files';@@ -18,8 +20,8 @@ import FileModalQueryRoute from '../../shared/FileModalQueryRoute';import { useSetFileModalId } from '../../shared/useFileQueryParam';import Container from './layout/Container';import RegisterHotkeys from './layout/RegisterHotkeys';-import FileMenu from './menu/FileMenu';-import KnowledgeBase from './menu/KnowledgeBase';+import CategoryMenu from './menu/CategoryMenu';+import Collection from './menu/KnowledgeBase';const useStyles = createStyles(({ css, token }) => ({main: css`@@ -27,42 +29,63 @@ const useStyles = createStyles(({ css, token }) => ({overflow: hidden;background: ${token.colorBgLayout};`,+ sidebar: css`+ position: relative;++ &:hover .toggle-button {+ opacity: 1;+ }+ `,+ toggleButton: css`+ position: absolute;+ z-index: 10;+ inset-block-start: 8px;+ inset-inline-end: 8px;++ opacity: 0;++ transition: opacity ${token.motionDurationSlow};+ `,}));-// Menu content component-const MenuContent = memo(() => {+const Sidebar = memo(() => {const { t } = useTranslation('file');+ const { styles } = useStyles();return (- <Flexbox gap={16} height={'100%'}>+ <Flexbox className={styles.sidebar} gap={16} height={'100%'}>+ <div className={`${styles.toggleButton} toggle-button`}>+ <TogglePanelButton />+ </div><Flexbox paddingInline={8}><PanelTitle desc={t('desc')} title={t('title')} />- <FileMenu />+ <CategoryMenu /></Flexbox>- <KnowledgeBase />+ <Collection /></Flexbox>);});-MenuContent.displayName = 'MenuContent';+Sidebar.displayName = 'Sidebar';// Main files list component-const FilesListPage = memo(() => {+const MainContent = memo(() => {+ const { id } = useParams<{ id: string }>();const [category] = useFileCategory();const setFileModalId = useSetFileModalId();return (- <FileManager+ <KnowledgeItemManagercategory={category}+ documentId={id}onOpenFile={setFileModalId}title={`${category as FilesTabs}`}/>);});-FilesListPage.displayName = 'FilesListPage';+MainContent.displayName = 'FilesListPage';-// Desktop layoutconst DesktopLayout = memo(() => {return (<>@@ -74,10 +97,10 @@ const DesktopLayout = memo(() => {width={'100%'}><FilePanel>- <MenuContent />+ <Sidebar /></FilePanel><Container>- <FilesListPage />+ <MainContent /></Container></Flexbox><RegisterHotkeys />@@ -88,7 +111,6 @@ const DesktopLayout = memo(() => {DesktopLayout.displayName = 'DesktopLayout';-// Mobile layoutconst MobileLayout = memo(() => {const showMobileWorkspace = useShowMobileWorkspace();const { styles } = useStyles();@@ -102,7 +124,7 @@ const MobileLayout = memo(() => {style={showMobileWorkspace ? { display: 'none' } : undefined}width="100%">- <MenuContent />+ <Sidebar /></Flexbox><FlexboxclassName={styles.main}@@ -110,7 +132,7 @@ const MobileLayout = memo(() => {style={showMobileWorkspace ? undefined : { display: 'none' }}width="100%">- <FilesListPage />+ <MainContent /></Flexbox><FileModalQueryRoute /></>diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/layout/Container.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/layout/Container.tsxindex 8d4dad10c1e..c7e997df14e 100644--- a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/layout/Container.tsx+++ b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/layout/Container.tsx@@ -12,7 +12,7 @@ const Container = memo<PropsWithChildren>(({ children }) => {flex={1}style={{background: theme.colorBgContainerSecondary,- overflow: 'hidden',+ overflowY: 'auto',position: 'relative',}}>diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/CategoryMenu.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/CategoryMenu.tsxnew file mode 100644index 00000000000..7cdf18c8c0c--- /dev/null+++ b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/CategoryMenu.tsx@@ -0,0 +1,148 @@+'use client';++import { CaretDownFilled } from '@ant-design/icons';+import { ActionIcon, Icon } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { motion } from 'framer-motion';+import { FilePenIcon, FileText, FolderOpen, ImageIcon, Mic2, SquarePlay } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';+import { useNavigate } from 'react-router-dom';++import Menu from '@/components/Menu';+import type { MenuProps } from '@/components/Menu';+import { FilesTabs } from '@/types/files';++import { useFileCategory } from '../../../hooks/useFileCategory';++const useStyles = createStyles(({ css, token }) => ({+ header: css`+ cursor: pointer;+ border-radius: ${token.borderRadius}px;+ color: ${token.colorTextSecondary};+ transition: background-color 0.2s;++ &:hover {+ background-color: ${token.colorFillTertiary};+ }+ `,+ headerActive: css`+ color: ${token.colorText};+ background-color: ${token.colorFillSecondary};+ `,+ indentedMenu: css`+ padding-inline-start: 24px;+ `,+}));++const CategoryMenu = memo(() => {+ const { t } = useTranslation('file');+ const { styles, cx } = useStyles();+ const [activeKey] = useFileCategory();+ const [showCollapsed, setShowCollapsed] = useState(activeKey !== FilesTabs.Home);+ const navigate = useNavigate();++ const collapsedItems: MenuProps['items'] = useMemo(+ () => [+ {+ icon: <Icon icon={FolderOpen} />,+ key: FilesTabs.All,+ label: t('tab.all'),+ },+ {+ icon: <Icon icon={FileText} />,+ key: FilesTabs.Documents,+ label: t('tab.documents'),+ },+ {+ icon: <Icon icon={FilePenIcon} />,+ key: FilesTabs.Pages,+ label: t('tab.pages'),+ },+ {+ icon: <Icon icon={ImageIcon} />,+ key: FilesTabs.Images,+ label: t('tab.images'),+ },+ {+ icon: <Icon icon={Mic2} />,+ key: FilesTabs.Audios,+ label: t('tab.audios'),+ },+ {+ icon: <Icon icon={SquarePlay} />,+ key: FilesTabs.Videos,+ label: t('tab.videos'),+ },+ // {+ // icon: <Icon icon={Globe} />,+ // key: FilesTabs.Websites,+ // label: t('tab.websites'),+ // },+ ],+ [t],+ );++ const isHomeActive = activeKey === FilesTabs.Home;++ return (+ <Flexbox gap={4}>+ <Flexbox+ align={'center'}+ className={cx(styles.header, isHomeActive && styles.headerActive)}+ horizontal+ onClick={() => {+ navigate('/', { replace: true });+ }}+ paddingBlock={6}+ paddingInline={8}+ >+ <Flexbox align={'center'} flex={1} gap={8} horizontal>+ <motion.div+ animate={{ rotate: showCollapsed ? 0 : -90 }}+ transition={{ duration: 0.2, ease: 'easeInOut' }}+ >+ <ActionIcon+ icon={CaretDownFilled as any}+ onClick={(e) => {+ e.stopPropagation();+ setShowCollapsed(!showCollapsed);+ }}+ size={'small'}+ />+ </motion.div>+ <div style={{ flex: 1, lineHeight: '14px' }}>{t('tab.home')}</div>+ </Flexbox>+ </Flexbox>++ <motion.div+ animate={{+ height: showCollapsed ? 'auto' : 0,+ opacity: showCollapsed ? 1 : 0,+ }}+ initial={false}+ style={{ overflow: 'hidden' }}+ transition={{ duration: 0.2, ease: 'easeInOut' }}+ >+ <Flexbox>+ <Menu+ compact+ items={collapsedItems}+ onClick={({ key }) => {+ // Navigate to home route and set category+ const categoryParam = key === FilesTabs.Home ? '' : `?category=${key}`;+ navigate(`/${categoryParam}`, { replace: true });+ }}+ selectable+ selectedKeys={[activeKey]}+ />+ </Flexbox>+ </motion.div>+ </Flexbox>+ );+});++CategoryMenu.displayName = 'CategoryMenu';++export default CategoryMenu;diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/FileMenu.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/FileMenu.tsxdeleted file mode 100644index 66c3d94386c..00000000000--- a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/FileMenu.tsx+++ /dev/null@@ -1,75 +0,0 @@-'use client';--import { Icon } from '@lobehub/ui';-import { FileText, Globe, ImageIcon, LayoutGrid, Mic2, SquarePlay } from 'lucide-react';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';-import { Flexbox } from 'react-layout-kit';--import Menu from '@/components/Menu';-import type { MenuProps } from '@/components/Menu';-import { FilesTabs } from '@/types/files';--import { useFileCategory } from '../../../hooks/useFileCategory';--const FileMenu = memo(() => {- const { t } = useTranslation('file');- const [activeKey, setActiveKey] = useFileCategory();-- const items: MenuProps['items'] = useMemo(- () =>- [- {- icon: <Icon icon={LayoutGrid} />,- key: FilesTabs.All,- label: t('tab.all'),- },- {- icon: <Icon icon={FileText} />,- key: FilesTabs.Documents,- label: t('tab.documents'),- },- {- icon: <Icon icon={ImageIcon} />,- key: FilesTabs.Images,- label: t('tab.images'),- },- {- icon: <Icon icon={Mic2} />,- key: FilesTabs.Audios,- label: t('tab.audios'),- },- {- icon: <Icon icon={SquarePlay} />,- key: FilesTabs.Videos,- label: t('tab.videos'),- },- {- icon: <Icon icon={Globe} />,- key: FilesTabs.Websites,- label: t('tab.websites'),- },- ]- .filter(Boolean)- .slice(0, 5) as MenuProps['items'],- [t],- );-- return (- <Flexbox>- <Menu- compact- items={items}- onClick={({ key }) => {- setActiveKey(key);- }}- selectable- selectedKeys={[activeKey]}- />- </Flexbox>- );-});--FileMenu.displayName = 'FileMenu';--export default FileMenu;diff --git a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/KnowledgeBase.tsx b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/KnowledgeBase.tsxindex d251b724208..81117168a10 100644--- a/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/KnowledgeBase.tsx+++ b/src/app/[variants]/(main)/knowledge/routes/KnowledgeHome/menu/KnowledgeBase.tsx@@ -13,11 +13,19 @@ import KnowledgeBaseList from '../../../components/KnowledgeBaseList';const useStyles = createStyles(({ css, token }) => ({header: css`- color: ${token.colorTextDescription};+ cursor: pointer;+ border-radius: ${token.borderRadius}px;+ color: ${token.colorTextSecondary};+ transition: background-color 0.2s;++ &:hover {+ background-color: ${token.colorFillTertiary};+ }`,}));-const KnowledgeBase = () => {+// TODO: Rename to Collection+const Collection = () => {const { t } = useTranslation('file');const { styles } = useStyles();const navigate = useNavigate();@@ -35,13 +43,14 @@ const KnowledgeBase = () => {};return (- <Flexbox flex={1} gap={8}>+ <Flexbox flex={1} gap={8} paddingInline={8}><Flexboxalign={'center'}className={styles.header}horizontaljustify={'space-between'}- paddingInline={'16px 12px'}+ paddingBlock={6}+ paddingInline={8}><Flexbox align={'center'} gap={8} horizontal><ActionIcon@@ -51,7 +60,7 @@ const KnowledgeBase = () => {}}size={'small'}/>- <div style={{ lineHeight: '14px' }}>{t('knowledgeBase.title')}</div>+ <div style={{ flex: 1, lineHeight: '14px' }}>{t('knowledgeBase.title')}</div></Flexbox><ActionIconicon={PlusIcon}@@ -61,9 +70,13 @@ const KnowledgeBase = () => {/></Flexbox>- {showList && <KnowledgeBaseList />}+ {showList && (+ <Flexbox flex={1}>+ <KnowledgeBaseList />+ </Flexbox>+ )}</Flexbox>);};-export default KnowledgeBase;+export default Collection;diff --git a/src/components/FileIcon/index.tsx b/src/components/FileIcon/index.tsxindex 19fa43e85ba..5afe49c9807 100644--- a/src/components/FileIcon/index.tsx+++ b/src/components/FileIcon/index.tsx@@ -11,7 +11,7 @@ interface FileListProps {variant?: 'raw' | 'file' | 'folder';}-const FileIcon = memo<FileListProps>(({ fileName, size, variant = 'file', isDirectory }) => {+const FileIcon = memo<FileListProps>(({ fileName, size, variant = 'raw', isDirectory }) => {if (isDirectory)return <FileTypeIcon color={'gold'} size={size} type={'folder'} variant={'color'} />;@@ -28,6 +28,8 @@ const FileIcon = memo<FileListProps>(({ fileName, size, variant = 'file', isDire);}+ console.log('FileIcon', fileName);+return <MaterialFileTypeIcon filename={fileName} size={size} type={'file'} variant={variant} />;});diff --git a/src/features/ChatInput/ActionBar/Knowledge/index.tsx b/src/features/ChatInput/ActionBar/Knowledge/index.tsxindex e44a0aa418e..c42ae42e21e 100644--- a/src/features/ChatInput/ActionBar/Knowledge/index.tsx+++ b/src/features/ChatInput/ActionBar/Knowledge/index.tsx@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next';import TipGuide from '@/components/TipGuide';import { LOBE_CHAT_CLOUD } from '@/const/branding';import { isServerMode } from '@/const/version';-import { AssignKnowledgeBaseModal } from '@/features/KnowledgeBaseModal';+import { AttachKnowledgeModal } from '@/features/KnowledgeBaseModal';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';import { preferenceSelectors } from '@/store/user/selectors';@@ -69,7 +69,7 @@ const Knowledge = memo(() => {) : (content)}- <AssignKnowledgeBaseModal open={modalOpen} setOpen={setModalOpen} />+ <AttachKnowledgeModal open={modalOpen} setOpen={setModalOpen} /></Suspense>);});diff --git a/src/features/FileManager/FileList/MasonryFileItem/index.tsx b/src/features/FileManager/FileList/MasonryFileItem/index.tsxdeleted file mode 100644index 34912fcbd59..00000000000--- a/src/features/FileManager/FileList/MasonryFileItem/index.tsx+++ /dev/null@@ -1,582 +0,0 @@-import { Button, Tooltip } from '@lobehub/ui';-import { Checkbox, Image } from 'antd';-import { createStyles } from 'antd-style';-import { isNull } from 'lodash-es';-import { FileBoxIcon } from 'lucide-react';-import { memo, useEffect, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { Flexbox } from 'react-layout-kit';--import FileIcon from '@/components/FileIcon';-import { fileManagerSelectors, useFileStore } from '@/store/file';-import { FileListItem } from '@/types/files';-import { formatSize } from '@/utils/format';-import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';--import ChunksBadge from '../FileListItem/ChunkTag';-import DropdownMenu from '../FileListItem/DropdownMenu';--// Image file types-const IMAGE_TYPES = new Set([- 'image/png',- 'image/jpeg',- 'image/jpg',- 'image/gif',- 'image/webp',- 'image/svg+xml',-]);--// Markdown file types-const MARKDOWN_TYPES = new Set(['text/markdown', 'text/x-markdown']);--// Helper to check if filename ends with .md-const isMarkdownFile = (name: string, fileType?: string) => {- return (- name.toLowerCase().endsWith('.md') ||- name.toLowerCase().endsWith('.markdown') ||- (fileType && MARKDOWN_TYPES.has(fileType))- );-};--const useStyles = createStyles(({ css, token }) => ({- actions: css`- opacity: 0;- transition: opacity ${token.motionDurationMid};- `,- card: css`- cursor: pointer;-- position: relative;-- overflow: visible;-- border: 1px solid ${token.colorBorderSecondary};- border-radius: ${token.borderRadiusLG}px;-- background: ${token.colorBgContainer};-- transition: all ${token.motionDurationMid};-- &:hover {- border-color: ${token.colorPrimary};- box-shadow: ${token.boxShadowTertiary};-- .actions {- opacity: 1;- }-- .checkbox {- opacity: 1;- }-- .dropdown {- opacity: 1;- }-- .floatingChunkBadge {- opacity: 1;- }- }- `,- checkbox: css`- position: absolute;- z-index: 2;- inset-block-start: 8px;- inset-inline-start: 8px;-- opacity: 0;-- transition: opacity ${token.motionDurationMid};- `,- content: css`- position: relative;- `,- contentWithPadding: css`- padding: 12px;- `,- dropdown: css`- position: absolute;- z-index: 2;- inset-block-start: 8px;- inset-inline-end: 8px;-- opacity: 0;-- transition: opacity ${token.motionDurationMid};- `,- floatingChunkBadge: css`- position: absolute;- z-index: 3;- inset-block-end: 8px;- inset-inline-end: 8px;-- border-radius: ${token.borderRadius}px;-- opacity: 0;- background: ${token.colorBgContainer};- box-shadow: ${token.boxShadow};-- transition: opacity ${token.motionDurationMid};- `,- hoverOverlay: css`- position: absolute;- z-index: 1;- inset: 0;-- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;-- padding: 16px;- border-radius: ${token.borderRadiusLG}px;-- opacity: 0;- background: ${token.colorBgMask};-- transition: opacity ${token.motionDurationMid};-- &:hover {- opacity: 1;- }- `,- iconWrapper: css`- display: flex;- align-items: center;- justify-content: center;-- height: 120px;- margin-block-end: 12px;- border-radius: ${token.borderRadius}px;-- background: ${token.colorFillQuaternary};- `,- imagePlaceholder: css`- display: flex;- align-items: center;- justify-content: center;-- min-height: 120px;-- background: ${token.colorFillQuaternary};- `,- imageWrapper: css`- position: relative;-- overflow: hidden;-- width: 100%;- border-radius: ${token.borderRadiusLG}px;-- background: ${token.colorFillQuaternary};-- img {- display: block;- width: 100%;- height: auto;- }- `,- markdownLoading: css`- display: flex;- align-items: center;- justify-content: center;-- min-height: 120px;- border-radius: ${token.borderRadiusLG}px;-- font-size: 12px;- color: ${token.colorTextTertiary};-- background: ${token.colorFillQuaternary};- `,- markdownPreview: css`- position: relative;-- overflow: hidden;-- width: 100%;- min-height: 120px;- max-height: 300px;- padding: 16px;- border-radius: ${token.borderRadiusLG}px;-- font-size: 13px;- line-height: 1.6;- color: ${token.colorTextSecondary};- word-wrap: break-word;- white-space: pre-wrap;-- background: ${token.colorFillQuaternary};-- &::after {- pointer-events: none;- content: '';-- position: absolute;- inset-block-end: 0;- inset-inline: 0;-- height: 60px;-- background: linear-gradient(to bottom, transparent, ${token.colorFillQuaternary});- }- `,- name: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 2;-- margin-block-end: 12px;-- font-weight: ${token.fontWeightStrong};- color: ${token.colorText};- word-break: break-word;- `,- overlaySize: css`- font-size: 12px;- color: ${token.colorTextLightSolid};- opacity: 0.9;- `,- overlayTitle: css`- overflow: hidden;- display: -webkit-box;- -webkit-box-orient: vertical;- -webkit-line-clamp: 3;-- max-width: 100%;- margin-block-end: 8px;-- font-size: 14px;- font-weight: ${token.fontWeightStrong};- color: ${token.colorTextLightSolid};- text-align: center;- word-break: break-word;- `,- selected: css`- border-color: ${token.colorPrimary};- background: ${token.colorPrimaryBg};-- .checkbox {- opacity: 1;- }- `,-}));--interface MasonryFileItemProps extends FileListItem {- knowledgeBaseId?: string;- onOpen: (id: string) => void;- onSelectedChange: (id: string, selected: boolean) => void;- selected?: boolean;-}--const MasonryFileItem = memo<MasonryFileItemProps>(- ({- chunkingError,- embeddingError,- embeddingStatus,- finishEmbedding,- chunkCount,- url,- name,- fileType,- id,- selected,- chunkingStatus,- onSelectedChange,- knowledgeBaseId,- size,- onOpen,- }) => {- const { t } = useTranslation('components');- const { styles, cx } = useStyles();- const [imageLoaded, setImageLoaded] = useState(false);- const [markdownContent, setMarkdownContent] = useState<string>('');- const [isLoadingMarkdown, setIsLoadingMarkdown] = useState(false);- const [isCreatingFileParseTask, parseFiles] = useFileStore((s) => [- fileManagerSelectors.isCreatingFileParseTask(id)(s),- s.parseFilesToChunks,- ]);-- const isSupportedForChunking = !isChunkingUnsupported(fileType);- const isImage = fileType && IMAGE_TYPES.has(fileType);- const isMarkdown = isMarkdownFile(name, fileType);-- const cardRef = useRef<HTMLDivElement>(null);- const [isInView, setIsInView] = useState(false);-- // Use Intersection Observer to detect when card enters viewport- useEffect(() => {- if (!cardRef.current) return;-- const observer = new IntersectionObserver(- (entries) => {- entries.forEach((entry) => {- if (entry.isIntersecting && !isInView) {- setIsInView(true);- }- });- },- {- rootMargin: '200px', // Increased margin to load content earlier- threshold: 0.01, // Lower threshold for earlier triggering- },- );-- observer.observe(cardRef.current);-- return () => {- observer.disconnect();- };- }, [isInView]);-- // Fetch markdown content only when in viewport- useEffect(() => {- if (isMarkdown && url && isInView && !markdownContent) {- setIsLoadingMarkdown(true);- fetch(url)- .then((res) => res.text())- .then((text) => {- // Take first 500 characters for preview- const preview = text.slice(0, 500);- setMarkdownContent(preview);- })- .catch((error) => {- console.error('Failed to fetch markdown content:', error);- setMarkdownContent('');- })- .finally(() => {- setIsLoadingMarkdown(false);- });- }- }, [isMarkdown, url, isInView, markdownContent]);-- return (- <div className={cx(styles.card, selected && styles.selected)} ref={cardRef}>- <div- className={cx('checkbox', styles.checkbox)}- onClick={(e) => {- e.stopPropagation();- onSelectedChange(id, !selected);- }}- >- <Checkbox checked={selected} />- </div>-- <div className={cx('dropdown', styles.dropdown)} onClick={(e) => e.stopPropagation()}>- <DropdownMenu filename={name} id={id} knowledgeBaseId={knowledgeBaseId} url={url} />- </div>-- <div- className={cx(styles.content, !isImage && !isMarkdown && styles.contentWithPadding)}- onClick={() => {- onOpen(id);- }}- >- {isImage && url ? (- <>- <div className={styles.imageWrapper}>- {!imageLoaded && (- <div className={styles.imagePlaceholder}>- <FileIcon fileName={name} fileType={fileType} size={64} />- </div>- )}- {isInView && (- <Image- alt={name}- loading="lazy"- onError={() => setImageLoaded(false)}- onLoad={() => setImageLoaded(true)}- preview={{- src: url,- }}- src={url}- style={{- display: 'block',- height: 'auto',- opacity: imageLoaded ? 1 : 0,- transition: 'opacity 0.3s',- width: '100%',- }}- wrapperStyle={{- display: 'block',- width: '100%',- }}- />- )}- {/* Hover overlay */}- <div className={styles.hoverOverlay}>- <div className={styles.overlayTitle}>{name}</div>- <div className={styles.overlaySize}>{formatSize(size)}</div>- </div>- </div>- {/* Floating chunk badge or action button */}- {!isNull(chunkingStatus) && chunkingStatus ? (- <div- className={cx('floatingChunkBadge', styles.floatingChunkBadge)}- onClick={(e) => e.stopPropagation()}- >- <ChunksBadge- chunkCount={chunkCount}- chunkingError={chunkingError}- chunkingStatus={chunkingStatus}- embeddingError={embeddingError}- embeddingStatus={embeddingStatus}- finishEmbedding={finishEmbedding}- id={id}- />- </div>- ) : (- isSupportedForChunking && (- <Tooltip title={t('FileManager.actions.chunkingTooltip')}>- <div- className={cx('floatingChunkBadge', styles.floatingChunkBadge)}- onClick={(e) => {- e.stopPropagation();- if (!isCreatingFileParseTask) {- parseFiles([id]);- }- }}- style={{ cursor: 'pointer' }}- >- <Button- icon={FileBoxIcon}- loading={isCreatingFileParseTask}- size={'small'}- type={'text'}- />- </div>- </Tooltip>- )- )}- </>- ) : isMarkdown ? (- <>- <div style={{ position: 'relative' }}>- {isLoadingMarkdown ? (- <div className={styles.markdownLoading}>Loading preview...</div>- ) : markdownContent ? (- <div className={styles.markdownPreview}>{markdownContent}</div>- ) : (- <div className={styles.iconWrapper}>- <FileIcon fileName={name} fileType={fileType} size={64} />- </div>- )}- {/* Hover overlay */}- <div className={styles.hoverOverlay}>- <div className={styles.overlayTitle}>{name}</div>- <div className={styles.overlaySize}>{formatSize(size)}</div>- </div>- </div>- {/* Floating chunk badge or action button */}- {!isNull(chunkingStatus) && chunkingStatus ? (- <div- className={cx('floatingChunkBadge', styles.floatingChunkBadge)}- onClick={(e) => e.stopPropagation()}- >- <ChunksBadge- chunkCount={chunkCount}- chunkingError={chunkingError}- chunkingStatus={chunkingStatus}- embeddingError={embeddingError}- embeddingStatus={embeddingStatus}- finishEmbedding={finishEmbedding}- id={id}- />- </div>- ) : (- isSupportedForChunking && (- <Tooltip title={t('FileManager.actions.chunkingTooltip')}>- <div- className={cx('floatingChunkBadge', styles.floatingChunkBadge)}- onClick={(e) => {- e.stopPropagation();- if (!isCreatingFileParseTask) {- parseFiles([id]);- }- }}- style={{ cursor: 'pointer' }}- >- <Button- icon={FileBoxIcon}- loading={isCreatingFileParseTask}- size={'small'}- type={'text'}- />- </div>- </Tooltip>- )- )}- </>- ) : (- <>- <Flexbox- align={'center'}- gap={12}- justify={'center'}- paddingBlock={24}- paddingInline={12}- style={{ minHeight: 180 }}- >- <FileIcon fileName={name} fileType={fileType} size={64} />- <div className={styles.name} style={{ textAlign: 'center' }}>- {name}- </div>- <div- style={{- color: 'var(--lobe-chat-text-tertiary)',- fontSize: 12,- textAlign: 'center',- }}- >- {formatSize(size)}- </div>- </Flexbox>- {/* Floating chunk badge or action button */}- {!isNull(chunkingStatus) && chunkingStatus ? (- <div- className={cx('floatingChunkBadge', styles.floatingChunkBadge)}- onClick={(e) => e.stopPropagation()}- >- <ChunksBadge- chunkCount={chunkCount}- chunkingError={chunkingError}- chunkingStatus={chunkingStatus}- embeddingError={embeddingError}- embeddingStatus={embeddingStatus}- finishEmbedding={finishEmbedding}- id={id}- />- </div>- ) : (- isSupportedForChunking && (- <Tooltip title={t('FileManager.actions.chunkingTooltip')}>- <div- className={cx('floatingChunkBadge', styles.floatingChunkBadge)}- onClick={(e) => {- e.stopPropagation();- if (!isCreatingFileParseTask) {- parseFiles([id]);- }- }}- style={{ cursor: 'pointer' }}- >- <Button- icon={FileBoxIcon}- loading={isCreatingFileParseTask}- size={'small'}- type={'text'}- />- </div>- </Tooltip>- )- )}- </>- )}- </div>- </div>- );- },-);--export default MasonryFileItem;diff --git a/src/features/FileManager/index.tsx b/src/features/FileManager/index.tsxdeleted file mode 100644index 973d37a9b0e..00000000000--- a/src/features/FileManager/index.tsx+++ /dev/null@@ -1,36 +0,0 @@-'use client';--import { Text } from '@lobehub/ui';-import dynamic from 'next/dynamic';-import { memo } from 'react';-import { Flexbox } from 'react-layout-kit';--import FileList from './FileList';-import Header from './Header';-import UploadDock from './UploadDock';--const ChunkDrawer = dynamic(() => import('./ChunkDrawer'), { ssr: false });--interface FileManagerProps {- category?: string;- knowledgeBaseId?: string;- onOpenFile: (id: string) => void;- title: string;-}-const FileManager = memo<FileManagerProps>(({ title, knowledgeBaseId, category, onOpenFile }) => {- return (- <>- <Header knowledgeBaseId={knowledgeBaseId} />- <Flexbox gap={12} height={'100%'}>- <Text strong style={{ fontSize: 16, marginBlock: 16, marginInline: 24 }}>- {title}- </Text>- <FileList category={category} knowledgeBaseId={knowledgeBaseId} onOpenFile={onOpenFile} />- </Flexbox>- <UploadDock />- <ChunkDrawer />- </>- );-});--export default FileManager;diff --git a/src/features/FileSidePanel/index.tsx b/src/features/FileSidePanel/index.tsxindex c7c36acfe24..712493a0774 100644--- a/src/features/FileSidePanel/index.tsx+++ b/src/features/FileSidePanel/index.tsx@@ -55,7 +55,7 @@ const FileSidePanel = memo<PropsWithChildren>(({ children }) => {className={styles.panel}defaultSize={{ width: tmpWidth }}expand={showFilePanel}- maxWidth={320}+ maxWidth={280}minWidth={FOLDER_WIDTH}mode={md ? 'fixed' : 'float'}onExpandChange={handleExpand}diff --git a/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/MasonryItem.tsx b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/MasonryItem.tsxnew file mode 100644index 00000000000..7f2b4f895fd--- /dev/null+++ b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/MasonryItem.tsx@@ -0,0 +1,80 @@+import { Text } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import KnowledgeIcon from '@/components/KnowledgeIcon';+import { KnowledgeItem } from '@/types/knowledgeBase';++import Actions from './Action';++const useStyles = createStyles(({ css, token }) => ({+ card: css`+ cursor: pointer;++ position: relative;++ overflow: hidden;++ padding: 12px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;++ background: ${token.colorBgContainer};++ transition: all ${token.motionDurationMid};++ &:hover {+ border-color: ${token.colorPrimary};+ box-shadow: ${token.boxShadowTertiary};+ }+ `,+ desc: css`+ margin: 0 !important;+ font-size: 12px;+ line-height: 1.4;+ color: ${token.colorTextDescription};+ `,+ title: css`+ margin: 0 !important;+ font-size: 14px;+ font-weight: 500;+ line-height: 1.4;+ `,+}));++const MasonryItem = memo<KnowledgeItem>(({ id, fileType, name, type, description, enabled }) => {+ const { styles } = useStyles();++ return (+ <div className={styles.card}>+ <Flexbox gap={12} style={{ position: 'relative' }}>+ <Flexbox align={'center'} gap={12} horizontal>+ <KnowledgeIcon+ fileType={fileType}+ name={name}+ size={{ file: 48, repo: 48 }}+ type={type}+ />+ <Flexbox flex={1} gap={6} style={{ overflow: 'hidden', position: 'relative' }}>+ <Text className={styles.title} ellipsis={{ rows: 2 }}>+ {name}+ </Text>+ </Flexbox>+ </Flexbox>+ {description && (+ <Text className={styles.desc} ellipsis={{ rows: 3 }}>+ {description}+ </Text>+ )}+ <Flexbox align={'center'} justify={'flex-end'}>+ <Actions enabled={enabled} id={id} type={type} />+ </Flexbox>+ </Flexbox>+ </div>+ );+});++MasonryItem.displayName = 'MasonryItem';++export default MasonryItem;diff --git a/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/MasonryItemWrapper.tsx b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/MasonryItemWrapper.tsxnew file mode 100644index 00000000000..8501d067aae--- /dev/null+++ b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/Item/MasonryItemWrapper.tsx@@ -0,0 +1,27 @@+import { memo } from 'react';++import { KnowledgeItem } from '@/types/knowledgeBase';++import MasonryItem from './MasonryItem';++interface MasonryItemWrapperProps {+ data: KnowledgeItem;+ index: number;+}++const MasonryItemWrapper = memo<MasonryItemWrapperProps>(({ data: item }) => {+ // Safety check: return null if item is undefined+ if (!item || !item.id) {+ return null;+ }++ return (+ <div style={{ padding: '8px 4px' }}>+ <MasonryItem {...item} />+ </div>+ );+});++MasonryItemWrapper.displayName = 'MasonryItemWrapper';++export default MasonryItemWrapper;diff --git a/src/features/KnowledgeBaseModal/AssignKnowledgeBase/List.tsx b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/List.tsxindex 698ada4b684..739aa38a683 100644--- a/src/features/KnowledgeBaseModal/AssignKnowledgeBase/List.tsx+++ b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/List.tsx@@ -1,15 +1,20 @@import { Icon } from '@lobehub/ui';+import { VirtuosoMasonry } from '@virtuoso.dev/masonry';import { Empty } from 'antd';import { ServerCrash } from 'lucide-react';-import { memo } from 'react';+import React, { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { Center } from 'react-layout-kit';+import { Center, Flexbox } from 'react-layout-kit';import { Virtuoso } from 'react-virtuoso';import { useAgentStore } from '@/store/agent';+import { useGlobalStore } from '@/store/global';import Item from './Item';+import MasonryItemWrapper from './Item/MasonryItemWrapper';import Loading from './Loading';+import MasonrySkeleton from './MasonrySkeleton';+import ViewSwitcher, { ViewMode } from './ViewSwitcher';export const List = memo(() => {const { t } = useTranslation('file');@@ -18,31 +23,107 @@ export const List = memo(() => {const { isLoading, error, data } = useFetchFilesAndKnowledgeBases();+ const [columnCount, setColumnCount] = useState(2);+ const [isTransitioning, setIsTransitioning] = useState(false);++ const viewMode = useGlobalStore((s) => s.status.knowledgeBaseModalViewMode || 'list') as ViewMode;+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);+ const setViewMode = (mode: ViewMode) => {+ setIsTransitioning(true);+ updateSystemStatus({ knowledgeBaseModalViewMode: mode });+ };++ // Update column count based on window size (max 2 columns for modal)+ const updateColumnCount = React.useCallback(() => {+ const width = window.innerWidth;+ if (width < 480) {+ setColumnCount(1);+ } else {+ setColumnCount(2);+ }+ }, []);++ // Initialize column count on mount+ React.useEffect(() => {+ updateColumnCount();+ }, [updateColumnCount]);++ // Set up resize listener when in masonry mode+ React.useEffect(() => {+ if (viewMode === 'masonry') {+ window.addEventListener('resize', updateColumnCount);+ return () => window.removeEventListener('resize', updateColumnCount);+ }+ }, [viewMode, updateColumnCount]);++ // Handle view transition with a brief delay to show skeleton+ React.useEffect(() => {+ if (isTransitioning && data) {+ requestAnimationFrame(() => {+ const timer = setTimeout(() => {+ setIsTransitioning(false);+ }, 100);+ return () => clearTimeout(timer);+ });+ }+ }, [isTransitioning, viewMode, data]);+const isEmpty = data && data.length === 0;- return isLoading ? (- <Loading />- ) : isEmpty ? (- <Center gap={12} padding={40}>- {error ? (- <>- <Icon icon={ServerCrash} size={80} />- {t('networkError')}- </>+ const masonryContext = useMemo(() => ({}), []);++ return (+ <Flexbox height={500}>+ <Flexbox paddingInline={16} style={{ paddingBlockEnd: 12 }}>+ <Flexbox align={'center'} horizontal justify={'flex-end'}>+ <ViewSwitcher onViewChange={setViewMode} view={viewMode} />+ </Flexbox>+ </Flexbox>+ {isLoading || isTransitioning ? (+ viewMode === 'masonry' ? (+ <MasonrySkeleton columnCount={columnCount} />+ ) : (+ <Loading />+ )+ ) : isEmpty ? (+ <Center gap={12} padding={40}>+ {error ? (+ <>+ <Icon icon={ServerCrash} size={80} />+ {t('networkError')}+ </>+ ) : (+ <Empty description={t('empty')} image={Empty.PRESENTED_IMAGE_SIMPLE} />+ )}+ </Center>+ ) : viewMode === 'list' ? (+ <Virtuoso+ itemContent={(index) => {+ const item = data![index];+ return <Item key={item.id} {...item} />;+ }}+ overscan={400}+ style={{ flex: 1, marginInline: -16 }}+ totalCount={data!.length}+ />) : (- <Empty description={t('empty')} image={Empty.PRESENTED_IMAGE_SIMPLE} />+ <div style={{ flex: 1, overflow: 'hidden' }}>+ <div style={{ height: '100%', overflowY: 'auto' }}>+ <div style={{ paddingInline: 16 }}>+ <VirtuosoMasonry+ ItemContent={MasonryItemWrapper}+ columnCount={columnCount}+ context={masonryContext}+ data={data || []}+ style={{+ gap: '16px',+ }}+ />+ </div>+ </div>+ </div>)}- </Center>- ) : (- <Virtuoso- itemContent={(index) => {- const item = data![index];- return <Item key={item.id} {...item} />;- }}- overscan={400}- style={{ height: 500, marginInline: -16 }}- totalCount={data!.length}- />+ </Flexbox>);});diff --git a/src/features/KnowledgeBaseModal/AssignKnowledgeBase/MasonrySkeleton.tsx b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/MasonrySkeleton.tsxnew file mode 100644index 00000000000..a8f3596546d--- /dev/null+++ b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/MasonrySkeleton.tsx@@ -0,0 +1,62 @@+import { Skeleton } from 'antd';+import { createStyles } from 'antd-style';+import { memo } from 'react';++const useStyles = createStyles(({ css, token }) => ({+ card: css`+ padding: 12px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;+ background: ${token.colorBgContainer};+ `,+ grid: css`+ display: grid;+ gap: 16px;+ padding-block: 12px;+ `,+}));++interface MasonrySkeletonProps {+ columnCount: number;+}++const MasonrySkeleton = memo<MasonrySkeletonProps>(({ columnCount }) => {+ const { styles } = useStyles();+ // Generate varying heights for more natural masonry look+ const heights = [160, 180, 170, 160, 190, 170, 160, 180];++ // Calculate number of items based on column count (max 2 columns for modal)+ const itemCount = Math.min(columnCount * 3, 8);++ return (+ <div+ className={styles.grid}+ style={{+ gridTemplateColumns: `repeat(${columnCount}, 1fr)`,+ }}+ >+ {Array.from({ length: itemCount }).map((_, index) => (+ <div className={styles.card} key={index}>+ <Skeleton+ active+ avatar={{ shape: 'square', size: 48 }}+ paragraph={{+ rows: 3,+ width: ['100%', '90%', '70%'],+ }}+ style={{+ height: heights[index % heights.length],+ }}+ title={{+ width: '80%',+ }}+ />+ </div>+ ))}+ </div>+ );+});++MasonrySkeleton.displayName = 'MasonrySkeleton';++export default MasonrySkeleton;diff --git a/src/features/FileManager/FileList/ToolBar/ViewSwitcher.tsx b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/ViewSwitcher.tsxsimilarity index 100%rename from src/features/FileManager/FileList/ToolBar/ViewSwitcher.tsxrename to src/features/KnowledgeBaseModal/AssignKnowledgeBase/ViewSwitcher.tsxdiff --git a/src/features/KnowledgeBaseModal/AssignKnowledgeBase/index.tsx b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/index.tsxindex 26d9032befb..8d23883efc8 100644--- a/src/features/KnowledgeBaseModal/AssignKnowledgeBase/index.tsx+++ b/src/features/KnowledgeBaseModal/AssignKnowledgeBase/index.tsx@@ -7,11 +7,12 @@ import { useServerConfigStore } from '@/store/serverConfig';import List from './List';-interface AssignKnowledgeBaseProps {+interface AttachKnowledgeModalProps {open?: boolean;setOpen: (open: boolean) => void;}-export const AssignKnowledgeBaseModal = memo<AssignKnowledgeBaseProps>(({ setOpen, open }) => {++export const AttachKnowledgeModal = memo<AttachKnowledgeModalProps>(({ setOpen, open }) => {const { t } = useTranslation('chat');const mobile = useServerConfigStore((s) => s.isMobile);diff --git a/src/features/KnowledgeBaseModal/CreateNew/CreateForm.tsx b/src/features/KnowledgeBaseModal/CreateNew/CreateForm.tsxindex 94f72e955ff..f95b16cedb3 100644--- a/src/features/KnowledgeBaseModal/CreateNew/CreateForm.tsx+++ b/src/features/KnowledgeBaseModal/CreateNew/CreateForm.tsx@@ -21,11 +21,11 @@ const CreateForm = memo<CreateFormProps>(({ onClose, onSuccess }) => {try {const id = await createNewKnowledgeBase(values);setLoading(false);- onClose?.();// Call onSuccess callback if provided, otherwise navigate directlyif (onSuccess) {onSuccess(id);+ onClose?.();} else {window.location.href = `/knowledge/bases/${id}`;}diff --git a/src/features/FileManager/ChunkDrawer/ChunkList/ChunkItem.tsx b/src/features/KnowledgeManager/ChunkDrawer/ChunkList/ChunkItem.tsxsimilarity index 100%rename from src/features/FileManager/ChunkDrawer/ChunkList/ChunkItem.tsxrename to src/features/KnowledgeManager/ChunkDrawer/ChunkList/ChunkItem.tsxdiff --git a/src/features/FileManager/ChunkDrawer/ChunkList/index.tsx b/src/features/KnowledgeManager/ChunkDrawer/ChunkList/index.tsxsimilarity index 100%rename from src/features/FileManager/ChunkDrawer/ChunkList/index.tsxrename to src/features/KnowledgeManager/ChunkDrawer/ChunkList/index.tsxdiff --git a/src/features/FileManager/ChunkDrawer/Content.tsx b/src/features/KnowledgeManager/ChunkDrawer/Content.tsxsimilarity index 100%rename from src/features/FileManager/ChunkDrawer/Content.tsxrename to src/features/KnowledgeManager/ChunkDrawer/Content.tsxdiff --git a/src/features/FileManager/ChunkDrawer/Loading/index.tsx b/src/features/KnowledgeManager/ChunkDrawer/Loading/index.tsxsimilarity index 100%rename from src/features/FileManager/ChunkDrawer/Loading/index.tsxrename to src/features/KnowledgeManager/ChunkDrawer/Loading/index.tsxdiff --git a/src/features/FileManager/ChunkDrawer/SimilaritySearchList/Item.tsx b/src/features/KnowledgeManager/ChunkDrawer/SimilaritySearchList/Item.tsxsimilarity index 100%rename from src/features/FileManager/ChunkDrawer/SimilaritySearchList/Item.tsxrename to src/features/KnowledgeManager/ChunkDrawer/SimilaritySearchList/Item.tsxdiff --git a/src/features/FileManager/ChunkDrawer/SimilaritySearchList/index.tsx b/src/features/KnowledgeManager/ChunkDrawer/SimilaritySearchList/index.tsxsimilarity index 100%rename from src/features/FileManager/ChunkDrawer/SimilaritySearchList/index.tsxrename to src/features/KnowledgeManager/ChunkDrawer/SimilaritySearchList/index.tsxdiff --git a/src/features/FileManager/ChunkDrawer/index.tsx b/src/features/KnowledgeManager/ChunkDrawer/index.tsxsimilarity index 100%rename from src/features/FileManager/ChunkDrawer/index.tsxrename to src/features/KnowledgeManager/ChunkDrawer/index.tsxdiff --git a/src/features/KnowledgeManager/DocumentExplorer/DocumentActions.tsx b/src/features/KnowledgeManager/DocumentExplorer/DocumentActions.tsxnew file mode 100644index 00000000000..bf58ff46f35--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/DocumentActions.tsx@@ -0,0 +1,111 @@+import { ActionIcon, Dropdown, Icon } from '@lobehub/ui';+import { App } from 'antd';+import { Copy, CopyPlus, MoreHorizontal, Pencil, Trash2 } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';++import { useFileStore } from '@/store/file';++interface DocumentActionsProps {+ documentContent?: string;+ documentId: string;+ onDelete?: () => void;+ onRename?: () => void;+}++const DocumentActions = memo<DocumentActionsProps>(+ ({ documentId, documentContent, onDelete, onRename }) => {+ const { t } = useTranslation(['common', 'file']);+ const { message, modal } = App.useApp();+ const [loading, setLoading] = useState(false);+ const removeDocument = useFileStore((s) => s.removeDocument);+ const duplicateDocument = useFileStore((s) => s.duplicateDocument);++ const handleDelete = () => {+ modal.confirm({+ cancelText: t('cancel'),+ content: t('documentEditor.deleteConfirm.content', { ns: 'file' }),+ okButtonProps: { danger: true },+ okText: t('delete'),+ onOk: async () => {+ setLoading(true);+ try {+ await removeDocument(documentId);+ message.success(t('documentEditor.deleteSuccess', { ns: 'file' }));+ onDelete?.();+ } catch (error) {+ console.error('Failed to delete document:', error);+ message.error(t('documentEditor.deleteError', { ns: 'file' }));+ } finally {+ setLoading(false);+ }+ },+ title: t('documentEditor.deleteConfirm.title', { ns: 'file' }),+ });+ };++ const handleCopy = async () => {+ if (documentContent) {+ try {+ await navigator.clipboard.writeText(documentContent);+ } catch (error) {+ console.error('Failed to copy document:', error);+ }+ }+ };++ const handleDuplicate = async () => {+ setLoading(true);+ try {+ await duplicateDocument(documentId);+ } catch (error) {+ console.error('Failed to duplicate document:', error);+ } finally {+ setLoading(false);+ }+ };++ return (+ <Flexbox align={'center'} horizontal onClick={(e) => e.stopPropagation()}>+ <Dropdown+ menu={{+ items: [+ {+ icon: <Icon icon={Pencil} />,+ key: 'rename',+ label: t('rename'),+ onClick: () => onRename?.(),+ },+ {+ icon: <Icon icon={Copy} />,+ key: 'copy',+ label: t('documentList.copyContent', { ns: 'file' }),+ onClick: handleCopy,+ },+ {+ icon: <Icon icon={CopyPlus} />,+ key: 'duplicate',+ label: t('documentList.duplicate', { ns: 'file' }),+ onClick: handleDuplicate,+ },+ {+ danger: true,+ icon: <Icon icon={Trash2} />,+ key: 'delete',+ label: t('delete'),+ onClick: handleDelete,+ },+ ],+ }}+ placement="bottomRight"+ trigger={['click']}+ >+ <ActionIcon icon={MoreHorizontal} loading={loading} size="small" variant="borderless" />+ </Dropdown>+ </Flexbox>+ );+ },+);++export default DocumentActions;diff --git a/src/features/KnowledgeManager/DocumentExplorer/DocumentEditor.tsx b/src/features/KnowledgeManager/DocumentExplorer/DocumentEditor.tsxnew file mode 100644index 00000000000..0f1b9d45982--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/DocumentEditor.tsx@@ -0,0 +1,723 @@+'use client';++import {+ INSERT_HEADING_COMMAND,+ INSERT_TABLE_COMMAND,+ ReactCodePlugin,+ ReactCodeblockPlugin,+ ReactHRPlugin,+ ReactImagePlugin,+ ReactLinkHighlightPlugin,+ ReactListPlugin,+ ReactMathPlugin,+ ReactTablePlugin,+} from '@lobehub/editor';+import { Editor, useEditor } from '@lobehub/editor/react';+import { ActionIcon, Button, Dropdown, Icon } from '@lobehub/ui';+import { useDebounceFn } from 'ahooks';+import { App } from 'antd';+import { useTheme } from 'antd-style';+import dayjs from 'dayjs';+import relativeTime from 'dayjs/plugin/relativeTime';+import {+ FileText,+ Heading1Icon,+ Heading2Icon,+ Heading3Icon,+ Link2,+ Loader2Icon,+ MoreVertical,+ SmilePlus,+ Table2Icon,+ Trash2,+} from 'lucide-react';+import dynamic from 'next/dynamic';+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';++import { documentService } from '@/services/document';+import { useFileStore } from '@/store/file';+import { documentSelectors } from '@/store/file/slices/document/selectors';+import { useGlobalStore } from '@/store/global';+import { globalGeneralSelectors } from '@/store/global/selectors';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';+import { DocumentSourceType, LobeDocument } from '@/types/document';++dayjs.extend(relativeTime);++const SAVE_THROTTLE_TIME = 3000; // ms+const RESET_DELAY = 100; // ms++const EmojiPicker = dynamic(() => import('@lobehub/ui/es/EmojiPicker'), { ssr: false });++interface DocumentEditorPanelProps {+ documentId?: string;+ knowledgeBaseId?: string;+ onDelete?: () => void;+ onDocumentIdChange?: (newId: string) => void;+ onSave?: () => void;+}++const DocumentEditor = memo<DocumentEditorPanelProps>(+ ({ documentId, knowledgeBaseId, onDocumentIdChange, onSave, onDelete }) => {+ const { t } = useTranslation(['file', 'common']);+ const theme = useTheme();+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);+ const { message, modal } = App.useApp();+ const username = useUserStore(userProfileSelectors.displayUserName);++ const editor = useEditor();++ const currentDocument = useFileStore(documentSelectors.getDocumentById(documentId));+ const currentDocumentTitle = currentDocument?.title;+ const currentDocumentEmoji = currentDocument?.metadata?.emoji;++ const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved'>('idle');+ const [currentTitle, setCurrentTitle] = useState('');+ const [currentEmoji, setCurrentEmoji] = useState<string | undefined>(undefined);+ const [isHoveringTitle, setIsHoveringTitle] = useState(false);+ const [showEmojiPicker, setShowEmojiPicker] = useState(false);+ const [currentDocId, setCurrentDocId] = useState<string | undefined>(documentId);+ const [lastUpdatedTime, setLastUpdatedTime] = useState<Date | null>(null);+ const [wordCount, setWordCount] = useState(0);++ const refreshFileList = useFileStore((s) => s.refreshFileList);+ const updateDocumentOptimistically = useFileStore((s) => s.updateDocumentOptimistically);+ const replaceTempDocumentWithReal = useFileStore((s) => s.replaceTempDocumentWithReal);+ const removeDocument = useFileStore((s) => s.removeDocument);++ const isInitialLoadRef = useRef(false);++ // Helper function to calculate word count from text+ const calculateWordCount = useCallback((text: string) => {+ return text.trim().split(/\s+/).filter(Boolean).length;+ }, []);++ // Helper function to extract content from pages array+ const extractContentFromPages = useCallback((pages?: Array<{ pageContent: string }>) => {+ if (!pages || pages.length === 0) return null;+ return pages.map((page) => page.pageContent).join('\n\n');+ }, []);++ // Sync title and emoji when document data changes (e.g., from rename)+ useEffect(() => {+ if (currentDocumentTitle !== undefined && currentDocumentTitle !== currentTitle) {+ setCurrentTitle(currentDocumentTitle);+ }+ if (currentDocumentEmoji !== currentEmoji) {+ setCurrentEmoji(currentDocumentEmoji);+ }+ }, [currentDocumentTitle, currentDocumentEmoji]);++ // Load document content when documentId changes+ useEffect(() => {+ // Reset initial load flag when switching documents+ isInitialLoadRef.current = true;++ if (documentId && editor) {+ setShowEmojiPicker(false);+ setCurrentEmoji(currentDocumentEmoji);+ setLastUpdatedTime(null);++ // Check if this is an optimistic temp document+ if (currentDocument && documentId.startsWith('temp-document-')) {+ console.log('[DocumentEditor] Using optimistic document from currentDocument');+ setCurrentTitle(currentDocument.title || 'Untitled Document');+ // Start with empty editor for new documents+ editor.cleanDocument();+ setWordCount(0);+ // Reset flag after cleanDocument (no onChange should fire for cleanDocument)+ setTimeout(() => {+ isInitialLoadRef.current = false;+ }, RESET_DELAY);+ return;+ }++ if (currentDocument?.editorData && Object.keys(currentDocument.editorData).length > 0) {+ setCurrentTitle(currentDocumentTitle || '');+ isInitialLoadRef.current = true;++ console.log('[DocumentEditor] Setting editor data', currentDocument.editorData);++ editor.setDocument('json', JSON.stringify(currentDocument.editorData));+ // Calculate word count from content+ const textContent = currentDocument.content || '';+ setWordCount(calculateWordCount(textContent));+ setTimeout(() => {+ isInitialLoadRef.current = false;+ }, RESET_DELAY);+ return;+ } else if (currentDocument?.pages && editor) {+ const pagesContent = extractContentFromPages(currentDocument.pages);+ if (pagesContent) {+ console.log('[DocumentEditor] Using pages content as fallback');+ setCurrentTitle(currentDocumentTitle || '');+ isInitialLoadRef.current = true;+ editor.setDocument('markdown', pagesContent);+ // Calculate word count from pages content+ setWordCount(calculateWordCount(pagesContent));+ setTimeout(() => {+ isInitialLoadRef.current = false;+ }, RESET_DELAY);+ return;+ }+ } else {+ // Reset editor+ editor.cleanDocument();+ setWordCount(0);+ isInitialLoadRef.current = false;+ return;+ }+ }+ }, [+ documentId,+ currentDocument,+ currentDocumentTitle,+ currentDocumentEmoji,+ editor,+ calculateWordCount,+ extractContentFromPages,+ ]);++ // Auto-save function+ const performSave = useCallback(async () => {+ if (!editor) return;++ const editorData = editor.getDocument('json');+ const textContent = (editor.getDocument('markdown') as unknown as string) || '';++ // Don't save if content is empty+ if (!textContent || textContent.trim() === '') {+ return;+ }++ // Store focus state before saving+ // Check if the editor's root element or any of its descendants has focus+ const editorElement = editor.getRootElement();+ const hadFocus = editorElement?.contains(document.activeElement) ?? false;++ setSaveStatus('saving');++ try {+ if (currentDocId && !currentDocId.startsWith('temp-document-')) {+ // Update existing document with optimistic update (including metadata for emoji)+ await updateDocumentOptimistically(currentDocId, {+ content: textContent,+ editorData: structuredClone(editorData),+ metadata: currentEmoji+ ? {+ emoji: currentEmoji,+ }+ : {+ emoji: undefined, // Explicitly set to undefined to remove emoji+ },+ title: currentTitle,+ updatedAt: new Date(),+ });++ // Restore focus if editor had it before save+ if (hadFocus) {+ // Use setTimeout to ensure focus is restored after any re-renders+ setTimeout(() => {+ editor.focus();+ }, 0);+ }+ } else {+ // Create new document (either no ID or temp ID)+ const now = Date.now();+ const timestamp = new Date(now).toLocaleString('en-US', {+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ month: 'short',+ year: 'numeric',+ });+ const title = currentTitle || `Document - ${timestamp}`;++ const newDoc = await documentService.createDocument({+ content: textContent,+ editorData: JSON.stringify(editorData),+ fileType: 'custom/document',+ knowledgeBaseId,+ metadata: currentEmoji+ ? {+ createdAt: now,+ emoji: currentEmoji,+ }+ : {+ createdAt: now,+ },+ title,+ });++ // Create the real document object for optimistic update+ const realDocument: LobeDocument = {+ content: textContent,+ createdAt: new Date(now),+ editorData: structuredClone(editorData) || null,+ fileType: 'custom/document' as const,+ filename: title,+ id: newDoc.id,+ metadata: currentEmoji+ ? {+ createdAt: now,+ emoji: currentEmoji,+ }+ : {+ createdAt: now,+ },+ source: 'document',+ sourceType: DocumentSourceType.EDITOR,+ title,+ totalCharCount: textContent.length,+ totalLineCount: 0,+ updatedAt: new Date(now),+ };++ // Replace temp document with real document (smooth UX, no flicker)+ if (currentDocId?.startsWith('temp-document-')) {+ replaceTempDocumentWithReal(currentDocId, realDocument);+ }++ // Update state and notify parent+ setCurrentDocId(newDoc.id);+ onDocumentIdChange?.(newDoc.id);++ // Refresh in background to sync with server+ refreshFileList();++ // Restore focus if editor had it before save+ if (hadFocus) {+ setTimeout(() => {+ editor.focus();+ }, 0);+ }+ }++ setSaveStatus('saved');+ // Update last updated time+ setLastUpdatedTime(new Date());++ onSave?.();+ } catch {+ setSaveStatus('idle');+ }+ }, [+ editor,+ currentDocId,+ currentTitle,+ currentEmoji,+ knowledgeBaseId,+ refreshFileList,+ updateDocumentOptimistically,+ onSave,+ onDocumentIdChange,+ replaceTempDocumentWithReal,+ ]);++ // Handle content change - auto-save after debounce (with skip initial load)+ const handleContentChangeInternal = useCallback(() => {+ // Skip if we're in the initial load phase+ if (isInitialLoadRef.current) {+ console.log('[DocumentEditor] Skipping onChange during initial load');+ return;+ }++ console.log('[DocumentEditor] Content changed, triggering auto-save');++ // Update word count from editor+ if (editor) {+ try {+ const textContent = (editor.getDocument('text') as unknown as string) || '';+ setWordCount(calculateWordCount(textContent));+ } catch (error) {+ console.error('Failed to update word count:', error);+ }+ }++ performSave();+ }, [performSave, editor, calculateWordCount]);++ const { run: handleContentChange } = useDebounceFn(handleContentChangeInternal, {+ wait: SAVE_THROTTLE_TIME,+ });++ // Debounced save for title/emoji changes (no initial load check needed)+ const { run: debouncedSave } = useDebounceFn(performSave, {+ wait: SAVE_THROTTLE_TIME,+ });++ // Update currentDocId when documentId prop changes+ useEffect(() => {+ setCurrentDocId(documentId);+ }, [documentId]);++ // Clean up when closing+ useEffect(() => {+ return () => {+ editor?.cleanDocument();+ };+ }, [editor]);++ // Handle Cmd+S / Ctrl+S keyboard shortcut+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 's') {+ e.preventDefault();+ message.info(t('documentEditor.autoSaveMessage'));+ }+ };++ document.addEventListener('keydown', handleKeyDown);+ return () => {+ document.removeEventListener('keydown', handleKeyDown);+ };+ }, [t]);++ // Handle delete document+ const handleDelete = useCallback(async () => {+ if (!currentDocId) return;++ modal.confirm({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('documentEditor.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('delete', { ns: 'common' }),+ onOk: async () => {+ try {+ await removeDocument(currentDocId);+ message.success(t('documentEditor.deleteSuccess'));+ onDelete?.();+ } catch (error) {+ console.error('Failed to delete document:', error);+ message.error(t('documentEditor.deleteError'));+ }+ },+ title: t('documentEditor.deleteConfirm.title'),+ });+ }, [currentDocId, modal, removeDocument, message, onDelete, t]);++ // Menu items for the three-dot menu+ const menuItems = useMemo(+ () => [+ {+ icon: <Icon icon={Link2} />,+ key: 'copy-link',+ label: t('documentEditor.menu.copyLink'),+ onClick: () => {+ if (currentDocId) {+ const url = `${window.location.origin}${window.location.pathname}`;+ navigator.clipboard.writeText(url);+ message.success(t('documentEditor.linkCopied'));+ }+ },+ },+ {+ danger: true,+ icon: <Icon icon={Trash2} />,+ key: 'delete',+ label: t('delete', { ns: 'common' }),+ onClick: handleDelete,+ },+ // {+ // type: 'divider' as const,+ // },+ // {+ // icon: <Icon icon={Download} />,+ // key: 'export',+ // label: t('documentEditor.menu.exportDocument'),+ // onClick: () => {+ // // TODO: Implement export functionality+ // console.log('Export clicked');+ // },+ // },+ // {+ // icon: <Icon icon={Upload} />,+ // key: 'import',+ // label: t('documentEditor.menu.importDocument'),+ // onClick: () => {+ // // TODO: Implement import functionality+ // console.log('Import clicked');+ // },+ // },+ {+ type: 'divider' as const,+ },+ {+ disabled: true,+ key: 'document-info',+ label: (+ <div style={{ color: theme.colorTextTertiary, fontSize: 12, lineHeight: 1.6 }}>+ <div>{t('documentEditor.wordCount', { wordCount })}</div>+ {/* <div>{t('documentEditor.editedBy', { name: username })}</div> */}+ <div>+ {lastUpdatedTime+ ? t('documentEditor.editedAt', {+ time: dayjs(lastUpdatedTime).format('MMMM D, YYYY [at] h:mm A'),+ })+ : ''}+ </div>+ </div>+ ),+ },+ ],+ [theme, wordCount, username, lastUpdatedTime, handleDelete, currentDocId, message, t],+ );++ return (+ <Flexbox height={'100%'} style={{ background: theme.colorBgContainer }}>+ {/* Header */}+ <Flexbox+ align="center"+ direction="horizontal"+ gap={8}+ paddingBlock={8}+ paddingInline={16}+ style={{+ background: theme.colorBgContainer,+ }}+ >+ {/* Icon */}+ {currentEmoji ? (+ <span style={{ fontSize: 20, lineHeight: 1 }}>{currentEmoji}</span>+ ) : (+ <Icon icon={FileText} size={20} style={{ color: theme.colorTextSecondary }} />+ )}++ {/* Title */}+ <Flexbox+ flex={1}+ style={{+ color: theme.colorText,+ fontSize: 14,+ fontWeight: 500,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {currentTitle || t('documentEditor.titlePlaceholder')}+ </Flexbox>++ {/* Save Status Indicator */}+ {saveStatus === 'saving' && (+ <Flexbox>+ <Icon icon={Loader2Icon} spin />+ </Flexbox>+ )}++ {/* Last Updated Time */}+ {lastUpdatedTime && (+ <span+ style={{+ color: theme.colorTextTertiary,+ fontSize: 12,+ whiteSpace: 'nowrap',+ }}+ >+ {t('documentEditor.editedAt', { time: dayjs(lastUpdatedTime).fromNow() })}+ </span>+ )}++ {/* Pin action */}+ {/* <ActionIcon+ icon={Pin}+ onClick={() => {+ // TODO: Implement pin functionality+ console.log('Pin clicked');+ }}+ size={15.5}+ style={{ color: theme.colorText }}+ /> */}++ {/* Three-dot menu */}+ <Dropdown+ menu={{+ items: menuItems,+ style: { minWidth: 200 },+ }}+ placement="bottomRight"+ trigger={['click']}+ >+ <ActionIcon icon={MoreVertical} size={15.5} style={{ color: theme.colorText }} />+ </Dropdown>+ </Flexbox>++ {/* Editor with title */}+ <Flexbox flex={1} style={{ overflowY: 'auto' }}>+ <Flexbox+ paddingBlock={36}+ style={{+ margin: '0 auto',+ maxWidth: 900,+ paddingLeft: 32,+ paddingRight: 48,+ width: '100%',+ }}+ >+ {/* Emoji and Title */}+ <Flexbox+ onMouseEnter={() => setIsHoveringTitle(true)}+ onMouseLeave={() => setIsHoveringTitle(false)}+ style={{ marginBottom: 24 }}+ >+ {/* Emoji picker above Choose Icon button */}+ {(currentEmoji || showEmojiPicker) && (+ <Flexbox style={{ marginBottom: 4 }}>+ <EmojiPicker+ allowDelete+ locale={locale}+ onChange={(emoji) => {+ setCurrentEmoji(emoji);+ setShowEmojiPicker(false);+ debouncedSave();+ }}+ onDelete={() => {+ setCurrentEmoji(undefined);+ setShowEmojiPicker(false);+ debouncedSave();+ }}+ onOpenChange={(open) => {+ setShowEmojiPicker(open);+ }}+ open={showEmojiPicker}+ size={80}+ style={{+ fontSize: 80,+ transform: 'translateX(-6px)',+ }}+ title={t('documentEditor.chooseIcon')}+ value={currentEmoji}+ />+ </Flexbox>+ )}++ {/* Choose Icon button - only shown when no emoji */}+ <Flexbox style={{ marginBottom: 12 }}>+ <Button+ icon={<Icon icon={SmilePlus} />}+ onClick={() => {+ setCurrentEmoji('📄');+ setShowEmojiPicker(true);+ }}+ size="small"+ style={{+ opacity: isHoveringTitle && !currentEmoji && !showEmojiPicker ? 1 : 0,+ transform: 'translateX(-6px)',+ transition: `opacity ${theme.motionDurationMid} ${theme.motionEaseInOut}`,+ width: 'fit-content',+ }}+ type="text"+ >+ {t('documentEditor.chooseIcon')}+ </Button>+ </Flexbox>++ {/* Title Input */}+ <Flexbox align="center" direction="horizontal" gap={8}>+ <input+ onChange={(e) => {+ setCurrentTitle(e.target.value);+ debouncedSave();+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ // Save immediately and focus on the editor+ performSave().then(() => {+ editor?.focus();+ });+ }+ }}+ placeholder={t('documentEditor.titlePlaceholder')}+ style={{+ background: 'transparent',+ border: 'none',+ color: theme.colorText,+ flex: 1,+ fontSize: 40,+ fontWeight: 700,+ lineHeight: 1.2,+ outline: 'none',+ }}+ value={currentTitle}+ />+ </Flexbox>+ </Flexbox>++ <div+ onClick={() => editor?.focus()}+ style={{+ cursor: 'text',+ flex: 1,+ minHeight: '400px',+ }}+ >+ <Editor+ content={''}+ editor={editor}+ onTextChange={handleContentChange}+ placeholder={t('documentEditor.editorPlaceholder')}+ plugins={[+ ReactListPlugin,+ ReactCodePlugin,+ ReactCodeblockPlugin,+ ReactHRPlugin,+ ReactLinkHighlightPlugin,+ ReactTablePlugin,+ ReactMathPlugin,+ ReactImagePlugin,+ ]}+ slashOption={{+ items: [+ {+ icon: Heading1Icon,+ key: 'h1',+ label: 'Heading 1',+ onSelect: (editor) => {+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h1' });+ },+ },+ {+ icon: Heading2Icon,+ key: 'h2',+ label: 'Heading 2',+ onSelect: (editor) => {+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h2' });+ },+ },+ {+ icon: Heading3Icon,+ key: 'h3',+ label: 'Heading 3',+ onSelect: (editor) => {+ editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h3' });+ },+ },+ {+ icon: Table2Icon,+ key: 'table',+ label: 'Table',+ onSelect: (editor) => {+ editor.dispatchCommand(INSERT_TABLE_COMMAND, { columns: '3', rows: '3' });+ },+ },+ ],+ }}+ style={{+ minHeight: '400px',+ paddingBottom: '200px',+ }}+ type={'text'}+ />+ </div>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+ },+);++export default DocumentEditor;diff --git a/src/features/KnowledgeManager/DocumentExplorer/DocumentEditorPlaceholder.tsx b/src/features/KnowledgeManager/DocumentExplorer/DocumentEditorPlaceholder.tsxnew file mode 100644index 00000000000..090fff523d9--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/DocumentEditorPlaceholder.tsx@@ -0,0 +1,169 @@+import { FileTypeIcon, Icon, Text } from '@lobehub/ui';+import { Upload } from 'antd';+import { createStyles, useTheme } from 'antd-style';+import { ArrowUpIcon, PlusIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Center, Flexbox } from 'react-layout-kit';++import { useFileStore } from '@/store/file';++const ICON_SIZE = 80;++const useStyles = createStyles(({ css, token }) => ({+ actionTitle: css`+ margin-block-start: 12px;+ font-size: 16px;+ color: ${token.colorTextSecondary};+ `,+ card: css`+ cursor: pointer;++ position: relative;++ overflow: hidden;++ width: 200px;+ height: 140px;+ border-radius: ${token.borderRadiusLG}px;++ font-weight: 500;+ text-align: center;++ background: ${token.colorFillTertiary};+ box-shadow: 0 0 0 1px ${token.colorFillTertiary} inset;++ transition: background 0.3s ease-in-out;++ &:hover {+ background: ${token.colorFillSecondary};+ }+ `,+ glow: css`+ position: absolute;+ inset-block-end: -12px;+ inset-inline-end: 0;++ width: 48px;+ height: 48px;++ opacity: 0.5;+ filter: blur(24px);+ `,+ icon: css`+ position: absolute;+ z-index: 1;+ inset-block-end: -24px;+ inset-inline-end: 8px;++ flex: none;+ `,+}));++interface DocumentEditorPlaceholderProps {+ knowledgeBaseId?: string;+ onCreateNewNote: () => void;+ onNoteCreated?: (noteId: string) => void;+}++const DocumentEditorPlaceholder = memo<DocumentEditorPlaceholderProps>(+ ({ knowledgeBaseId, onCreateNewNote, onNoteCreated }) => {+ const { t } = useTranslation(['file', 'common']);+ const theme = useTheme();+ const { styles } = useStyles();+ const [isUploading, setIsUploading] = useState(false);+ const createDocument = useFileStore((s) => s.createDocument);++ const handleUploadMarkdown = async (file: File) => {+ try {+ setIsUploading(true);++ // Read markdown file content+ const content = await file.text();++ // Create document with markdown content+ const newDoc = await createDocument({+ content,+ knowledgeBaseId,+ title: file.name.replace(/\.md$|\.markdown$/i, ''),+ });++ // Notify parent component+ onNoteCreated?.(newDoc.id);+ } catch (error) {+ console.error('Failed to upload markdown:', error);+ } finally {+ setIsUploading(false);+ }++ return false; // Prevent default upload behavior+ };++ return (+ <Center gap={24} height={'100%'} style={{ paddingBottom: 100 }} width={'100%'}>+ <Flexbox justify={'center'} style={{ textAlign: 'center' }}>+ <Text as={'h4'}>{t('documentEditor.empty.title')}</Text>+ <Text type={'secondary'}>{t('or', { ns: 'common' })}</Text>+ </Flexbox>+ <Flexbox gap={12} horizontal>+ {/* Create New Note */}+ <Flexbox className={styles.card} onClick={onCreateNewNote} padding={16}>+ <span className={styles.actionTitle}>+ {t('documentEditor.empty.createNewDocument')}+ </span>+ <div className={styles.glow} style={{ background: theme.purple }} />+ <FileTypeIcon+ className={styles.icon}+ color={theme.purple}+ icon={<Icon color={'#fff'} icon={PlusIcon} />}+ size={ICON_SIZE}+ type={'file'}+ />+ </Flexbox>++ {/* Upload Markdown File */}+ <Upload+ accept=".md,.markdown"+ beforeUpload={handleUploadMarkdown}+ disabled={isUploading}+ multiple={false}+ showUploadList={false}+ >+ <Flexbox+ className={styles.card}+ padding={16}+ style={{ opacity: isUploading ? 0.5 : 1 }}+ >+ <span className={styles.actionTitle}>+ {isUploading ? 'Uploading...' : t('documentEditor.empty.uploadMarkdown')}+ </span>+ <div className={styles.glow} style={{ background: theme.gold }} />+ <FileTypeIcon+ className={styles.icon}+ color={theme.gold}+ icon={<Icon color={'#fff'} icon={ArrowUpIcon} />}+ size={ICON_SIZE}+ type={'file'}+ />+ </Flexbox>+ </Upload>++ {/* Import from Notion */}+ {/* <Flexbox className={styles.card} onClick={handleImportFromNotion} padding={16}>+ <span className={styles.actionTitle}>Import from Notion</span>+ <div className={styles.glow} style={{ background: theme.geekblue }} />+ <FileTypeIcon+ className={styles.icon}+ color={theme.geekblue}+ icon={<Icon color={'#fff'} icon={FileTextIcon} />}+ size={ICON_SIZE}+ type={'doc'}+ />+ </Flexbox> */}+ </Flexbox>+ </Center>+ );+ },+);++export default DocumentEditorPlaceholder;diff --git a/src/features/KnowledgeManager/DocumentExplorer/DocumentListItem.tsx b/src/features/KnowledgeManager/DocumentExplorer/DocumentListItem.tsxnew file mode 100644index 00000000000..07b535d855d--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/DocumentListItem.tsx@@ -0,0 +1,148 @@+'use client';++import { Icon } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { FileText } from 'lucide-react';+import { memo } from 'react';++import { LobeDocument } from '@/types/document';++import DocumentActions from './DocumentActions';+import RenamePopover from './RenamePopover';++const useStyles = createStyles(({ css, token }) => ({+ documentActions: css`+ opacity: 0;+ transition: opacity ${token.motionDurationMid};+ `,+ documentCard: css`+ cursor: pointer;+ user-select: none;++ position: relative;++ display: flex;+ gap: 12px;+ align-items: center;++ min-height: 36px;+ margin-block: 4px;+ margin-inline: 8px;+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${token.borderRadius}px;++ color: ${token.colorTextSecondary};++ background: transparent;++ transition: all ${token.motionDurationMid};++ &:hover {+ background: ${token.colorFillTertiary};++ .document-actions {+ opacity: 1;+ }+ }++ &.selected {+ color: ${token.colorText};+ background: ${token.colorFillSecondary};+ }+ `,+ documentContent: css`+ display: flex;+ flex: 1;+ gap: 12px;+ align-items: center;++ min-width: 0;+ `,+ documentTitle: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ font-size: 14px;+ line-height: 20px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ emoji: css`+ font-size: 16px;+ line-height: 1;+ `,+ icon: css`+ display: flex;+ align-items: center;+ justify-content: center;+ color: ${token.colorTextSecondary};+ `,+}));++interface DocumentListItemProps {+ document: LobeDocument;+ isRenaming: boolean;+ isSelected: boolean;+ onDelete: () => void;+ onRenameConfirm: (documentId: string, title: string, emoji?: string) => void;+ onRenameOpenChange: (documentId: string, open: boolean) => void;+ onSelect: (documentId: string) => void;+ untitledText: string;+}++const DocumentListItem = memo<DocumentListItemProps>(+ ({+ document,+ isRenaming,+ isSelected,+ onDelete,+ onRenameConfirm,+ onRenameOpenChange,+ onSelect,+ untitledText,+ }) => {+ const { styles, cx } = useStyles();++ const title = document.title || untitledText;+ const emoji = document.metadata?.emoji;++ return (+ <div+ className={cx(styles.documentCard, isSelected && 'selected')}+ onClick={() => !isRenaming && onSelect(document.id)}+ >+ <RenamePopover+ currentEmoji={emoji}+ currentTitle={title}+ onConfirm={(newTitle, newEmoji) => {+ onRenameConfirm(document.id, newTitle, newEmoji);+ }}+ onOpenChange={(open) => onRenameOpenChange(document.id, open)}+ open={isRenaming}+ >+ <div className={styles.documentContent}>+ {emoji ? (+ <span className={styles.emoji}>{emoji}</span>+ ) : (+ <Icon className={styles.icon} icon={FileText} size={16} />+ )}+ <div className={styles.documentTitle}>{title}</div>+ </div>+ </RenamePopover>+ <div className={cx(styles.documentActions, 'document-actions')}>+ <DocumentActions+ documentContent={document.content || undefined}+ documentId={document.id}+ onDelete={onDelete}+ onRename={() => onRenameOpenChange(document.id, true)}+ />+ </div>+ </div>+ );+ },+);++export default DocumentListItem;diff --git a/src/features/KnowledgeManager/DocumentExplorer/DocumentListSkeleton.tsx b/src/features/KnowledgeManager/DocumentExplorer/DocumentListSkeleton.tsxnew file mode 100644index 00000000000..ac091fb55a4--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/DocumentListSkeleton.tsx@@ -0,0 +1,39 @@+import { Skeleton } from 'antd';+import { createStyles } from 'antd-style';+import { Flexbox } from 'react-layout-kit';++const useStyles = createStyles(({ css, token }) => ({+ skeletonCard: css`+ display: flex;+ gap: 12px;+ align-items: center;++ min-height: 36px;+ margin-block: 4px;+ margin-inline: 8px;+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${token.borderRadius}px;++ background: transparent;+ `,+}));++const DocumentListSkeleton = () => {+ const { styles } = useStyles();++ return (+ <Flexbox>+ {Array.from({ length: 8 }).map((_, index) => (+ <div className={styles.skeletonCard} key={index}>+ {/* Icon skeleton */}+ <Skeleton.Avatar active shape="square" size={16} />+ {/* Title skeleton */}+ <Skeleton.Input active size="small" style={{ height: 20, minWidth: 120, width: 120 }} />+ </div>+ ))}+ </Flexbox>+ );+};++export default DocumentListSkeleton;diff --git a/src/features/KnowledgeManager/DocumentExplorer/NoteEditorModal.tsx b/src/features/KnowledgeManager/DocumentExplorer/NoteEditorModal.tsxnew file mode 100644index 00000000000..bc046c4f21e--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/NoteEditorModal.tsx@@ -0,0 +1,348 @@+'use client';++import {+ HotkeyEnum,+ ReactCodePlugin,+ ReactCodeblockPlugin,+ ReactHRPlugin,+ ReactLinkHighlightPlugin,+ ReactListPlugin,+ ReactMathPlugin,+ ReactTablePlugin,+ getHotkeyById,+} from '@lobehub/editor';+import {+ ChatInputActionBar,+ ChatInputActions,+ type ChatInputActionsProps,+ CodeLanguageSelect,+ Editor,+ useEditor,+ useEditorState,+} from '@lobehub/editor/react';+import { Modal } from '@lobehub/ui';+import { css, cx, useTheme } from 'antd-style';+import {+ BoldIcon,+ CodeXmlIcon,+ ItalicIcon,+ ListIcon,+ ListOrderedIcon,+ ListTodoIcon,+ MessageSquareQuote,+ SigmaIcon,+ SquareDashedBottomCodeIcon,+ StrikethroughIcon,+ UnderlineIcon,+} from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';++import { message } from '@/components/AntdStaticMethods';+import { documentService } from '@/services/document';+import { useFileStore } from '@/store/file';++const editorClassName = cx(css`+ p {+ margin-block-end: 0;+ }+`);++interface NoteEditorModalProps {+ documentId?: string;+ documentTitle?: string;+ editorData?: Record<string, any> | null;+ knowledgeBaseId?: string;+ onClose: () => void;+ open: boolean;+}++const NoteEditorModal = memo<NoteEditorModalProps>(+ ({ open, onClose, documentId, documentTitle, editorData: cachedEditorData, knowledgeBaseId }) => {+ const { t } = useTranslation(['file', 'editor']);+ const theme = useTheme();++ const editor = useEditor();+ const editorState = useEditorState(editor);++ const [isSaving, setIsSaving] = useState(false);+ const [noteTitle, setNoteTitle] = useState('');+ const refreshFileList = useFileStore((s) => s.refreshFileList);+ const isEditMode = !!documentId;++ const handleClose = () => {+ // Clean up editor state+ editor?.cleanDocument();+ setNoteTitle('');+ onClose();+ };++ const handleSave = async () => {+ if (!editor || isSaving) return;++ // Get editor content as JSON (native format)+ const editorData = editor.getDocument('json');++ // Check if editor is empty by getting text content+ const textContent = (editor.getDocument('markdown') as unknown as string) || '';+ if (!textContent || textContent.trim() === '') {+ message.warning(t('header.newNoteDialog.emptyContent', { ns: 'file' }));+ return;+ }++ setIsSaving(true);++ try {+ if (isEditMode) {+ // Update existing note+ await documentService.updateDocument({+ content: textContent,+ editorData: JSON.stringify(editorData),+ id: documentId,+ title: noteTitle,+ });+ message.success(t('header.newNoteDialog.updateSuccess', { ns: 'file' }));+ } else {+ // Create new note+ const now = Date.now();+ const timestamp = new Date(now).toLocaleString('en-US', {+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ month: 'short',+ year: 'numeric',+ });+ const title = noteTitle || `Note - ${timestamp}`;++ await documentService.createDocument({+ content: textContent,+ editorData: JSON.stringify(editorData),+ fileType: 'custom/document',+ knowledgeBaseId,+ metadata: {+ createdAt: now,+ },+ title,+ });++ message.success(t('header.newNoteDialog.saveSuccess', { ns: 'file' }));+ editor.cleanDocument();+ }++ onClose();+ await refreshFileList();+ } catch (error) {+ console.error('Failed to save note:', error);+ message.error(t('header.newNoteDialog.saveError', { ns: 'file' }));+ } finally {+ setIsSaving(false);+ }+ };++ const handleOpenChange = (isOpen: boolean) => {+ // When modal opens, load document content if in edit mode+ if (isOpen && documentId && editor) {+ console.log('[NoteEditorModal] Loading content:', {+ cachedEditorDataPreview: cachedEditorData+ ? JSON.stringify(cachedEditorData).slice(0, 100)+ : null,+ cachedEditorDataType: typeof cachedEditorData,+ documentId,+ documentTitle,+ hasCachedEditorData: !!cachedEditorData,+ });++ // If editorData is already cached (from list), use it directly+ if (cachedEditorData) {+ console.log('[NoteEditorModal] Using cached editorData', cachedEditorData);+ setNoteTitle(documentTitle || '');+ editor.setDocument('json', JSON.stringify(cachedEditorData));+ return;+ }++ // Otherwise, fetch full content from API+ console.log('[NoteEditorModal] Fetching from API');+ documentService+ .getDocumentById(documentId)+ .then((doc) => {+ if (doc && doc.content) {+ setNoteTitle(doc.title || doc.filename || '');++ console.log('[NoteEditorModal] Fetched doc.editorData:', {+ editorDataPreview: doc.editorData+ ? JSON.stringify(doc.editorData).slice(0, 100)+ : null,+ editorDataType: typeof doc.editorData,+ hasEditorData: !!doc.editorData,+ });++ editor.setDocument('json', doc.editorData);+ }+ })+ .catch((error) => {+ console.error('[NoteEditorModal] Failed to load document:', error);+ message.error(t('header.newNoteDialog.loadError', { ns: 'file' }));+ });+ }++ // When modal closes, clean up state+ if (!isOpen) {+ editor?.cleanDocument();+ setNoteTitle('');+ }+ };++ const toolbarItems: ChatInputActionsProps['items'] = useMemo(+ () =>+ [+ {+ active: editorState.isBold,+ icon: BoldIcon,+ key: 'bold',+ label: t('typobar.bold', { ns: 'editor' }),+ onClick: editorState.bold,+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Bold).keys },+ },+ {+ active: editorState.isItalic,+ icon: ItalicIcon,+ key: 'italic',+ label: t('typobar.italic', { ns: 'editor' }),+ onClick: editorState.italic,+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Italic).keys },+ },+ {+ active: editorState.isUnderline,+ icon: UnderlineIcon,+ key: 'underline',+ label: t('typobar.underline', { ns: 'editor' }),+ onClick: editorState.underline,+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Underline).keys },+ },+ {+ active: editorState.isStrikethrough,+ icon: StrikethroughIcon,+ key: 'strikethrough',+ label: t('typobar.strikethrough', { ns: 'editor' }),+ onClick: editorState.strikethrough,+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Strikethrough).keys },+ },+ {+ type: 'divider',+ },+ {+ icon: ListIcon,+ key: 'bulletList',+ label: t('typobar.bulletList', { ns: 'editor' }),+ onClick: editorState.bulletList,+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.BulletList).keys },+ },+ {+ icon: ListOrderedIcon,+ key: 'numberlist',+ label: t('typobar.numberList', { ns: 'editor' }),+ onClick: editorState.numberList,+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.NumberList).keys },+ },+ {+ icon: ListTodoIcon,+ key: 'tasklist',+ label: t('typobar.taskList', { ns: 'editor' }),+ onClick: editorState.checkList,+ },+ {+ type: 'divider',+ },+ {+ active: editorState.isBlockquote,+ icon: MessageSquareQuote,+ key: 'blockquote',+ label: t('typobar.blockquote', { ns: 'editor' }),+ onClick: editorState.blockquote,+ },+ {+ type: 'divider',+ },+ {+ icon: SigmaIcon,+ key: 'math',+ label: t('typobar.tex', { ns: 'editor' }),+ onClick: editorState.insertMath,+ },+ {+ active: editorState.isCode,+ icon: CodeXmlIcon,+ key: 'code',+ label: t('typobar.code', { ns: 'editor' }),+ onClick: editorState.code,+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.CodeInline).keys },+ },+ {+ icon: SquareDashedBottomCodeIcon,+ key: 'codeblock',+ label: t('typobar.codeblock', { ns: 'editor' }),+ onClick: editorState.codeblock,+ },+ editorState.isCodeblock && {+ children: (+ <CodeLanguageSelect+ onSelect={(value) => editorState.updateCodeblockLang(value)}+ value={editorState.codeblockLang}+ />+ ),+ disabled: !editorState.isCodeblock,+ key: 'codeblockLang',+ },+ ].filter(Boolean) as ChatInputActionsProps['items'],+ [editorState, t],+ );++ return (+ <Modal+ afterOpenChange={handleOpenChange}+ okButtonProps={{ loading: isSaving }}+ okText={t('header.newNoteDialog.save')}+ onCancel={handleClose}+ onOk={handleSave}+ open={open}+ title={isEditMode ? t('header.newNoteDialog.editTitle') : t('header.newNoteDialog.title')}+ width={800}+ >+ <Flexbox gap={0}>+ <ChatInputActionBar+ left={<ChatInputActions items={toolbarItems} />}+ style={{+ background: theme.colorFillQuaternary,+ borderTopLeftRadius: 8,+ borderTopRightRadius: 8,+ }}+ />+ <Flexbox padding={16}>+ <Editor+ // autoFocus+ className={editorClassName}+ content={''}+ editor={editor}+ plugins={[+ ReactListPlugin,+ ReactCodePlugin,+ ReactCodeblockPlugin,+ ReactHRPlugin,+ ReactLinkHighlightPlugin,+ ReactTablePlugin,+ ReactMathPlugin,+ ]}+ style={{+ minHeight: 400,+ }}+ type={'text'}+ />+ </Flexbox>+ </Flexbox>+ </Modal>+ );+ },+);++export default NoteEditorModal;diff --git a/src/features/KnowledgeManager/DocumentExplorer/RenamePopover.tsx b/src/features/KnowledgeManager/DocumentExplorer/RenamePopover.tsxnew file mode 100644index 00000000000..00163bfa4b4--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/RenamePopover.tsx@@ -0,0 +1,163 @@+'use client';++import { Input, Popover } from 'antd';+import { createStyles } from 'antd-style';+import dynamic from 'next/dynamic';+import React, { memo, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useGlobalStore } from '@/store/global';+import { globalGeneralSelectors } from '@/store/global/selectors';++const EmojiPicker = dynamic(() => import('@lobehub/ui/es/EmojiPicker'), { ssr: false });++const useStyles = createStyles(({ css }) => ({+ input: css`+ flex: 1;+ `,+ inputGroup: css`+ display: flex;+ gap: 8px;+ align-items: center;+ `,+ popoverContent: css`+ width: 320px;+ `,+}));++interface RenamePopoverProps {+ children: React.ReactElement;+ currentEmoji?: string;+ currentTitle: string;+ onConfirm: (title: string, emoji?: string) => void;+ onOpenChange: (open: boolean) => void;+ open: boolean;+}++const RenamePopover = memo<RenamePopoverProps>(+ ({ children, currentTitle, currentEmoji, onConfirm, open, onOpenChange }) => {+ const { t } = useTranslation(['file', 'editor']);+ const { styles } = useStyles();+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);++ const [title, setTitle] = useState(currentTitle);+ const [emoji, setEmoji] = useState<string | undefined>(currentEmoji);+ const [showEmojiPicker, setShowEmojiPicker] = useState(false);+ const inputRef = useRef<any>(null);+ const isInteractingWithEmojiPicker = useRef(false);++ // Reset state when popover opens+ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen) {+ setTitle(currentTitle);+ setEmoji(currentEmoji);+ setShowEmojiPicker(false);+ }+ onOpenChange(nextOpen);+ };++ // Select all text when popover opens+ useEffect(() => {+ if (open && inputRef.current?.input) {+ // Use a slightly longer timeout to ensure the input is fully rendered+ const timer = setTimeout(() => {+ inputRef.current.input.select();+ }, 150);+ return () => clearTimeout(timer);+ }+ }, [open]);++ const handleTitleConfirm = () => {+ if (title.trim() && title.trim() !== currentTitle) {+ onConfirm(title.trim(), emoji);+ }+ onOpenChange(false);+ };++ const handleBlur = () => {+ // Use setTimeout to check if we're interacting with emoji picker+ setTimeout(() => {+ // Don't close if emoji picker interaction is in progress+ if (isInteractingWithEmojiPicker.current) {+ return;+ }++ // Save title on blur if it changed+ if (title.trim() && title.trim() !== currentTitle) {+ onConfirm(title.trim(), emoji);+ }+ onOpenChange(false);+ }, 150);+ };++ const content = (+ <div className={styles.popoverContent}>+ <div className={styles.inputGroup}>+ <EmojiPicker+ allowDelete+ locale={locale}+ onChange={(newEmoji) => {+ setEmoji(newEmoji);+ setShowEmojiPicker(false);+ isInteractingWithEmojiPicker.current = false;+ // Update emoji immediately+ onConfirm(title, newEmoji);+ // Refocus input after emoji selection+ setTimeout(() => inputRef.current?.focus(), 100);+ }}+ onDelete={() => {+ setEmoji(undefined);+ setShowEmojiPicker(false);+ isInteractingWithEmojiPicker.current = false;+ // Update to remove emoji immediately+ onConfirm(title, undefined);+ // Refocus input after emoji deletion+ setTimeout(() => inputRef.current?.focus(), 100);+ }}+ onOpenChange={(isOpen) => {+ setShowEmojiPicker(isOpen);+ isInteractingWithEmojiPicker.current = isOpen;+ }}+ open={showEmojiPicker}+ size={32}+ style={{+ fontSize: 32,+ }}+ title={t('documentEditor.chooseIcon')}+ value={emoji}+ />+ <Input+ autoFocus+ className={styles.input}+ onBlur={handleBlur}+ onChange={(e) => setTitle(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ handleTitleConfirm();+ } else if (e.key === 'Escape') {+ onOpenChange(false);+ }+ }}+ placeholder={t('documentEditor.titlePlaceholder')}+ ref={inputRef}+ value={title}+ />+ </div>+ </div>+ );++ return (+ <Popover+ content={content}+ onOpenChange={handleOpenChange}+ open={open}+ placement="bottom"+ trigger={[]}+ >+ {children}+ </Popover>+ );+ },+);++export default RenamePopover;diff --git a/src/features/KnowledgeManager/DocumentExplorer/index.tsx b/src/features/KnowledgeManager/DocumentExplorer/index.tsxnew file mode 100644index 00000000000..c88cc8f562a--- /dev/null+++ b/src/features/KnowledgeManager/DocumentExplorer/index.tsx@@ -0,0 +1,318 @@+'use client';++import { ActionIcon, SearchBar, Text } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { PlusIcon } from 'lucide-react';+import { memo, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Center } from 'react-layout-kit';+import { Virtuoso } from 'react-virtuoso';++import { useFileStore } from '@/store/file';+import { DocumentSourceType, LobeDocument } from '@/types/document';++import DocumentEditor from './DocumentEditor';+import DocumentEditorPlaceholder from './DocumentEditorPlaceholder';+import DocumentListItem from './DocumentListItem';+import DocumentListSkeleton from './DocumentListSkeleton';++const useStyles = createStyles(({ css, token }) => ({+ container: css`+ display: flex;+ width: 100%;+ height: 100%;+ `,+ documentList: css`+ overflow-y: auto;+ flex: 1;+ padding-block: 4px;+ `,+ editorPanel: css`+ overflow: hidden;+ flex: 1;+ background: ${token.colorBgContainer};+ `,+ header: css`+ display: flex;+ gap: 8px;+ align-items: center;++ padding-block: ${token.paddingXXS}px;+ padding-inline: ${token.paddingXS}px;+ border-block-end: 1px solid ${token.colorBorderSecondary};++ background: ${token.colorBgContainer};+ `,+ listPanel: css`+ display: flex;+ flex-direction: column;++ width: 280px;+ min-width: 280px;+ border-inline-end: 1px solid ${token.colorBorderSecondary};++ background: ${token.colorBgContainer};+ `,+}));++interface DocumentExplorerProps {+ documentId?: string;+ knowledgeBaseId?: string;+}++const updateUrl = (docId: string | null) => {+ const newPath = docId ? `/knowledge/${docId}` : '/knowledge';+ window.history.replaceState({}, '', newPath);+};++/**+ * View, edit and create documents.+ */+const DocumentExplorer = memo<DocumentExplorerProps>(({ knowledgeBaseId, documentId }) => {+ const { t } = useTranslation('file');+ const { styles } = useStyles();++ const [selectedDocumentId, setSelectedDocumentId] = useState<string | null>(null);+ const [isCreatingNew, setIsCreatingNew] = useState(false);+ const [searchKeywords, setSearchKeywords] = useState<string>('');+ const [renamingDocumentId, setRenamingDocumentId] = useState<string | null>(null);++ const fetchDocuments = useFileStore((s) => s.fetchDocuments);+ const getOptimisticDocuments = useFileStore((s) => s.getOptimisticDocuments);+ const isDocumentListLoading = useFileStore((s) => s.isDocumentListLoading);+ const createDocument = useFileStore((s) => s.createDocument);+ const createOptimisticDocument = useFileStore((s) => s.createOptimisticDocument);+ const replaceTempDocumentWithReal = useFileStore((s) => s.replaceTempDocumentWithReal);+ const updateDocumentOptimistically = useFileStore((s) => s.updateDocumentOptimistically);+ // Subscribe to localDocumentMap and documents to trigger re-render when documents are updated+ useFileStore((s) => s.localDocumentMap);+ useFileStore((s) => s.documents);++ // Fetch documents on mount+ useEffect(() => {+ fetchDocuments();+ }, [fetchDocuments]);++ // If documentId is provided, automatically open that document+ useEffect(() => {+ if (documentId) {+ setSelectedDocumentId(documentId);+ setIsCreatingNew(false);+ }+ }, [documentId]);++ // Get optimistic documents (merged local + server)+ // Filter by knowledgeBaseId if provided+ // Since the API call already filters by knowledgeBaseId, we trust that data+ // But we also need to check local optimistic updates+ // Re-compute when localDocumentMap changes to ensure list updates when documents are edited+ const documents = getOptimisticDocuments();++ // Filter documents based on search keywords and sort by creation date (newest first)+ const filteredDocuments = useMemo(() => {+ let result = documents;++ // Filter by search keywords+ if (searchKeywords.trim()) {+ const lowerKeywords = searchKeywords.toLowerCase();+ result = documents.filter((document) => {+ const content = document.content?.toLowerCase() || '';+ const title = document.title?.toLowerCase() || '';+ return content.includes(lowerKeywords) || title.includes(lowerKeywords);+ });+ }++ // Sort by creation date (newest first)+ return result.sort((a, b) => {+ const dateA = a.createdAt ? new Date(a.createdAt).getTime() : 0;+ const dateB = b.createdAt ? new Date(b.createdAt).getTime() : 0;+ return dateB - dateA;+ });+ }, [documents, searchKeywords]);++ const handleDocumentSelect = (documentId: string) => {+ if (selectedDocumentId === documentId) {+ // Deselect if clicking the same document+ setSelectedDocumentId(null);+ updateUrl(null);+ } else {+ setSelectedDocumentId(documentId);+ updateUrl(documentId);+ }+ setIsCreatingNew(false);+ };++ const handleNewDocument = async () => {+ const untitledTitle = t('documentList.untitled');++ // Create optimistic document immediately for instant UX+ const tempDocumentId = createOptimisticDocument(untitledTitle);+ setSelectedDocumentId(tempDocumentId);+ setIsCreatingNew(true);++ try {+ // Create real document in background+ const newDoc = await createDocument({+ content: '',+ knowledgeBaseId,+ title: untitledTitle,+ });++ // Convert DocumentItem to EditorDocument+ const realDocument: LobeDocument = {+ 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',+ filename: newDoc.title || untitledTitle,+ id: newDoc.id,+ metadata: newDoc.metadata || {},+ source: 'document',+ sourceType: DocumentSourceType.EDITOR,+ title: newDoc.title || untitledTitle,+ totalCharCount: newDoc.content?.length || 0,+ totalLineCount: 0,+ updatedAt: newDoc.updatedAt ? new Date(newDoc.updatedAt) : new Date(),+ };++ // Replace optimistic document with real document (smooth UX, no flicker)+ replaceTempDocumentWithReal(tempDocumentId, realDocument);++ // Update selected document ID to real ID and update URL+ setSelectedDocumentId(newDoc.id);+ setIsCreatingNew(false);+ updateUrl(newDoc.id);+ } catch (error) {+ console.error('Failed to create document:', error);+ // On error, remove the optimistic document and deselect+ useFileStore.getState().removeTempDocument(tempDocumentId);+ setSelectedDocumentId(null);+ setIsCreatingNew(false);+ }+ };++ const handleDocumentIdChange = (newId: string) => {+ // When a temp document gets a real ID, update the selected document ID+ setSelectedDocumentId(newId);+ setIsCreatingNew(false);+ updateUrl(newId);+ };++ const handleRenameOpenChange = (documentId: string, open: boolean) => {+ setRenamingDocumentId(open ? documentId : null);+ };++ const handleRenameConfirm = async (documentId: string, title: string, emoji?: string) => {+ try {+ await updateDocumentOptimistically(documentId, {+ metadata: {+ emoji,+ },+ title,+ });+ } catch (error) {+ console.error('Failed to rename document:', error);+ } finally {+ setRenamingDocumentId(null);+ }+ };++ return (+ <div className={styles.container}>+ {/* Left Panel - Documents List */}+ <div className={styles.listPanel}>+ <div className={styles.header}>+ <SearchBar+ allowClear+ onChange={(e) => setSearchKeywords(e.target.value)}+ placeholder={t('searchDocumentPlaceholder')}+ style={{ flex: 1 }}+ value={searchKeywords}+ variant={'borderless'}+ />+ <ActionIcon+ icon={PlusIcon}+ onClick={handleNewDocument}+ title={t('header.newDocumentButton')}+ />+ </div>+ <div className={styles.documentList}>+ {isDocumentListLoading ? (+ <DocumentListSkeleton />+ ) : filteredDocuments.length === 0 ? (+ <div style={{ color: 'var(--lobe-text-secondary)', padding: 24, textAlign: 'center' }}>+ {searchKeywords.trim() ? t('documentList.noResults') : t('documentList.empty')}+ </div>+ ) : (+ <Virtuoso+ components={{+ Footer: () => (+ <Center style={{ paddingBlock: 16 }}>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('documentList.documentCount', { count: filteredDocuments.length })}+ </Text>+ </Center>+ ),+ }}+ data={filteredDocuments}+ itemContent={(_index, document) => {+ const isSelected = selectedDocumentId === document.id;+ const isRenaming = renamingDocumentId === document.id;+ return (+ <DocumentListItem+ document={document}+ isRenaming={isRenaming}+ isSelected={isSelected}+ key={document.id}+ onDelete={() => {+ if (selectedDocumentId === document.id) {+ setSelectedDocumentId(null);+ setIsCreatingNew(false);+ updateUrl(null);+ }+ }}+ onRenameConfirm={handleRenameConfirm}+ onRenameOpenChange={handleRenameOpenChange}+ onSelect={handleDocumentSelect}+ untitledText={t('documentList.untitled')}+ />+ );+ }}+ style={{ height: '100%' }}+ />+ )}+ </div>+ </div>++ {/* Right Panel - Editor */}+ <div className={styles.editorPanel}>+ {selectedDocumentId || isCreatingNew ? (+ <DocumentEditor+ documentId={selectedDocumentId || undefined}+ knowledgeBaseId={knowledgeBaseId}+ onDelete={() => {+ setSelectedDocumentId(null);+ setIsCreatingNew(false);+ updateUrl(null);+ }}+ onDocumentIdChange={handleDocumentIdChange}+ />+ ) : (+ <DocumentEditorPlaceholder+ knowledgeBaseId={knowledgeBaseId}+ onCreateNewNote={handleNewDocument}+ onNoteCreated={(documentId) => {+ setSelectedDocumentId(documentId);+ setIsCreatingNew(false);+ }}+ />+ )}+ </div>+ </div>+ );+});++export default DocumentExplorer;diff --git a/src/features/FileManager/FileList/EmptyStatus.tsx b/src/features/KnowledgeManager/FileExplorer/EmptyStatus.tsxsimilarity index 100%rename from src/features/FileManager/FileList/EmptyStatus.tsxrename to src/features/KnowledgeManager/FileExplorer/EmptyStatus.tsxdiff --git a/src/features/FileManager/FileList/FileListItem/ChunkTag.tsx b/src/features/KnowledgeManager/FileExplorer/FileListItem/ChunkTag.tsxsimilarity index 100%rename from src/features/FileManager/FileList/FileListItem/ChunkTag.tsxrename to src/features/KnowledgeManager/FileExplorer/FileListItem/ChunkTag.tsxdiff --git a/src/features/FileManager/FileList/FileListItem/DropdownMenu.tsx b/src/features/KnowledgeManager/FileExplorer/FileListItem/DropdownMenu.tsxsimilarity index 100%rename from src/features/FileManager/FileList/FileListItem/DropdownMenu.tsxrename to src/features/KnowledgeManager/FileExplorer/FileListItem/DropdownMenu.tsxdiff --git a/src/features/FileManager/FileList/FileListItem/index.tsx b/src/features/KnowledgeManager/FileExplorer/FileListItem/index.tsxsimilarity index 79%rename from src/features/FileManager/FileList/FileListItem/index.tsxrename to src/features/KnowledgeManager/FileExplorer/FileListItem/index.tsxindex a6dec5fa556..b82e8853809 100644--- a/src/features/FileManager/FileList/FileListItem/index.tsx+++ b/src/features/KnowledgeManager/FileExplorer/FileListItem/index.tsx@@ -1,12 +1,12 @@-import { Button, Tooltip } from '@lobehub/ui';+import { Button, Icon, Tooltip } from '@lobehub/ui';import { Checkbox } from 'antd';import { createStyles } from 'antd-style';import dayjs from 'dayjs';import relativeTime from 'dayjs/plugin/relativeTime';import { isNull } from 'lodash-es';-import { FileBoxIcon } from 'lucide-react';+import { FileBoxIcon, FileText } from 'lucide-react';import { rgba } from 'polished';-import { memo } from 'react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { Center, Flexbox } from 'react-layout-kit';import { useSearchParams } from 'react-router-dom';@@ -22,6 +22,15 @@ import DropdownMenu from './DropdownMenu';dayjs.extend(relativeTime);+// Helper to extract title from markdown content+const extractTitle = (content: string): string | null => {+ if (!content) return null;++ // Find first markdown header (# title)+ const match = content.match(/^#\s+(.+)$/m);+ return match ? match[1].trim() : null;+};+export const FILE_DATE_WIDTH = 160;export const FILE_SIZE_WIDTH = 140;@@ -33,9 +42,8 @@ const useStyles = createStyles(({ css, token, cx, isDarkMode }) => {checkbox: hover,container: css`cursor: pointer;- margin-inline: 24px;+ margin-inline: 16px;border-block-end: 1px solid ${isDarkMode ? token.colorSplit : rgba(token.colorSplit, 0.06)};- border-radius: ${token.borderRadius}px;&:hover {background: ${token.colorFillTertiary};@@ -101,8 +109,11 @@ const FileRenderItem = memo<FileRenderItemProps>(onSelectedChange,knowledgeBaseId,index,+ content,+ metadata,+ sourceType,}) => {- const { t } = useTranslation('components');+ const { t } = useTranslation(['components', 'file']);const { styles, cx } = useStyles();const [, setSearchParams] = useSearchParams();const [isCreatingFileParseTask, parseFiles] = useFileStore((s) => [@@ -111,6 +122,18 @@ const FileRenderItem = memo<FileRenderItemProps>(]);const isSupportedForChunking = !isChunkingUnsupported(fileType);+ const isNote = sourceType === 'document' || fileType === 'custom/document';++ // Extract title and emoji for notes+ const displayTitle = useMemo(() => {+ if (isNote && content) {+ const extractedTitle = extractTitle(content);+ return extractedTitle || name || t('file:documentList.untitled');+ }+ return name;+ }, [isNote, content, name, t]);++ const emoji = isNote ? metadata?.emoji : null;const displayTime =dayjs().diff(dayjs(createdAt), 'd') < 7@@ -121,7 +144,7 @@ const FileRenderItem = memo<FileRenderItemProps>(<Flexboxalign={'center'}className={cx(styles.container, selected && styles.selected)}- height={64}+ height={48}horizontalpaddingInline={8}>@@ -158,8 +181,24 @@ const FileRenderItem = memo<FileRenderItemProps>(style={{ borderRadius: '50%' }}/></Center>- <FileIcon fileName={name} fileType={fileType} />- <span className={styles.name}>{name}</span>+ <Flexbox+ align={'center'}+ justify={'center'}+ style={{ fontSize: 24, marginInline: 8, width: 24 }}+ >+ {isNote ? (+ emoji ? (+ <span style={{ fontSize: 24 }}>{emoji}</span>+ ) : (+ <Center height={24} width={24}>+ <Icon icon={FileText} size={24} />+ </Center>+ )+ ) : (+ <FileIcon fileName={name} fileType={fileType} size={24} />+ )}+ </Flexbox>+ <span className={styles.name}>{displayTitle}</span></Flexbox><Flexboxalign={'center'}diff --git a/src/features/FileManager/FileList/FileSkeleton.tsx b/src/features/KnowledgeManager/FileExplorer/FileSkeleton.tsxsimilarity index 100%rename from src/features/FileManager/FileList/FileSkeleton.tsxrename to src/features/KnowledgeManager/FileExplorer/FileSkeleton.tsxdiff --git a/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/DefaultFileItem.tsx b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/DefaultFileItem.tsxnew file mode 100644index 00000000000..b6f1642002a--- /dev/null+++ b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/DefaultFileItem.tsx@@ -0,0 +1,149 @@+import { Button, Tooltip } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { isNull } from 'lodash-es';+import { FileBoxIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';++import FileIcon from '@/components/FileIcon';+import { fileManagerSelectors, useFileStore } from '@/store/file';+import { AsyncTaskStatus, IAsyncTaskError } from '@/types/asyncTask';+import { formatSize } from '@/utils/format';+import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';++import ChunksBadge from '../FileListItem/ChunkTag';++const useStyles = createStyles(({ css, token }) => ({+ floatingChunkBadge: css`+ position: absolute;+ z-index: 3;+ inset-block-end: 8px;+ inset-inline-end: 8px;++ border-radius: ${token.borderRadius}px;++ opacity: 0;+ background: ${token.colorBgContainer};+ box-shadow: ${token.boxShadow};++ transition: opacity ${token.motionDurationMid};+ `,+ name: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;++ margin-block-end: 12px;++ font-weight: ${token.fontWeightStrong};+ color: ${token.colorText};+ word-break: break-word;+ `,+}));++interface DefaultFileItemProps {+ chunkCount?: number | null;+ chunkingError?: IAsyncTaskError | null;+ chunkingStatus?: AsyncTaskStatus | null;+ embeddingError?: IAsyncTaskError | null;+ embeddingStatus?: AsyncTaskStatus | null;+ fileType?: string;+ finishEmbedding?: boolean;+ id: string;+ name: string;+ size: number;+}++const DefaultFileItem = memo<DefaultFileItemProps>(+ ({+ chunkCount,+ chunkingError,+ chunkingStatus,+ embeddingError,+ embeddingStatus,+ fileType,+ finishEmbedding,+ id,+ name,+ size,+ }) => {+ const { t } = useTranslation('components');+ const { styles, cx } = useStyles();+ const [isCreatingFileParseTask, parseFiles] = useFileStore((s) => [+ fileManagerSelectors.isCreatingFileParseTask(id)(s),+ s.parseFilesToChunks,+ ]);++ const isSupportedForChunking = !isChunkingUnsupported(fileType || '');++ return (+ <>+ <Flexbox+ align={'center'}+ gap={12}+ justify={'center'}+ paddingBlock={24}+ paddingInline={12}+ style={{ minHeight: 180 }}+ >+ <FileIcon fileName={name} fileType={fileType} size={64} />+ <div className={styles.name} style={{ textAlign: 'center' }}>+ {name}+ </div>+ <div+ style={{+ color: 'var(--lobe-chat-text-tertiary)',+ fontSize: 12,+ textAlign: 'center',+ }}+ >+ {formatSize(size)}+ </div>+ </Flexbox>+ {/* Floating chunk badge or action button */}+ {!isNull(chunkingStatus) && chunkingStatus ? (+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => e.stopPropagation()}+ >+ <ChunksBadge+ chunkCount={chunkCount}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus}+ finishEmbedding={finishEmbedding}+ id={id}+ />+ </div>+ ) : (+ isSupportedForChunking && (+ <Tooltip title={t('FileManager.actions.chunkingTooltip')}>+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => {+ e.stopPropagation();+ if (!isCreatingFileParseTask) {+ parseFiles([id]);+ }+ }}+ style={{ cursor: 'pointer' }}+ >+ <Button+ icon={FileBoxIcon}+ loading={isCreatingFileParseTask}+ size={'small'}+ type={'text'}+ />+ </div>+ </Tooltip>+ )+ )}+ </>+ );+ },+);++export default DefaultFileItem;diff --git a/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/ImageFileItem.tsx b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/ImageFileItem.tsxnew file mode 100644index 00000000000..e900eee0dec--- /dev/null+++ b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/ImageFileItem.tsx@@ -0,0 +1,245 @@+import { Button, Tooltip } from '@lobehub/ui';+import { Image } from 'antd';+import { createStyles } from 'antd-style';+import { isNull } from 'lodash-es';+import { FileBoxIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';++import FileIcon from '@/components/FileIcon';+import { fileManagerSelectors, useFileStore } from '@/store/file';+import { AsyncTaskStatus, IAsyncTaskError } from '@/types/asyncTask';+import { formatSize } from '@/utils/format';+import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';++import ChunksBadge from '../FileListItem/ChunkTag';++const useStyles = createStyles(({ css, token }) => ({+ floatingChunkBadge: css`+ position: absolute;+ z-index: 3;+ inset-block-end: 8px;+ inset-inline-end: 8px;++ border-radius: ${token.borderRadius}px;++ opacity: 0;+ background: ${token.colorBgContainer};+ box-shadow: ${token.boxShadow};++ transition: opacity ${token.motionDurationMid};+ `,+ hoverOverlay: css`+ position: absolute;+ z-index: 1;+ inset: 0;++ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;++ padding: 16px;++ opacity: 0;+ background: ${token.colorBgMask};++ transition: opacity ${token.motionDurationMid};++ &:hover {+ opacity: 1;+ }+ `,+ imagePlaceholder: css`+ display: flex;+ align-items: center;+ justify-content: center;+ background: ${token.colorFillQuaternary};+ `,+ imageWrapper: css`+ position: relative;+ width: 100%;+ background: ${token.colorFillQuaternary};++ img {+ display: block;+ height: auto;+ }+ `,+ name: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;++ margin-block-end: 12px;++ font-weight: ${token.fontWeightStrong};+ color: ${token.colorText};+ word-break: break-word;+ `,+ overlaySize: css`+ font-size: 12px;+ color: ${token.colorTextLightSolid};+ opacity: 0.9;+ `,+ overlayTitle: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 3;++ max-width: 100%;+ margin-block-end: 8px;++ font-size: 14px;+ font-weight: ${token.fontWeightStrong};+ color: ${token.colorTextLightSolid};+ text-align: center;+ word-break: break-word;+ `,+}));++interface ImageFileItemProps {+ chunkCount?: number | null;+ chunkingError?: IAsyncTaskError | null;+ chunkingStatus?: AsyncTaskStatus | null;+ embeddingError?: IAsyncTaskError | null;+ embeddingStatus?: AsyncTaskStatus | null;+ fileType?: string;+ finishEmbedding?: boolean;+ id: string;+ isInView: boolean;+ name: string;+ size: number;+ url?: string;+}++const ImageFileItem = memo<ImageFileItemProps>(+ ({+ chunkCount,+ chunkingError,+ chunkingStatus,+ embeddingError,+ embeddingStatus,+ fileType,+ finishEmbedding,+ id,+ isInView,+ name,+ size,+ url,+ }) => {+ const { t } = useTranslation('components');+ const { styles, cx } = useStyles();+ const [imageLoaded, setImageLoaded] = useState(false);+ const [isCreatingFileParseTask, parseFiles] = useFileStore((s) => [+ fileManagerSelectors.isCreatingFileParseTask(id)(s),+ s.parseFilesToChunks,+ ]);++ const isSupportedForChunking = !isChunkingUnsupported(fileType || '');++ return (+ <>+ <div className={styles.imageWrapper}>+ {!imageLoaded && (+ <div className={styles.imagePlaceholder}>+ <Flexbox+ align={'center'}+ gap={12}+ justify={'center'}+ paddingBlock={24}+ paddingInline={12}+ >+ <FileIcon fileName={name} fileType={fileType} size={48} />+ <div className={styles.name} style={{ textAlign: 'center' }}>+ {name}+ </div>+ <div+ style={{+ color: 'var(--lobe-chat-text-tertiary)',+ fontSize: 12,+ textAlign: 'center',+ }}+ >+ {formatSize(size)}+ </div>+ </Flexbox>+ </div>+ )}+ {isInView && url && (+ <Image+ alt={name}+ loading="lazy"+ onError={() => setImageLoaded(false)}+ onLoad={() => setImageLoaded(true)}+ preview={{+ src: url,+ }}+ src={url}+ style={{+ display: 'block',+ height: 'auto',+ opacity: imageLoaded ? 1 : 0,+ transition: 'opacity 0.3s',+ width: '100%',+ }}+ wrapperStyle={{+ display: 'block',+ width: '100%',+ }}+ />+ )}+ {/* Hover overlay */}+ <div className={styles.hoverOverlay}>+ <div className={styles.overlayTitle}>{name}</div>+ <div className={styles.overlaySize}>{formatSize(size)}</div>+ </div>+ </div>+ {/* Floating chunk badge or action button */}+ {!isNull(chunkingStatus) && chunkingStatus ? (+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => e.stopPropagation()}+ >+ <ChunksBadge+ chunkCount={chunkCount}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus}+ finishEmbedding={finishEmbedding}+ id={id}+ />+ </div>+ ) : (+ isSupportedForChunking && (+ <Tooltip title={t('FileManager.actions.chunkingTooltip')}>+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => {+ e.stopPropagation();+ if (!isCreatingFileParseTask) {+ parseFiles([id]);+ }+ }}+ style={{ cursor: 'pointer' }}+ >+ <Button+ icon={FileBoxIcon}+ loading={isCreatingFileParseTask}+ size={'small'}+ type={'text'}+ />+ </div>+ </Tooltip>+ )+ )}+ </>+ );+ },+);++export default ImageFileItem;diff --git a/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/MarkdownFileItem.tsx b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/MarkdownFileItem.tsxnew file mode 100644index 00000000000..5b49cffa9a6--- /dev/null+++ b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/MarkdownFileItem.tsx@@ -0,0 +1,232 @@+import { Button, Tooltip } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { isNull } from 'lodash-es';+import { FileBoxIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import FileIcon from '@/components/FileIcon';+import { fileManagerSelectors, useFileStore } from '@/store/file';+import { AsyncTaskStatus, IAsyncTaskError } from '@/types/asyncTask';+import { formatSize } from '@/utils/format';+import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';++import ChunksBadge from '../FileListItem/ChunkTag';++const useStyles = createStyles(({ css, token }) => ({+ floatingChunkBadge: css`+ position: absolute;+ z-index: 3;+ inset-block-end: 8px;+ inset-inline-end: 8px;++ border-radius: ${token.borderRadius}px;++ opacity: 0;+ background: ${token.colorBgContainer};+ box-shadow: ${token.boxShadow};++ transition: opacity ${token.motionDurationMid};+ `,+ hoverOverlay: css`+ position: absolute;+ z-index: 1;+ inset: 0;++ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;++ padding: 16px;+ border-radius: ${token.borderRadiusLG}px;++ opacity: 0;+ background: ${token.colorBgMask};++ transition: opacity ${token.motionDurationMid};++ &:hover {+ opacity: 1;+ }+ `,+ iconWrapper: css`+ display: flex;+ align-items: center;+ justify-content: center;++ height: 120px;+ margin-block-end: 12px;+ border-radius: ${token.borderRadius}px;++ background: ${token.colorFillQuaternary};+ `,+ markdownLoading: css`+ display: flex;+ align-items: center;+ justify-content: center;++ min-height: 120px;+ border-radius: ${token.borderRadiusLG}px;++ font-size: 12px;+ color: ${token.colorTextTertiary};++ background: ${token.colorFillQuaternary};+ `,+ markdownPreview: css`+ position: relative;++ overflow: hidden;++ width: 100%;+ min-height: 120px;+ max-height: 300px;+ padding: 16px;+ border-radius: ${token.borderRadiusLG}px;++ font-size: 13px;+ line-height: 1.6;+ color: ${token.colorTextSecondary};+ word-wrap: break-word;+ white-space: pre-wrap;++ background: ${token.colorFillQuaternary};++ &::after {+ pointer-events: none;+ content: '';++ position: absolute;+ inset-block-end: 0;+ inset-inline: 0;++ height: 60px;++ background: linear-gradient(to bottom, transparent, ${token.colorFillQuaternary});+ }+ `,+ overlaySize: css`+ font-size: 12px;+ color: ${token.colorTextLightSolid};+ opacity: 0.9;+ `,+ overlayTitle: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 3;++ max-width: 100%;+ margin-block-end: 8px;++ font-size: 14px;+ font-weight: ${token.fontWeightStrong};+ color: ${token.colorTextLightSolid};+ text-align: center;+ word-break: break-word;+ `,+}));++interface MarkdownFileItemProps {+ chunkCount?: number | null;+ chunkingError?: IAsyncTaskError | null;+ chunkingStatus?: AsyncTaskStatus | null;+ embeddingError?: IAsyncTaskError | null;+ embeddingStatus?: AsyncTaskStatus | null;+ fileType?: string;+ finishEmbedding?: boolean;+ id: string;+ isLoadingMarkdown: boolean;+ markdownContent: string;+ name: string;+ size: number;+}++const MarkdownFileItem = memo<MarkdownFileItemProps>(+ ({+ chunkCount,+ chunkingError,+ chunkingStatus,+ embeddingError,+ embeddingStatus,+ fileType,+ finishEmbedding,+ id,+ isLoadingMarkdown,+ markdownContent,+ name,+ size,+ }) => {+ const { t } = useTranslation('components');+ const { styles, cx } = useStyles();+ const [isCreatingFileParseTask, parseFiles] = useFileStore((s) => [+ fileManagerSelectors.isCreatingFileParseTask(id)(s),+ s.parseFilesToChunks,+ ]);++ const isSupportedForChunking = !isChunkingUnsupported(fileType || '');++ return (+ <>+ <div style={{ position: 'relative' }}>+ {isLoadingMarkdown ? (+ <div className={styles.markdownLoading}>Loading preview...</div>+ ) : markdownContent ? (+ <div className={styles.markdownPreview}>{markdownContent}</div>+ ) : (+ <div className={styles.iconWrapper}>+ <FileIcon fileName={name} fileType={fileType} size={64} />+ </div>+ )}+ {/* Hover overlay */}+ <div className={styles.hoverOverlay}>+ <div className={styles.overlayTitle}>{name}</div>+ <div className={styles.overlaySize}>{formatSize(size)}</div>+ </div>+ </div>+ {/* Floating chunk badge or action button */}+ {!isNull(chunkingStatus) && chunkingStatus ? (+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => e.stopPropagation()}+ >+ <ChunksBadge+ chunkCount={chunkCount}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus}+ finishEmbedding={finishEmbedding}+ id={id}+ />+ </div>+ ) : (+ isSupportedForChunking && (+ <Tooltip title={t('FileManager.actions.chunkingTooltip')}>+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => {+ e.stopPropagation();+ if (!isCreatingFileParseTask) {+ parseFiles([id]);+ }+ }}+ style={{ cursor: 'pointer' }}+ >+ <Button+ icon={FileBoxIcon}+ loading={isCreatingFileParseTask}+ size={'small'}+ type={'text'}+ />+ </div>+ </Tooltip>+ )+ )}+ </>+ );+ },+);++export default MarkdownFileItem;diff --git a/src/features/FileManager/FileList/MasonryFileItem/MasonryItemWrapper.tsx b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/MasonryItemWrapper.tsxsimilarity index 100%rename from src/features/FileManager/FileList/MasonryFileItem/MasonryItemWrapper.tsxrename to src/features/KnowledgeManager/FileExplorer/MasonryFileItem/MasonryItemWrapper.tsxdiff --git a/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/NoteFileItem.tsx b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/NoteFileItem.tsxnew file mode 100644index 00000000000..6bc8ac22c54--- /dev/null+++ b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/NoteFileItem.tsx@@ -0,0 +1,230 @@+import { Button, Tooltip } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { isNull } from 'lodash-es';+import { FileBoxIcon } from 'lucide-react';+import markdownToTxt from 'markdown-to-txt';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import FileIcon from '@/components/FileIcon';+import { fileManagerSelectors, useFileStore } from '@/store/file';+import { AsyncTaskStatus, IAsyncTaskError } from '@/types/asyncTask';+import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';++import ChunksBadge from '../FileListItem/ChunkTag';++const useStyles = createStyles(({ css, token }) => ({+ floatingChunkBadge: css`+ position: absolute;+ z-index: 3;+ inset-block-end: 8px;+ inset-inline-end: 8px;++ border-radius: ${token.borderRadius}px;++ opacity: 0;+ background: ${token.colorBgContainer};+ box-shadow: ${token.boxShadow};++ transition: opacity ${token.motionDurationMid};+ `,+ iconWrapper: css`+ display: flex;+ align-items: center;+ justify-content: center;++ height: 120px;+ margin-block-end: 12px;+ border-radius: ${token.borderRadius}px;++ background: ${token.colorFillQuaternary};+ `,+ markdownLoading: css`+ display: flex;+ align-items: center;+ justify-content: center;++ min-height: 120px;+ border-radius: ${token.borderRadiusLG}px;++ font-size: 12px;+ color: ${token.colorTextTertiary};++ background: ${token.colorFillQuaternary};+ `,+ noteContent: css`+ display: flex;+ flex-direction: column;+ gap: 12px;++ width: 100%;+ min-height: 120px;+ padding: 16px;+ border-radius: ${token.borderRadiusLG}px;++ background: ${token.colorFillQuaternary};+ `,+ notePreview: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 6;++ font-size: 13px;+ line-height: 1.6;+ color: ${token.colorTextSecondary};+ `,+ noteTitle: css`+ display: flex;+ gap: 8px;+ align-items: center;++ font-size: 16px;+ font-weight: ${token.fontWeightStrong};+ line-height: 1.4;+ color: ${token.colorText};+ `,+}));++// Helper to extract title from markdown content+const extractTitle = (content: string): string | null => {+ if (!content) return null;++ // Find first markdown header (# title)+ const match = content.match(/^#\s+(.+)$/m);+ return match ? match[1].trim() : null;+};++// Helper to extract preview text from note content+const getPreviewText = (content: string): string => {+ if (!content) return '';++ // Convert markdown to plain text+ let plainText = markdownToTxt(content);++ // Remove the title line if it exists+ const title = extractTitle(content);+ if (title) {+ plainText = plainText.replace(title, '').trim();+ }++ // Limit to first 400 characters for preview+ return plainText.slice(0, 400);+};++interface NoteFileItemProps {+ chunkCount?: number | null;+ chunkingError?: IAsyncTaskError | null;+ chunkingStatus?: AsyncTaskStatus | null;+ embeddingError?: IAsyncTaskError | null;+ embeddingStatus?: AsyncTaskStatus | null;+ fileType?: string;+ finishEmbedding?: boolean;+ id: string;+ isLoadingMarkdown: boolean;+ markdownContent: string;+ metadata?: Record<string, any> | null;+ name: string;+}++const NoteFileItem = memo<NoteFileItemProps>(+ ({+ chunkCount,+ chunkingError,+ chunkingStatus,+ embeddingError,+ embeddingStatus,+ fileType,+ finishEmbedding,+ id,+ isLoadingMarkdown,+ markdownContent,+ name,+ metadata,+ }) => {+ const { t } = useTranslation(['components', 'file']);+ const { styles, cx } = useStyles();+ const [isCreatingFileParseTask, parseFiles] = useFileStore((s) => [+ fileManagerSelectors.isCreatingFileParseTask(id)(s),+ s.parseFilesToChunks,+ ]);++ const isSupportedForChunking = !isChunkingUnsupported(fileType || '');++ const extractedTitle = markdownContent ? extractTitle(markdownContent) : null;+ const displayTitle = extractedTitle || name || t('file:documentList.untitled');+ const emoji = metadata?.emoji;+ const previewText = markdownContent ? getPreviewText(markdownContent) : '';++ return (+ <>+ <div style={{ position: 'relative' }}>+ {isLoadingMarkdown ? (+ <div className={styles.markdownLoading}>Loading preview...</div>+ ) : markdownContent ? (+ <div className={styles.noteContent}>+ <div className={styles.noteTitle}>+ {emoji && <span style={{ fontSize: 20 }}>{emoji}</span>}+ <span>{displayTitle}</span>+ </div>+ {previewText ? (+ <div className={styles.notePreview}>{previewText}</div>+ ) : (+ <div className={styles.notePreview}>+ <span style={{ color: 'var(--lobe-text-tertiary)', fontStyle: 'italic' }}>+ No content+ </span>+ </div>+ )}+ </div>+ ) : (+ <div className={styles.iconWrapper}>+ <FileIcon fileName={name} fileType={fileType} size={64} />+ </div>+ )}+ </div>+ {/* Floating chunk badge or action button */}+ {!isNull(chunkingStatus) && chunkingStatus ? (+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => e.stopPropagation()}+ >+ <ChunksBadge+ chunkCount={chunkCount}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus}+ finishEmbedding={finishEmbedding}+ id={id}+ />+ </div>+ ) : (+ isSupportedForChunking && (+ <Tooltip title={t('FileManager.actions.chunkingTooltip')}>+ <div+ className={cx('floatingChunkBadge', styles.floatingChunkBadge)}+ onClick={(e) => {+ e.stopPropagation();+ if (!isCreatingFileParseTask) {+ parseFiles([id]);+ }+ }}+ style={{ cursor: 'pointer' }}+ >+ <Button+ icon={FileBoxIcon}+ loading={isCreatingFileParseTask}+ size={'small'}+ type={'text'}+ />+ </div>+ </Tooltip>+ )+ )}+ </>+ );+ },+);++export default NoteFileItem;diff --git a/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/index.tsx b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/index.tsxnew file mode 100644index 00000000000..2625f744a90--- /dev/null+++ b/src/features/KnowledgeManager/FileExplorer/MasonryFileItem/index.tsx@@ -0,0 +1,398 @@+import { Checkbox } from 'antd';+import { createStyles } from 'antd-style';+import React, { memo, useEffect, useRef, useState } from 'react';++import { documentService } from '@/services/document';+import { FileListItem } from '@/types/files';++import NoteEditorModal from '../../DocumentExplorer/NoteEditorModal';+import DropdownMenu from '../FileListItem/DropdownMenu';+import DefaultFileItem from './DefaultFileItem';+import ImageFileItem from './ImageFileItem';+import MarkdownFileItem from './MarkdownFileItem';+import NoteFileItem from './NoteFileItem';++// Image file types+const IMAGE_TYPES = new Set([+ 'image/png',+ 'image/jpeg',+ 'image/jpg',+ 'image/gif',+ 'image/webp',+ 'image/svg+xml',+]);++// Markdown file types+const MARKDOWN_TYPES = new Set(['text/markdown', 'text/x-markdown']);++// Custom note file type+const CUSTOM_NOTE_TYPE = 'custom/document';++// Helper to check if filename ends with .md or is a custom note+const isMarkdownFile = (name: string, fileType?: string) => {+ return (+ name.toLowerCase().endsWith('.md') ||+ name.toLowerCase().endsWith('.markdown') ||+ (fileType && MARKDOWN_TYPES.has(fileType))+ );+};++// Helper to check if it's a custom note that should be rendered+const isCustomNote = (fileType?: string) => {+ return fileType === CUSTOM_NOTE_TYPE;+};++// Helper function to extract text from editor's JSON format for preview+const extractTextFromEditorJSON = (editorData: any): string => {+ if (!editorData || !editorData.root || !editorData.root.children) {+ return '';+ }++ const extractFromNode = (node: any): string => {+ if (!node) return '';++ // If node has text, return it+ if (node.text) return node.text;++ // If node has children, recursively extract text+ if (node.children && Array.isArray(node.children)) {+ return node.children.map((child: any) => extractFromNode(child)).join('');+ }++ return '';+ };++ return editorData.root.children.map((node: any) => extractFromNode(node)).join('\n');+};++const useStyles = createStyles(({ css, token }) => ({+ actions: css`+ opacity: 0;+ transition: opacity ${token.motionDurationMid};+ `,+ card: css`+ cursor: pointer;++ position: relative;++ overflow: hidden;++ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;++ background: ${token.colorBgContainer};++ transition: all ${token.motionDurationMid};++ &:hover {+ border-color: ${token.colorPrimary};+ box-shadow: ${token.boxShadowTertiary};++ .actions {+ opacity: 1;+ }++ .checkbox {+ opacity: 1;+ }++ .dropdown {+ opacity: 1;+ }++ .floatingChunkBadge {+ opacity: 1;+ }+ }+ `,+ checkbox: css`+ position: absolute;+ z-index: 2;+ inset-block-start: 8px;+ inset-inline-start: 8px;++ opacity: 0;++ transition: opacity ${token.motionDurationMid};+ `,+ content: css`+ position: relative;+ `,+ contentWithPadding: css`+ padding: 12px;+ `,+ dropdown: css`+ position: absolute;+ z-index: 2;+ inset-block-start: 8px;+ inset-inline-end: 8px;++ opacity: 0;++ transition: opacity ${token.motionDurationMid};+ `,+ selected: css`+ border-color: ${token.colorPrimary};+ background: ${token.colorPrimaryBg};++ .checkbox {+ opacity: 1;+ }+ `,+}));++interface MasonryFileItemProps extends FileListItem {+ knowledgeBaseId?: string;+ onOpen: (id: string) => void;+ onSelectedChange: (id: string, selected: boolean) => void;+ selected?: boolean;+}++const MasonryFileItem = memo<MasonryFileItemProps>(+ ({+ chunkingError,+ editorData,+ embeddingError,+ embeddingStatus,+ finishEmbedding,+ chunkCount,+ url,+ name,+ fileType,+ id,+ selected,+ chunkingStatus,+ onSelectedChange,+ knowledgeBaseId,+ size,+ onOpen,+ metadata,+ }) => {+ const { styles, cx } = useStyles();+ const [markdownContent, setMarkdownContent] = useState<string>('');+ const [isLoadingMarkdown, setIsLoadingMarkdown] = useState(false);+ const [isNoteModalOpen, setIsNoteModalOpen] = useState(false);++ const isImage = fileType && IMAGE_TYPES.has(fileType);+ const isMarkdown = isMarkdownFile(name, fileType);+ const isNote = isCustomNote(fileType);++ // Debug: Log editorData for notes+ useEffect(() => {+ if (isNote) {+ console.log('[MasonryFileItem] Note item:', {+ editorDataPreview: editorData ? JSON.stringify(editorData).slice(0, 100) : null,+ editorDataType: typeof editorData,+ hasEditorData: !!editorData,+ id,+ name,+ });+ }+ }, [isNote, id, name, editorData]);++ const cardRef = useRef<HTMLDivElement>(null);+ const [isInView, setIsInView] = useState(false);++ // Use Intersection Observer to detect when card enters viewport+ useEffect(() => {+ if (!cardRef.current) return;++ const observer = new IntersectionObserver(+ (entries) => {+ entries.forEach((entry) => {+ if (entry.isIntersecting && !isInView) {+ setIsInView(true);+ }+ });+ },+ {+ rootMargin: '200px', // Increased margin to load content earlier+ threshold: 0.01, // Lower threshold for earlier triggering+ },+ );++ observer.observe(cardRef.current);++ return () => {+ observer.disconnect();+ };+ }, [isInView]);++ // Fetch markdown content only when in viewport+ useEffect(() => {+ if ((isMarkdown || isNote) && isInView && !markdownContent) {+ setIsLoadingMarkdown(true);++ const fetchContent = async () => {+ try {+ let text: string;++ if (isNote) {+ // For custom notes, fetch from document service+ const document = await documentService.getDocumentById(id);+ const content = document?.content || '';++ // Try to parse as JSON (editor's native format) and convert to markdown for preview+ try {+ const editorData = JSON.parse(content);+ // Since we can't easily convert JSON to markdown here without an editor instance,+ // we'll extract plain text from the JSON structure for preview+ text = extractTextFromEditorJSON(editorData);+ } catch {+ // If it's not JSON, use it as-is (might be old markdown format)+ text = content;+ }+ } else if (url) {+ // For regular markdown files, fetch from URL+ const res = await fetch(url);+ text = await res.text();+ } else {+ text = '';+ }++ // For custom notes, take more content for better preview; for regular markdown, take first 500 chars+ const preview = isNote ? text.slice(0, 1000) : text.slice(0, 500);+ setMarkdownContent(preview);+ } catch (error) {+ console.error('Failed to fetch markdown content:', error);+ setMarkdownContent('');+ } finally {+ setIsLoadingMarkdown(false);+ }+ };++ fetchContent();+ }+ }, [isMarkdown, isNote, url, isInView, markdownContent, id]);++ return (+ <div className={cx(styles.card, selected && styles.selected)} ref={cardRef}>+ <div+ className={cx('checkbox', styles.checkbox)}+ onClick={(e) => {+ e.stopPropagation();+ onSelectedChange(id, !selected);+ }}+ >+ <Checkbox checked={selected} />+ </div>++ <div className={cx('dropdown', styles.dropdown)} onClick={(e) => e.stopPropagation()}>+ <DropdownMenu filename={name} id={id} knowledgeBaseId={knowledgeBaseId} url={url} />+ </div>++ <div+ className={cx(+ styles.content,+ !isImage && !isMarkdown && !isNote && styles.contentWithPadding,+ )}+ onClick={() => {+ if (isNote) {+ console.log('[MasonryFileItem] Opening note modal with:', {+ editorDataType: typeof editorData,+ hasEditorData: !!editorData,+ id,+ name,+ });+ setIsNoteModalOpen(true);+ } else {+ onOpen(id);+ }+ }}+ >+ {(() => {+ switch (true) {+ case isImage && !!url: {+ return (+ <ImageFileItem+ chunkCount={chunkCount ?? undefined}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus ?? undefined}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus ?? undefined}+ fileType={fileType}+ finishEmbedding={finishEmbedding}+ id={id}+ isInView={isInView}+ name={name}+ size={size}+ url={url}+ />+ );+ }+ case isNote: {+ return (+ <NoteFileItem+ chunkCount={chunkCount ?? undefined}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus ?? undefined}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus ?? undefined}+ fileType={fileType}+ finishEmbedding={finishEmbedding}+ id={id}+ isLoadingMarkdown={isLoadingMarkdown}+ markdownContent={markdownContent}+ metadata={metadata}+ name={name}+ />+ );+ }+ case isMarkdown: {+ return (+ <MarkdownFileItem+ chunkCount={chunkCount ?? undefined}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus ?? undefined}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus ?? undefined}+ fileType={fileType}+ finishEmbedding={finishEmbedding}+ id={id}+ isLoadingMarkdown={isLoadingMarkdown}+ markdownContent={markdownContent}+ name={name}+ size={size}+ />+ );+ }+ default: {+ return (+ <DefaultFileItem+ chunkCount={chunkCount ?? undefined}+ chunkingError={chunkingError}+ chunkingStatus={chunkingStatus ?? undefined}+ embeddingError={embeddingError}+ embeddingStatus={embeddingStatus ?? undefined}+ fileType={fileType}+ finishEmbedding={finishEmbedding}+ id={id}+ name={name}+ size={size}+ />+ );+ }+ }+ })()}+ </div>++ {/* Note Editor Modal */}+ {isNote && (+ <NoteEditorModal+ documentId={id}+ documentTitle={name}+ editorData={editorData}+ knowledgeBaseId={knowledgeBaseId}+ onClose={() => {+ console.log('[MasonryFileItem] Closing note modal');+ setIsNoteModalOpen(false);+ }}+ open={isNoteModalOpen}+ />+ )}+ </div>+ );+ },+);++export default MasonryFileItem;diff --git a/src/features/FileManager/FileList/MasonrySkeleton.tsx b/src/features/KnowledgeManager/FileExplorer/MasonrySkeleton.tsxsimilarity index 100%rename from src/features/FileManager/FileList/MasonrySkeleton.tsxrename to src/features/KnowledgeManager/FileExplorer/MasonrySkeleton.tsxdiff --git a/src/features/FileManager/FileList/ToolBar/Config.tsx b/src/features/KnowledgeManager/FileExplorer/ToolBar/Config.tsxsimilarity index 100%rename from src/features/FileManager/FileList/ToolBar/Config.tsxrename to src/features/KnowledgeManager/FileExplorer/ToolBar/Config.tsxdiff --git a/src/features/FileManager/FileList/ToolBar/MultiSelectActions.tsx b/src/features/KnowledgeManager/FileExplorer/ToolBar/MultiSelectActions.tsxsimilarity index 100%rename from src/features/FileManager/FileList/ToolBar/MultiSelectActions.tsxrename to src/features/KnowledgeManager/FileExplorer/ToolBar/MultiSelectActions.tsxdiff --git a/src/features/KnowledgeManager/FileExplorer/ToolBar/ViewSwitcher.tsx b/src/features/KnowledgeManager/FileExplorer/ToolBar/ViewSwitcher.tsxnew file mode 100644index 00000000000..7d6056c139e--- /dev/null+++ b/src/features/KnowledgeManager/FileExplorer/ToolBar/ViewSwitcher.tsx@@ -0,0 +1,45 @@+import { ActionIcon } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { Grid3x3Icon, ListIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';++export type ViewMode = 'list' | 'masonry';++interface ViewSwitcherProps {+ onViewChange: (view: ViewMode) => void;+ view: ViewMode;+}++const useStyles = createStyles(({ css }) => ({+ container: css`+ gap: 4px;+ `,+}));++const ViewSwitcher = memo<ViewSwitcherProps>(({ onViewChange, view }) => {+ const { t } = useTranslation('components');+ const { styles } = useStyles();++ return (+ <Flexbox className={styles.container} horizontal>+ <ActionIcon+ active={view === 'list'}+ icon={ListIcon}+ onClick={() => onViewChange('list')}+ size={16}+ title={t('FileManager.view.list')}+ />+ <ActionIcon+ active={view === 'masonry'}+ icon={Grid3x3Icon}+ onClick={() => onViewChange('masonry')}+ size={16}+ title={t('FileManager.view.masonry')}+ />+ </Flexbox>+ );+});++export default ViewSwitcher;diff --git a/src/features/FileManager/FileList/ToolBar/index.tsx b/src/features/KnowledgeManager/FileExplorer/ToolBar/index.tsxsimilarity index 100%rename from src/features/FileManager/FileList/ToolBar/index.tsxrename to src/features/KnowledgeManager/FileExplorer/ToolBar/index.tsxdiff --git a/src/features/FileManager/FileList/index.tsx b/src/features/KnowledgeManager/FileExplorer/index.tsxsimilarity index 76%rename from src/features/FileManager/FileList/index.tsxrename to src/features/KnowledgeManager/FileExplorer/index.tsxindex 0611fc8024e..f09c6e91d69 100644--- a/src/features/FileManager/FileList/index.tsx+++ b/src/features/KnowledgeManager/FileExplorer/index.tsx@@ -12,7 +12,7 @@ import { Virtuoso } from 'react-virtuoso';import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';-import { SortType } from '@/types/files';+import { FilesTabs, SortType } from '@/types/files';import EmptyStatus from './EmptyStatus';import FileListItem, { FILE_DATE_WIDTH, FILE_SIZE_WIDTH } from './FileListItem';@@ -40,13 +40,13 @@ const useStyles = createStyles(({ css, token, isDarkMode }) => ({`,}));-interface FileListProps {+interface FileExplorerProps {category?: string;knowledgeBaseId?: string;onOpenFile: (id: string) => void;}-const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile }) => {+const FileExplorer = memo<FileExplorerProps>(({ knowledgeBaseId, category, onOpenFile }) => {const { t } = useTranslation('components');const { styles } = useStyles();@@ -54,11 +54,19 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile })const [viewConfig, setViewConfig] = useState({ showFilesInKnowledgeBase: false });const [lastSelectedIndex, setLastSelectedIndex] = useState<number | null>(null);const [isTransitioning, setIsTransitioning] = useState(false);+ const [isMasonryReady, setIsMasonryReady] = useState(false);- const viewMode = useGlobalStore((s) => s.status.fileManagerViewMode || 'list') as ViewMode;+ // Always use masonry view for Images category, ignore stored preference+ const storedViewMode = useGlobalStore((s) => s.status.fileManagerViewMode);+ const viewMode = (+ category === FilesTabs.Images ? 'masonry' : storedViewMode || 'list'+ ) as ViewMode;const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);const setViewMode = (mode: ViewMode) => {setIsTransitioning(true);+ if (mode === 'masonry') {+ setIsMasonryReady(false);+ }updateSystemStatus({ fileManagerViewMode: mode });};@@ -71,7 +79,7 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile })setColumnCount(2);} else if (width < 1024) {setColumnCount(3);- } else if (width < 1440) {+ } else if (width < 1536) {setColumnCount(4);} else {setColumnCount(5);@@ -100,9 +108,9 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile })defaultValue: SortType.Desc,});- const useFetchFileManage = useFileStore((s) => s.useFetchFileManage);+ const useFetchKnowledgeItems = useFileStore((s) => s.useFetchKnowledgeItems);- const { data, isLoading } = useFetchFileManage({+ const { data, isLoading } = useFetchKnowledgeItems({category,knowledgeBaseId,q: query,@@ -111,6 +119,19 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile })...viewConfig,});+ // Debug: Log received data+ React.useEffect(() => {+ if (data) {+ console.log('[FileList] Received data:', {+ count: data.length,+ documents: data.filter((item) => item.sourceType === 'document'),+ sampleDocumentWithEditorData: data.find(+ (item) => item.sourceType === 'document' && item.editorData,+ ),+ });+ }+ }, [data]);+// Handle view transition with a brief delay to show skeletonReact.useEffect(() => {if (isTransitioning && data) {@@ -124,6 +145,20 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile })}}, [isTransitioning, viewMode, data]);+ // Mark masonry as ready after it has time to mount and render+ React.useEffect(() => {+ if (viewMode === 'masonry' && data && !isLoading && !isTransitioning) {+ // Give VirtuosoMasonry enough time to fully render and calculate layout+ const timer = setTimeout(() => {+ setIsMasonryReady(true);+ }, 300);+ return () => clearTimeout(timer);+ } else if (viewMode === 'list') {+ // Reset when switching to list view+ setIsMasonryReady(false);+ }+ }, [viewMode, data, isLoading, isTransitioning]);+useCheckTaskStatus(data);// Clean up selected files that no longer exist in the data@@ -188,12 +223,8 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile })</Flexbox>)}</Flexbox>- {isLoading || isTransitioning ? (- viewMode === 'masonry' ? (- <MasonrySkeleton columnCount={columnCount} />- ) : (- <FileSkeleton />- )+ {isLoading || (viewMode === 'list' && isTransitioning) ? (+ <FileSkeleton />) : viewMode === 'list' ? (<Virtuosocomponents={{@@ -243,8 +274,29 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile })style={{ flex: 1 }}/>) : (- <div style={{ flex: 1, overflow: 'hidden' }}>- <div style={{ height: '100%', overflowY: 'auto' }}>+ <div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>+ {/* Skeleton overlay */}+ {(isTransitioning || !isMasonryReady) && (+ <div+ style={{+ background: 'inherit',+ inset: 0,+ position: 'absolute',+ zIndex: 10,+ }}+ >+ <MasonrySkeleton columnCount={columnCount} />+ </div>+ )}+ {/* Masonry content - always rendered but hidden until ready */}+ <div+ style={{+ height: '100%',+ opacity: isMasonryReady ? 1 : 0,+ overflowY: 'auto',+ transition: 'opacity 0.2s ease-in-out',+ }}+ ><div style={{ paddingBlockEnd: 64, paddingBlockStart: 12, paddingInline: 24 }}><VirtuosoMasonryItemContent={MasonryItemWrapper}@@ -263,4 +315,4 @@ const FileList = memo<FileListProps>(({ knowledgeBaseId, category, onOpenFile }));});-export default FileList;+export default FileExplorer;diff --git a/src/features/FileManager/FileList/useCheckTaskStatus.ts b/src/features/KnowledgeManager/FileExplorer/useCheckTaskStatus.tssimilarity index 100%rename from src/features/FileManager/FileList/useCheckTaskStatus.tsrename to src/features/KnowledgeManager/FileExplorer/useCheckTaskStatus.tsdiff --git a/src/features/KnowledgeManager/Header/AddButton.tsx b/src/features/KnowledgeManager/Header/AddButton.tsxnew file mode 100644index 00000000000..4a3440895e3--- /dev/null+++ b/src/features/KnowledgeManager/Header/AddButton.tsx@@ -0,0 +1,107 @@+'use client';++import { Button, Dropdown, Icon, MenuProps } from '@lobehub/ui';+import { Upload } from 'antd';+import { css, cx } from 'antd-style';+import { FilePenLine, FileUp, FolderUp, Plus } from 'lucide-react';+import { useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import DragUpload from '@/components/DragUpload';+import { useFileStore } from '@/store/file';++import NoteEditorModal from '../DocumentExplorer/NoteEditorModal';++const hotArea = css`+ &::before {+ content: '';+ position: absolute;+ inset: 0;+ background-color: transparent;+ }+`;++const AddButton = ({ knowledgeBaseId }: { knowledgeBaseId?: string }) => {+ const { t } = useTranslation('file');+ const [isModalOpen, setIsModalOpen] = useState(false);+ const pushDockFileList = useFileStore((s) => s.pushDockFileList);++ const handleOpenNoteEditor = () => {+ setIsModalOpen(true);+ };++ const handleCloseNoteEditor = () => {+ setIsModalOpen(false);+ };++ const items = useMemo<MenuProps['items']>(+ () => [+ {+ icon: <Icon icon={FilePenLine} />,+ key: 'create-note',+ label: t('addPage'),+ onClick: handleOpenNoteEditor,+ },+ {+ type: 'divider',+ },+ {+ icon: <Icon icon={FileUp} />,+ key: 'upload-file',+ label: (+ <Upload+ beforeUpload={async (file) => {+ await pushDockFileList([file], knowledgeBaseId);++ return false;+ }}+ multiple={true}+ showUploadList={false}+ >+ <div className={cx(hotArea)}>Upload File</div>+ </Upload>+ ),+ },+ {+ icon: <Icon icon={FolderUp} />,+ key: 'upload-folder',+ label: (+ <Upload+ beforeUpload={async (file) => {+ await pushDockFileList([file], knowledgeBaseId);++ return false;+ }}+ directory+ multiple={true}+ showUploadList={false}+ >+ <div className={cx(hotArea)}>Upload Folder</div>+ </Upload>+ ),+ },+ ],+ [knowledgeBaseId, pushDockFileList],+ );++ return (+ <>+ <Dropdown menu={{ items }} placement="bottomRight">+ <Button icon={Plus} type="primary">+ {t('addKnowledge')}+ </Button>+ </Dropdown>+ <DragUpload+ enabledFiles+ onUploadFiles={(files) => pushDockFileList(files, knowledgeBaseId)}+ />+ <NoteEditorModal+ knowledgeBaseId={knowledgeBaseId}+ onClose={handleCloseNoteEditor}+ open={isModalOpen}+ />+ </>+ );+};++export default AddButton;diff --git a/src/features/FileManager/Header/FilesSearchBar.tsx b/src/features/KnowledgeManager/Header/FilesSearchBar.tsxsimilarity index 100%rename from src/features/FileManager/Header/FilesSearchBar.tsxrename to src/features/KnowledgeManager/Header/FilesSearchBar.tsxdiff --git a/src/features/KnowledgeManager/Header/NewNoteButton.tsx b/src/features/KnowledgeManager/Header/NewNoteButton.tsxnew file mode 100644index 00000000000..9d5160c7726--- /dev/null+++ b/src/features/KnowledgeManager/Header/NewNoteButton.tsx@@ -0,0 +1,33 @@+'use client';++import { Button } from '@lobehub/ui';+import { FilePenLine } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import NoteEditorModal from '../DocumentExplorer/NoteEditorModal';++const NewNoteButton = ({ knowledgeBaseId }: { knowledgeBaseId?: string }) => {+ const { t } = useTranslation('file');+ const [isModalOpen, setIsModalOpen] = useState(false);++ const handleOpen = () => {+ setIsModalOpen(true);+ };++ const handleClose = () => {+ setIsModalOpen(false);+ };++ return (+ <>+ <Button icon={FilePenLine} onClick={handleOpen} type="primary">+ {t('header.newDocumentButton')}+ </Button>++ <NoteEditorModal knowledgeBaseId={knowledgeBaseId} onClose={handleClose} open={isModalOpen} />+ </>+ );+};++export default NewNoteButton;diff --git a/src/features/FileManager/Header/TogglePanelButton.tsx b/src/features/KnowledgeManager/Header/TogglePanelButton.tsxsimilarity index 100%rename from src/features/FileManager/Header/TogglePanelButton.tsxrename to src/features/KnowledgeManager/Header/TogglePanelButton.tsxdiff --git a/src/features/FileManager/Header/UploadFileButton.tsx b/src/features/KnowledgeManager/Header/UploadFileButton.tsxsimilarity index 100%rename from src/features/FileManager/Header/UploadFileButton.tsxrename to src/features/KnowledgeManager/Header/UploadFileButton.tsxdiff --git a/src/features/FileManager/Header/index.tsx b/src/features/KnowledgeManager/Header/index.tsxsimilarity index 55%rename from src/features/FileManager/Header/index.tsxrename to src/features/KnowledgeManager/Header/index.tsxindex a4362d614c2..fd4c1634fe9 100644--- a/src/features/FileManager/Header/index.tsx+++ b/src/features/KnowledgeManager/Header/index.tsx@@ -3,20 +3,14 @@import { ChatHeader } from '@lobehub/ui/chat';import { memo } from 'react';+import AddButton from './AddButton';import FilesSearchBar from './FilesSearchBar';-import TogglePanelButton from './TogglePanelButton';-import UploadFileButton from './UploadFileButton';const Header = memo<{ knowledgeBaseId?: string }>(({ knowledgeBaseId }) => {return (<ChatHeader- left={- <>- <TogglePanelButton />- <FilesSearchBar />- </>- }- right={<UploadFileButton knowledgeBaseId={knowledgeBaseId} />}+ left={<FilesSearchBar />}+ right={<AddButton knowledgeBaseId={knowledgeBaseId} />}styles={{left: { padding: 0 },}}diff --git a/src/features/KnowledgeManager/Home/RecentDocumentCard.tsx b/src/features/KnowledgeManager/Home/RecentDocumentCard.tsxnew file mode 100644index 00000000000..33076ad8f04--- /dev/null+++ b/src/features/KnowledgeManager/Home/RecentDocumentCard.tsx@@ -0,0 +1,115 @@+'use client';++import { createStyles } from 'antd-style';+import markdownToTxt from 'markdown-to-txt';+import { memo } from 'react';++import { FileListItem } from '@/types/files';++// Helper to extract title from markdown content+const extractTitle = (content: string): string | null => {+ if (!content) return null;++ // Find first markdown header (# title)+ const match = content.match(/^#\s+(.+)$/m);+ return match ? match[1].trim() : null;+};++// Helper to extract preview text from note content+const getPreviewText = (item: FileListItem): string => {+ if (!item.content) return '';++ // Convert markdown to plain text+ let plainText = markdownToTxt(item.content);++ // Remove the title line if it exists+ const title = extractTitle(item.content);+ if (title) {+ plainText = plainText.replace(title, '').trim();+ }++ // Limit to first 200 characters for preview+ return plainText.slice(0, 200);+};++const useStyles = createStyles(({ css, token }) => ({+ card: css`+ cursor: pointer;+ user-select: none;++ position: relative;+ flex-shrink: 0;++ overflow: hidden;++ width: 280px;+ height: 180px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;++ background: ${token.colorBgContainer};++ transition: all ${token.motionDurationMid};++ &:hover {+ border-color: ${token.colorPrimary};+ box-shadow: ${token.boxShadowTertiary};+ }+ `,+ noteContent: css`+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 12px;+ height: 100%;+ overflow: hidden;+ `,+ notePreview: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 3;++ font-size: 13px;+ line-height: 1.6;+ color: ${token.colorTextSecondary};+ flex: 1;+ `,+ noteTitle: css`+ overflow: hidden;++ font-size: 14px;+ font-weight: ${token.fontWeightStrong};+ line-height: 1.4;+ color: ${token.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++interface RecentDocumentCardProps {+ document: FileListItem;+ onClick: () => void;+}++const RecentDocumentCard = memo<RecentDocumentCardProps>(({ document, onClick }) => {+ const { styles } = useStyles();++ const title = document.name || '';+ const previewText = getPreviewText(document);+ const emoji = document.metadata?.emoji;++ return (+ <div className={styles.card} onClick={onClick} role="button" tabIndex={0}>+ <div className={styles.noteContent}>+ <div style={{ alignItems: 'center', display: 'flex', gap: 8 }}>+ {emoji && <span style={{ fontSize: 20 }}>{emoji}</span>}+ <div className={styles.noteTitle}>{title}</div>+ </div>+ {previewText && <div className={styles.notePreview}>{previewText}</div>}+ </div>+ </div>+ );+});++export default RecentDocumentCard;diff --git a/src/features/KnowledgeManager/Home/RecentDocuments.tsx b/src/features/KnowledgeManager/Home/RecentDocuments.tsxnew file mode 100644index 00000000000..af6bf8a0b25--- /dev/null+++ b/src/features/KnowledgeManager/Home/RecentDocuments.tsx@@ -0,0 +1,77 @@+'use client';++import { createStyles } from 'antd-style';+import { memo } from 'react';++import { FileListItem } from '@/types/files';++import RecentDocumentCard from './RecentDocumentCard';+import RecentFilesSkeleton from './RecentFilesSkeleton';++const useStyles = createStyles(({ css, token }) => ({+ container: css`+ position: relative;+ overflow: hidden;+ `,+ fadeEdge: css`+ pointer-events: none;++ position: absolute;+ inset-block: 0 0;+ inset-inline-end: 0;++ width: 80px;++ background: linear-gradient(to left, ${token.colorBgContainerSecondary}, transparent);+ `,+ scrollContainer: css`+ scroll-behavior: smooth;++ /* Hide scrollbar */+ scrollbar-width: none;++ overflow: auto hidden;+ display: flex;+ gap: 16px;++ padding-block-end: 8px;+ padding-inline-end: 80px;++ -ms-overflow-style: none;++ &::-webkit-scrollbar {+ display: none;+ }+ `,+}));++interface RecentDocumentsProps {+ documents: FileListItem[];+ isLoading?: boolean;+ onOpenDocument: (id: string) => void;+}++const RecentDocuments = memo<RecentDocumentsProps>(({ documents, isLoading, onOpenDocument }) => {+ const { styles } = useStyles();++ if (isLoading) {+ return <RecentFilesSkeleton />;+ }++ return (+ <div className={styles.container}>+ <div className={styles.scrollContainer}>+ {documents.map((document) => (+ <RecentDocumentCard+ document={document}+ key={document.id}+ onClick={() => onOpenDocument(document.id)}+ />+ ))}+ </div>+ <div className={styles.fadeEdge} />+ </div>+ );+});++export default RecentDocuments;diff --git a/src/features/KnowledgeManager/Home/RecentFileCard.tsx b/src/features/KnowledgeManager/Home/RecentFileCard.tsxnew file mode 100644index 00000000000..fcc3a1ee468--- /dev/null+++ b/src/features/KnowledgeManager/Home/RecentFileCard.tsx@@ -0,0 +1,118 @@+'use client';++import { formatSize } from '@lobechat/utils/format';+import { Image as LobeImage, Text } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import dayjs from 'dayjs';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import FileIcon from '@/components/FileIcon';+import { FileListItem } from '@/types/files';++const IMAGE_FILE_TYPES = new Set([+ 'image/png',+ 'image/jpeg',+ 'image/jpg',+ 'image/gif',+ 'image/webp',+ 'image/svg+xml',+]);++const useStyles = createStyles(({ css, token }) => ({+ card: css`+ cursor: pointer;++ position: relative;+ flex-shrink: 0;++ overflow: hidden;++ width: 280px;+ padding: 12px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;++ background: ${token.colorBgContainer};++ transition: all ${token.motionDurationMid};++ &:hover {+ border-color: ${token.colorPrimary};+ box-shadow: ${token.boxShadowTertiary};+ }+ `,+ iconWrapper: css`+ display: flex;+ align-items: center;+ justify-content: center;+ height: 160px;+ margin-block-end: 12px;+ border-radius: ${token.borderRadius}px;+ background: ${token.colorBgLayout};+ `,+ imagePreview: css`+ width: 100%;+ height: 160px;+ margin-block-end: 12px;+ border-radius: ${token.borderRadius}px;+ background: ${token.colorBgLayout};+ object-fit: cover;+ `,+ info: css`+ font-size: 12px;+ color: ${token.colorTextDescription};+ `,+ title: css`+ margin: 0 !important;+ font-size: 14px;+ font-weight: 500;+ line-height: 1.4;+ `,+}));++interface RecentFileCardProps {+ file: FileListItem;+ onClick: () => void;+}++const RecentFileCard = memo<RecentFileCardProps>(({ file, onClick }) => {+ const { styles } = useStyles();++ const isImage = IMAGE_FILE_TYPES.has(file.fileType);+ const relativeTime = dayjs(file.updatedAt).fromNow();++ return (+ <div className={styles.card} onClick={onClick} role="button" tabIndex={0}>+ <Flexbox gap={12} style={{ position: 'relative' }}>+ {/* Preview or Icon */}+ {isImage && file.url ? (+ <LobeImage+ alt={file.name}+ className={styles.imagePreview}+ preview={false}+ src={file.url}+ />+ ) : (+ <div className={styles.iconWrapper}>+ <FileIcon fileName={file.name} fileType={file.fileType} size={48} />+ </div>+ )}++ {/* File Info */}+ <Flexbox gap={6} style={{ overflow: 'hidden', position: 'relative' }}>+ <Text className={styles.title} ellipsis={{ rows: 2 }}>+ {file.name}+ </Text>+ <Flexbox className={styles.info} gap={8} horizontal>+ <span>{relativeTime}</span>+ <span>•</span>+ <span>{formatSize(file.size)}</span>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ </div>+ );+});++export default RecentFileCard;diff --git a/src/features/KnowledgeManager/Home/RecentFiles.tsx b/src/features/KnowledgeManager/Home/RecentFiles.tsxnew file mode 100644index 00000000000..e05f76c3d4c--- /dev/null+++ b/src/features/KnowledgeManager/Home/RecentFiles.tsx@@ -0,0 +1,73 @@+'use client';++import { createStyles } from 'antd-style';+import { memo } from 'react';++import { FileListItem } from '@/types/files';++import RecentFileCard from './RecentFileCard';+import RecentFilesSkeleton from './RecentFilesSkeleton';++const useStyles = createStyles(({ css, token }) => ({+ container: css`+ position: relative;+ overflow: hidden;+ `,+ fadeEdge: css`+ pointer-events: none;++ position: absolute;+ inset-block: 0 0;+ inset-inline-end: 0;++ width: 80px;++ background: linear-gradient(to left, ${token.colorBgContainerSecondary}, transparent);+ `,+ scrollContainer: css`+ scroll-behavior: smooth;++ /* Hide scrollbar */+ scrollbar-width: none;++ overflow: auto hidden;+ display: flex;+ gap: 16px;++ padding-block-end: 8px;+ padding-inline-end: 80px;++ -ms-overflow-style: none;++ &::-webkit-scrollbar {+ display: none;+ }+ `,+}));++interface RecentFilesProps {+ files: FileListItem[];+ isLoading?: boolean;+ onOpenFile: (id: string) => void;+}++const RecentFiles = memo<RecentFilesProps>(({ files, isLoading, onOpenFile }) => {+ const { styles } = useStyles();++ if (isLoading) {+ return <RecentFilesSkeleton />;+ }++ return (+ <div className={styles.container}>+ <div className={styles.scrollContainer}>+ {files.map((file) => (+ <RecentFileCard file={file} key={file.id} onClick={() => onOpenFile(file.id)} />+ ))}+ </div>+ <div className={styles.fadeEdge} />+ </div>+ );+});++export default RecentFiles;diff --git a/src/features/KnowledgeManager/Home/RecentFilesSkeleton.tsx b/src/features/KnowledgeManager/Home/RecentFilesSkeleton.tsxnew file mode 100644index 00000000000..7dde5943136--- /dev/null+++ b/src/features/KnowledgeManager/Home/RecentFilesSkeleton.tsx@@ -0,0 +1,79 @@+'use client';++import { Skeleton } from 'antd';+import { createStyles } from 'antd-style';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++const useStyles = createStyles(({ css, token }) => ({+ card: css`+ flex-shrink: 0;++ width: 280px;+ padding: 12px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;++ background: ${token.colorBgContainer};+ `,+ container: css`+ position: relative;+ overflow: hidden;+ `,+ fadeEdge: css`+ pointer-events: none;+ position: absolute;+ top: 0;+ right: 0;+ bottom: 0;++ width: 80px;++ background: linear-gradient(to left, ${token.colorBgLayout}, transparent);+ `,+ previewSkeleton: css`+ width: 100%;+ height: 160px;+ margin-block-end: 12px;+ border-radius: ${token.borderRadius}px;+ background: ${token.colorFillQuaternary};+ `,+ scrollContainer: css`+ display: flex;+ gap: 16px;+ overflow-x: auto;+ padding-bottom: 8px;++ /* Hide scrollbar */+ scrollbar-width: none;+ -ms-overflow-style: none;++ &::-webkit-scrollbar {+ display: none;+ }+ `,+}));++const RecentFilesSkeleton = memo(() => {+ const { styles } = useStyles();++ return (+ <div className={styles.container}>+ <div className={styles.scrollContainer}>+ {Array.from({ length: 10 }).map((_, index) => (+ <Flexbox className={styles.card} gap={12} key={index}>+ <div className={styles.previewSkeleton} />+ <Flexbox gap={6}>+ <Skeleton active paragraph={false} title={{ width: '90%' }} />+ <Skeleton active paragraph={false} title={{ style: { height: 12 }, width: '70%' }} />+ </Flexbox>+ </Flexbox>+ ))}+ </div>+ <div className={styles.fadeEdge} />+ </div>+ );+});++export default RecentFilesSkeleton;+diff --git a/src/features/KnowledgeManager/Home/UploadEntries.tsx b/src/features/KnowledgeManager/Home/UploadEntries.tsxnew file mode 100644index 00000000000..f92bb0eb550--- /dev/null+++ b/src/features/KnowledgeManager/Home/UploadEntries.tsx@@ -0,0 +1,208 @@+'use client';++import { FileTypeIcon, Icon } from '@lobehub/ui';+import { Upload } from 'antd';+import { createStyles, useTheme } from 'antd-style';+import { ArrowUpIcon, FolderUp, PlusIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';+import { useNavigate } from 'react-router-dom';++import { useFileStore } from '@/store/file';++const ICON_SIZE = 64;++const useStyles = createStyles(({ css, token }) => ({+ actionTitle: css`+ margin-block-start: 12px;+ font-size: 14px;+ font-weight: 500;+ color: ${token.colorTextSecondary};+ `,+ card: css`+ cursor: pointer;++ position: relative;++ overflow: hidden;++ width: 200px;+ min-height: 120px;+ padding: 16px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: ${token.borderRadiusLG}px;++ font-weight: 500;+ text-align: center;++ background: ${token.colorBgContainer};++ transition: all ${token.motionDurationMid} ${token.motionEaseInOut};++ &:hover {+ border-color: ${token.colorPrimary};+ box-shadow: ${token.boxShadowTertiary};+ }+ `,+ glow: css`+ position: absolute;+ inset-block-end: -12px;+ inset-inline-end: 0;++ width: 48px;+ height: 48px;++ opacity: 0.3;+ filter: blur(24px);+ `,+ grid: css`+ display: flex;+ flex-wrap: wrap;+ gap: 16px;+ justify-content: left;+ `,+ icon: css`+ position: absolute;+ z-index: 1;+ inset-block-end: -16px;+ inset-inline-end: 8px;++ flex: none;+ `,+ uploadWrapper: css`+ /* Make the wrapper transparent so hover passes through to the card */+ & > span {+ display: block;+ }+ `,+}));++interface UploadEntriesProps {+ knowledgeBaseId?: string;+}++const UploadEntries = memo<UploadEntriesProps>(({ knowledgeBaseId }) => {+ const { t } = useTranslation('file');+ const theme = useTheme();+ const { styles } = useStyles();+ const navigate = useNavigate();++ const createDocument = useFileStore((s) => s.createDocument);+ const pushDockFileList = useFileStore((s) => s.pushDockFileList);+ // const { open } = useCreateNewModal();++ const handleCreateNote = async () => {+ try {+ const newDoc = await createDocument({+ content: '',+ knowledgeBaseId,+ title: t('home.uploadEntries.newDocument.title'),+ });+ // Navigate to the newly created document+ // The KnowledgeHomePage will automatically set category to 'documents' when it detects the id param+ navigate(`/${newDoc.id}`);+ } catch (error) {+ console.error('Failed to create document:', error);+ }+ };++ // const handleCreateKnowledgeBase = () => {+ // open({+ // onSuccess: (id) => {+ // navigate(`/bases/${id}`);+ // },+ // });+ // };++ const handleUploadFiles = async (file: File) => {+ try {+ await pushDockFileList([file], knowledgeBaseId);+ } catch (error) {+ console.error('Failed to upload file:', error);+ }+ return false;+ };++ const handleUploadFolder = async (file: File) => {+ try {+ await pushDockFileList([file], knowledgeBaseId);+ } catch (error) {+ console.error('Failed to upload folder:', error);+ }+ return false;+ };++ return (+ <div className={styles.grid}>+ {/* Create New Note */}+ <Flexbox className={styles.card} onClick={handleCreateNote} padding={16}>+ <span className={styles.actionTitle}>{t('home.uploadEntries.newDocument.title')}</span>+ <div className={styles.glow} style={{ background: theme.purple }} />+ <FileTypeIcon+ className={styles.icon}+ color={theme.purple}+ icon={<Icon color={'#fff'} icon={PlusIcon} />}+ size={ICON_SIZE}+ type={'file'}+ />+ </Flexbox>++ {/* Create Knowledge Base */}+ {/* <Flexbox className={styles.card} onClick={handleCreateKnowledgeBase} padding={16}>+ <span className={styles.actionTitle}>{t('home.uploadEntries.knowledgeBase.title')}</span>+ <div className={styles.glow} style={{ background: theme.colorPrimary }} />+ <FileTypeIcon+ className={styles.icon}+ color={theme.colorPrimary}+ icon={<Icon color={'#fff'} icon={LibraryBig} />}+ size={ICON_SIZE}+ type={'file'}+ />+ </Flexbox> */}++ {/* Upload Files */}+ <Upload+ beforeUpload={handleUploadFiles}+ className={styles.uploadWrapper}+ multiple+ showUploadList={false}+ >+ <Flexbox className={styles.card} padding={16}>+ <span className={styles.actionTitle}>{t('home.uploadEntries.files.title')}</span>+ <div className={styles.glow} style={{ background: theme.geekblue }} />+ <FileTypeIcon+ className={styles.icon}+ color={theme.geekblue}+ icon={<Icon color={'#fff'} icon={ArrowUpIcon} />}+ size={ICON_SIZE}+ type={'file'}+ />+ </Flexbox>+ </Upload>++ {/* Upload Folder */}+ <Upload+ beforeUpload={handleUploadFolder}+ className={styles.uploadWrapper}+ directory+ multiple+ showUploadList={false}+ >+ <Flexbox className={styles.card} padding={16}>+ <span className={styles.actionTitle}>{t('home.uploadEntries.folder.title')}</span>+ <div className={styles.glow} style={{ background: theme.green }} />+ <FileTypeIcon+ className={styles.icon}+ color={theme.green}+ icon={<Icon color={'#fff'} icon={FolderUp} />}+ size={ICON_SIZE}+ type={'file'}+ />+ </Flexbox>+ </Upload>+ </div>+ );+});++export default UploadEntries;diff --git a/src/features/KnowledgeManager/Home/index.tsx b/src/features/KnowledgeManager/Home/index.tsxnew file mode 100644index 00000000000..fe9cbc87ed0--- /dev/null+++ b/src/features/KnowledgeManager/Home/index.tsx@@ -0,0 +1,221 @@+'use client';++import { ActionIcon, Dropdown, Text } from '@lobehub/ui';+import { createStyles } from 'antd-style';+import { Clock, FileTextIcon, MoreHorizontal } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Flexbox } from 'react-layout-kit';+import { useNavigate } from 'react-router-dom';++import { useFileCategory } from '@/app/[variants]/(main)/knowledge/hooks/useFileCategory';+import { useFileStore } from '@/store/file';+import { FilesTabs } from '@/types/files';++import RecentDocuments from './RecentDocuments';+import RecentFiles from './RecentFiles';+import UploadEntries from './UploadEntries';++const useStyles = createStyles(({ css, token }) => ({+ container: css`+ padding-block: 20px 48px;+ padding-inline: 24px;+ `,+ content: css`+ width: 100%;+ max-width: 1200px;+ margin-block: 0;+ margin-inline: auto;+ `,+ greeting: css`+ font-size: 24px;+ font-weight: 600;+ color: ${token.colorText};+ text-align: start;+ `,+ section: css`+ margin-block: 6px 36px;+ `,+ sectionActions: css`+ transition: opacity ${token.motionDurationMid} ${token.motionEaseInOut};+ `,+ sectionTitle: css`+ display: flex;+ gap: 8px;+ align-items: center;++ margin-block-end: 24px;++ font-size: 18px;+ font-weight: 600;+ color: ${token.colorTextSecondary};+ text-align: start;+ `,+ sectionTitleWrapper: css`+ display: flex;+ align-items: center;+ justify-content: space-between;++ min-height: 36px;+ margin-block-end: 24px;+ `,+}));++interface HomeProps {+ knowledgeBaseId?: string;+ onOpenFile: (id: string) => void;+}++const Home = memo<HomeProps>(({ knowledgeBaseId, onOpenFile }) => {+ const { t } = useTranslation('file');+ const { styles } = useStyles();+ const navigate = useNavigate();+ const [, setActiveKey] = useFileCategory();+ const [isDocumentsMenuOpen, setIsDocumentsMenuOpen] = useState(false);+ const [isDocumentsSectionHovered, setIsDocumentsSectionHovered] = useState(false);+ const [isFilesMenuOpen, setIsFilesMenuOpen] = useState(false);+ const [isFilesSectionHovered, setIsFilesSectionHovered] = useState(false);++ const useFetchKnowledgeItems = useFileStore((s) => s.useFetchKnowledgeItems);++ // Fetch all items (all categories, sorted by updatedAt)+ const { data: allItems, isLoading } = useFetchKnowledgeItems({+ category: FilesTabs.All,+ knowledgeBaseId,+ sortType: 'desc',+ sorter: 'createdAt',+ });++ // Get top 10 recent files (filter by sourceType === 'file')+ const topRecentFiles = useMemo(() => {+ if (!allItems) return [];+ const files = allItems.filter((item) => item.sourceType === 'file');+ return files.slice(0, 10);+ }, [allItems]);++ // Get top 10 recent documents (filter by sourceType === 'document')+ const topRecentDocuments = useMemo(() => {+ if (!allItems) return [];+ const documents = allItems.filter((item) => item.sourceType === 'document');+ return documents.slice(0, 10);+ }, [allItems]);++ // Handle document click - navigate to document explorer+ const handleDocumentClick = (documentId: string) => {+ // Navigate to the document in the explorer+ // The KnowledgeHomePage will automatically set category to 'documents' when it detects the id param+ navigate(`/${documentId}`);+ };++ return (+ <div className={styles.container}>+ <Flexbox className={styles.content}>+ {/* Greeting Section */}+ <Flexbox className={styles.section}>+ <Text className={styles.greeting}>{t('home.greeting')}</Text>+ </Flexbox>++ {/* Upload Entries Section */}+ <Flexbox className={styles.section}>+ <UploadEntries knowledgeBaseId={knowledgeBaseId} />+ </Flexbox>++ {/* Recent Files Section */}+ {(isLoading || topRecentFiles.length > 0) && (+ <div+ className={styles.section}+ onMouseEnter={() => {+ setIsFilesSectionHovered(true);+ }}+ onMouseLeave={() => {+ setIsFilesSectionHovered(false);+ }}+ >+ <div className={styles.sectionTitleWrapper}>+ <Text className={styles.sectionTitle} style={{ marginBottom: 0 }}>+ <Clock size={18} />+ {t('home.recentFiles')}+ </Text>+ <div+ className={styles.sectionActions}+ style={{+ opacity: isFilesSectionHovered || isFilesMenuOpen ? 1 : 0,+ }}+ >+ <Dropdown+ menu={{+ items: [+ {+ key: 'all-files',+ label: t('menu.allFiles'),+ onClick: () => {+ setActiveKey(FilesTabs.All);+ },+ },+ ],+ }}+ onOpenChange={setIsFilesMenuOpen}+ open={isFilesMenuOpen}+ >+ <ActionIcon icon={MoreHorizontal} size="small" />+ </Dropdown>+ </div>+ </div>+ <RecentFiles files={topRecentFiles} isLoading={isLoading} onOpenFile={onOpenFile} />+ </div>+ )}++ {/* Recent Documents Section */}+ {(isLoading || topRecentDocuments.length > 0) && (+ <div+ className={styles.section}+ onMouseEnter={() => {+ setIsDocumentsSectionHovered(true);+ }}+ onMouseLeave={() => {+ setIsDocumentsSectionHovered(false);+ }}+ >+ <div className={styles.sectionTitleWrapper}>+ <Text className={styles.sectionTitle} style={{ marginBottom: 0 }}>+ <FileTextIcon size={18} />+ {t('home.recentDocuments')}+ </Text>+ <div+ className={styles.sectionActions}+ style={{+ opacity: isDocumentsSectionHovered || isDocumentsMenuOpen ? 1 : 0,+ }}+ >+ <Dropdown+ menu={{+ items: [+ {+ key: 'all-documents',+ label: t('menu.allDocuments'),+ onClick: () => {+ setActiveKey(FilesTabs.Documents);+ },+ },+ ],+ }}+ onOpenChange={setIsDocumentsMenuOpen}+ open={isDocumentsMenuOpen}+ >+ <ActionIcon icon={MoreHorizontal} size="small" />+ </Dropdown>+ </div>+ </div>+ <RecentDocuments+ documents={topRecentDocuments}+ isLoading={isLoading}+ onOpenDocument={handleDocumentClick}+ />+ </div>+ )}+ </Flexbox>+ </div>+ );+});++export default Home;diff --git a/src/features/FileManager/UploadDock/Item.tsx b/src/features/KnowledgeManager/UploadDock/Item.tsxsimilarity index 100%rename from src/features/FileManager/UploadDock/Item.tsxrename to src/features/KnowledgeManager/UploadDock/Item.tsxdiff --git a/src/features/FileManager/UploadDock/index.tsx b/src/features/KnowledgeManager/UploadDock/index.tsxsimilarity index 100%rename from src/features/FileManager/UploadDock/index.tsxrename to src/features/KnowledgeManager/UploadDock/index.tsxdiff --git a/src/features/KnowledgeManager/index.tsx b/src/features/KnowledgeManager/index.tsxnew file mode 100644index 00000000000..3f268e80b0d--- /dev/null+++ b/src/features/KnowledgeManager/index.tsx@@ -0,0 +1,75 @@+'use client';++import { Text } from '@lobehub/ui';+import dynamic from 'next/dynamic';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { FilesTabs } from '@/types/files';++import DocumentExplorer from './DocumentExplorer';+import FileExplorer from './FileExplorer';+import Header from './Header';+import Home from './Home';+import UploadDock from './UploadDock';++const ChunkDrawer = dynamic(() => import('./ChunkDrawer'), { ssr: false });++interface KnowledgeManagerProps {+ category?: string;+ // Directly open a document if provided+ documentId?: string;+ knowledgeBaseId?: string;+ onOpenFile: (id: string) => void;+ title: string;+}++/**+ * Manage knowledge items. Can be all items or certian knowledge base.+ *+ * DocumentExplorer: For the "documents" category.+ * Home: For the "home" category.+ * FileExplorer: For other categories.+ */+const KnowledgeManager = memo<KnowledgeManagerProps>(+ ({ title, knowledgeBaseId, category, onOpenFile, documentId }) => {+ const isDocumentsView = category === FilesTabs.Pages;+ const isHomeView = category === FilesTabs.Home;++ if (isHomeView) {+ return (+ <>+ <Home knowledgeBaseId={knowledgeBaseId} onOpenFile={onOpenFile} />+ <UploadDock />+ <ChunkDrawer />+ </>+ );+ }++ return (+ <>+ {!isDocumentsView && <Header knowledgeBaseId={knowledgeBaseId} />}+ <Flexbox gap={12} height={'100%'}>+ {!isDocumentsView && (+ <Text strong style={{ fontSize: 16, marginBlock: 16, marginInline: 24 }}>+ {title}+ </Text>+ )}+ {isDocumentsView ? (+ <DocumentExplorer documentId={documentId} knowledgeBaseId={knowledgeBaseId} />+ ) : (+ <FileExplorer+ category={category}+ knowledgeBaseId={knowledgeBaseId}+ onOpenFile={onOpenFile}+ />+ )}+ </Flexbox>+ <UploadDock />+ <ChunkDrawer />+ </>+ );+ },+);++export default KnowledgeManager;diff --git a/src/features/Portal/FilePreview/Body/index.tsx b/src/features/Portal/FilePreview/Body/index.tsxindex 3aa8cdb9a50..b1fb82425c2 100644--- a/src/features/Portal/FilePreview/Body/index.tsx+++ b/src/features/Portal/FilePreview/Body/index.tsx@@ -18,7 +18,7 @@ enum FilePreviewTab {const FilePreview = () => {const previewFileId = useChatStore(chatPortalSelectors.previewFileId);const chunkText = useChatStore(chatPortalSelectors.chunkText);- const useFetchFileItem = useFileStore((s) => s.useFetchFileItem);+ const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);const { t } = useTranslation('portal');const [tab, setTab] = useState<FilePreviewTab>(FilePreviewTab.File);diff --git a/src/features/Portal/FilePreview/Header.tsx b/src/features/Portal/FilePreview/Header.tsxindex 687d0537829..ff6581d58a7 100644--- a/src/features/Portal/FilePreview/Header.tsx+++ b/src/features/Portal/FilePreview/Header.tsx@@ -14,7 +14,7 @@ const Header = () => {chatPortalSelectors.previewFileId(s),]);- const useFetchFileItem = useFileStore((s) => s.useFetchFileItem);+ const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);const { data, isLoading } = useFetchFileItem(previewFileId);diff --git a/src/locales/default/common.ts b/src/locales/default/common.tsindex 83d279eefb2..71a4b86c4e2 100644--- a/src/locales/default/common.ts+++ b/src/locales/default/common.ts@@ -289,6 +289,7 @@ export default {oauth: 'SSO 登录',officialSite: '官方网站',ok: '确定',+ or: '或',password: '密码',pin: '置顶',pinOff: '取消置顶',diff --git a/src/locales/default/file.ts b/src/locales/default/file.tsindex c84d89b9e8c..e5a68f25a09 100644--- a/src/locales/default/file.ts+++ b/src/locales/default/file.ts@@ -1,5 +1,7 @@export default {- desc: '管理你的知识',+ addKnowledge: '添加知识',+ addPage: '创建文稿',+ desc: '管理你的工作、学习与生活知识。',detail: {basic: {createdAt: '创建时间',@@ -21,6 +23,44 @@ export default {embeddingStatus: '向量化',},},+ documentEditor: {+ addIcon: '添加图标',+ autoSaveMessage: '文档会自动保存,无需手动保存',+ chooseIcon: '选择图标',+ deleteConfirm: {+ content: '即将删除该文档,删除后将不可恢复,请谨慎操作。',+ title: '删除文档',+ },+ deleteError: '删除文档失败',+ deleteSuccess: '文档删除成功',+ editedAt: '最后编辑于 {{time}}',+ editedBy: '最后编辑者 {{name}}',+ editorPlaceholder: '输入文档内容,按 / 打开命令菜单',+ empty: {+ createNewDocument: '创建新文档',+ title: '选择一个文档以开始',+ uploadMarkdown: '上传 Markdown 文件',+ },+ linkCopied: '链接已复制',+ menu: {+ copyLink: '复制链接',+ exportDocument: '导出文档',+ importDocument: '导入文档',+ pin: '置顶文档',+ },+ saving: '保存中...',+ titlePlaceholder: '无标题',+ wordCount: '{{wordCount}} 字',+ },+ documentList: {+ copyContent: '复制全文',+ documentCount: '共 {{count}} 个文档',+ duplicate: '创建副本',+ empty: '暂无文档,点击上方按钮创建你的第一篇文档',+ noResults: '未找到匹配的文档',+ selectNote: '选择一个文档开始编辑',+ untitled: '无标题',+ },empty: '暂无已上传文件/文件夹',header: {actions: {@@ -28,8 +68,43 @@ export default {uploadFile: '上传文件',uploadFolder: '上传文件夹',},+ newDocumentButton: '新建文档',+ newNoteDialog: {+ cancel: '取消',+ editTitle: '编辑文档',+ emptyContent: '文档内容不能为空',+ loadError: '加载文档失败,请重试',+ loading: '加载中...',+ save: '保存',+ saveError: '保存文档失败,请重试',+ saveSuccess: '文档保存成功',+ title: '新建文档',+ updateSuccess: '文档更新成功',+ },uploadButton: '上传',},+ home: {+ getStarted: '开始使用',+ greeting: '开始',+ quickActions: '快捷操作',+ recentDocuments: '最近文档',+ recentFiles: '最近文件',+ subtitle: '欢迎使用知识库,从这里开始管理你的文档和文档',+ uploadEntries: {+ files: {+ title: '上传文件',+ },+ folder: {+ title: '上传文件夹',+ },+ knowledgeBase: {+ title: '新建知识库',+ },+ newDocument: {+ title: '新建文档',+ },+ },+ },knowledgeBase: {list: {confirmRemoveKnowledgeBase:@@ -39,6 +114,10 @@ export default {new: '新建知识库',title: '知识库',},+ menu: {+ allDocuments: '全部文档',+ allFiles: '全部文件',+ },networkError: '获取知识库失败,请检测网络连接后重试',notSupportGuide: {desc: '当前部署实例为客户端数据库模式,无法使用文件管理功能。请切换到<1>服务端数据库部署模式</1>,或直接使用 <3>LobeChat Cloud</3>',@@ -62,12 +141,16 @@ export default {downloadFile: '下载文件',unsupportedFileAndContact: '此文件格式暂不支持在线预览,如有预览诉求,欢迎<1>反馈给我们</1>',},+ searchDocumentPlaceholder: '搜索文档',searchFilePlaceholder: '搜索文件',tab: {- all: '全部文件',+ all: '全部',audios: '语音',documents: '文档',+ home: '首页',images: '图片',+ moreTypes: '更多类型',+ pages: '文稿',videos: '视频',websites: '网页',},diff --git a/src/server/routers/lambda/__tests__/file.test.ts b/src/server/routers/lambda/__tests__/file.test.tsindex bd47a6ccbc0..6de93a83a3d 100644--- a/src/server/routers/lambda/__tests__/file.test.ts+++ b/src/server/routers/lambda/__tests__/file.test.ts@@ -39,13 +39,21 @@ function createCallerWithCtx(partialCtx: any = {}) {delete: vi.fn(),};+ const knowledgeRepo = {+ query: vi.fn().mockResolvedValue([]),+ };++ const documentModel = {};+const ctx = {serverDB: {} as any,userId: 'test-user',asyncTaskModel,chunkModel,+ documentModel,fileModel,fileService,+ knowledgeRepo,...partialCtx,};@@ -58,18 +66,24 @@ vi.mock('@/config/db', () => ({},}));+const mockAsyncTaskFindByIds = vi.fn();+const mockAsyncTaskFindById = vi.fn();+const mockAsyncTaskDelete = vi.fn();+const mockChunkCountByFileIds = vi.fn();+const mockChunkCountByFileId = vi.fn();+vi.mock('@/database/models/asyncTask', () => ({AsyncTaskModel: vi.fn(() => ({- findById: vi.fn(),- findByIds: vi.fn(),- delete: vi.fn(),+ delete: mockAsyncTaskDelete,+ findById: mockAsyncTaskFindById,+ findByIds: mockAsyncTaskFindByIds,})),}));vi.mock('@/database/models/chunk', () => ({ChunkModel: vi.fn(() => ({- countByFileId: vi.fn(),- countByFileIds: vi.fn(),+ countByFileId: mockChunkCountByFileId,+ countByFileIds: mockChunkCountByFileIds,})),}));@@ -85,14 +99,28 @@ vi.mock('@/database/models/file', () => ({})),}));+const mockFileServiceGetFullFileUrl = vi.fn();+vi.mock('@/server/services/file', () => ({FileService: vi.fn(() => ({- getFullFileUrl: vi.fn(),deleteFile: vi.fn(),deleteFiles: vi.fn(),+ getFullFileUrl: mockFileServiceGetFullFileUrl,})),}));+const mockKnowledgeRepoQuery = vi.fn().mockResolvedValue([]);++vi.mock('@/database/repositories/knowledge', () => ({+ KnowledgeRepo: vi.fn(() => ({+ query: mockKnowledgeRepoQuery,+ })),+}));++vi.mock('@/database/models/document', () => ({+ DocumentModel: vi.fn(() => ({})),+}));+describe('fileRouter', () => {let ctx: any;let caller: any;@@ -169,6 +197,57 @@ describe('fileRouter', () => {});});+ describe('getKnowledgeItems', () => {+ it('should return knowledge items with files and documents', async () => {+ const knowledgeItems = [+ {+ ...mockFile,+ chunkTaskId: 'chunk-1',+ embeddingTaskId: 'emb-1',+ id: 'file-1',+ sourceType: 'file' as const,+ },+ {+ editorData: { content: 'test' },+ id: 'doc-1',+ name: 'Document 1',+ sourceType: 'document' as const,+ },+ ];++ mockKnowledgeRepoQuery.mockResolvedValue(knowledgeItems);+ mockChunkCountByFileIds.mockResolvedValue([{ count: 10, id: 'file-1' }]);+ mockAsyncTaskFindByIds+ .mockResolvedValueOnce([{ error: null, id: 'chunk-1', status: AsyncTaskStatus.Success }])+ .mockResolvedValueOnce([{ error: null, id: 'emb-1', status: AsyncTaskStatus.Success }]);+ mockFileServiceGetFullFileUrl.mockResolvedValue('https://example.com/test-url');++ const result = await caller.getKnowledgeItems({});++ expect(result).toHaveLength(2);+ expect(result[0]).toMatchObject({+ chunkCount: 10,+ chunkingStatus: AsyncTaskStatus.Success,+ embeddingStatus: AsyncTaskStatus.Success,+ finishEmbedding: true,+ id: 'file-1',+ sourceType: 'file',+ url: 'https://example.com/test-url',+ });+ expect(result[1]).toMatchObject({+ chunkCount: null,+ chunkingError: null,+ chunkingStatus: null,+ editorData: { content: 'test' },+ embeddingError: null,+ embeddingStatus: null,+ finishEmbedding: false,+ id: 'doc-1',+ name: 'Document 1',+ });+ });+ });+describe('removeFile', () => {it('should do nothing when file not found', async () => {ctx.fileModel.delete.mockResolvedValue(null);diff --git a/src/server/routers/lambda/document.ts b/src/server/routers/lambda/document.tsindex d75fd86871c..4c1f2e15a11 100644--- a/src/server/routers/lambda/document.ts+++ b/src/server/routers/lambda/document.ts@@ -21,6 +21,38 @@ const documentProcedure = authedProcedure.use(serverDatabase).use(async (opts) =});export const documentRouter = router({+ createDocument: documentProcedure+ .input(+ z.object({+ content: z.string().optional(),+ editorData: z.string(),+ fileType: z.string().optional(),+ knowledgeBaseId: z.string().optional(),+ metadata: z.record(z.any()).optional(),+ title: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ // Parse editorData from JSON string to object+ const editorData = JSON.parse(input.editorData);+ return ctx.documentService.createDocument({+ ...input,+ editorData,+ });+ }),++ deleteDocument: documentProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ return ctx.documentService.deleteDocument(input.id);+ }),++ getDocumentById: documentProcedure+ .input(z.object({ id: z.string() }))+ .query(async ({ ctx, input }) => {+ return ctx.documentService.getDocumentById(input.id);+ }),+parseFileContent: documentProcedure.input(z.object({@@ -33,4 +65,29 @@ export const documentRouter = router({return lobeDocument;}),++ queryDocuments: documentProcedure.query(async ({ ctx }) => {+ return ctx.documentService.queryDocuments();+ }),++ updateDocument: documentProcedure+ .input(+ z.object({+ content: z.string().optional(),+ editorData: z.string().optional(),+ id: z.string(),+ metadata: z.record(z.any()).optional(),+ rawData: z.string().optional(),+ title: z.string().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { id, editorData: editorDataString, ...params } = input;+ // Parse editorData from JSON string to object if present+ const editorData = editorDataString ? JSON.parse(editorDataString) : undefined;+ return ctx.documentService.updateDocument(id, {+ ...params,+ editorData,+ });+ }),});diff --git a/src/server/routers/lambda/file.ts b/src/server/routers/lambda/file.tsindex a02cc113c4e..3485fd5e239 100644--- a/src/server/routers/lambda/file.ts+++ b/src/server/routers/lambda/file.ts@@ -4,7 +4,9 @@ import { z } from 'zod';import { serverDBEnv } from '@/config/db';import { AsyncTaskModel } from '@/database/models/asyncTask';import { ChunkModel } from '@/database/models/chunk';+import { DocumentModel } from '@/database/models/document';import { FileModel } from '@/database/models/file';+import { KnowledgeRepo } from '@/database/repositories/knowledge';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';@@ -18,8 +20,10 @@ const fileProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {ctx: {asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),chunkModel: new ChunkModel(ctx.serverDB, ctx.userId),+ documentModel: new DocumentModel(ctx.serverDB, ctx.userId),fileModel: new FileModel(ctx.serverDB, ctx.userId),fileService: new FileService(ctx.serverDB, ctx.userId),+ knowledgeRepo: new KnowledgeRepo(ctx.serverDB, ctx.userId),},});});@@ -95,6 +99,8 @@ export const fileRouter = router({embeddingError: embeddingTask?.error,embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,+ metadata: item.metadata as Record<string, any> | null | undefined,+ sourceType: 'file' as const,url: await ctx.fileService.getFullFileUrl(item.url!),};}),@@ -132,6 +138,7 @@ export const fileRouter = router({embeddingError: embeddingTask?.error ?? null,embeddingStatus: embeddingTask?.status as AsyncTaskStatus,finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,+ sourceType: 'file' as const,url: await ctx.fileService.getFullFileUrl(item.url!),} as FileListItem;resultFiles.push(fileItem);@@ -140,6 +147,71 @@ export const fileRouter = router({return resultFiles;}),+ getKnowledgeItems: fileProcedure.input(QueryFileListSchema).query(async ({ ctx, input }) => {+ const knowledgeItems = await ctx.knowledgeRepo.query(input);++ // Process files (add chunk info and async task status)+ const fileItems = knowledgeItems.filter((item) => item.sourceType === 'file');+ const fileIds = fileItems.map((item) => item.id);+ const chunks = await ctx.chunkModel.countByFileIds(fileIds);++ const chunkTaskIds = fileItems.map((item) => item.chunkTaskId).filter(Boolean) as string[];+ const chunkTasks = await ctx.asyncTaskModel.findByIds(chunkTaskIds, AsyncTaskType.Chunking);++ const embeddingTaskIds = fileItems+ .map((item) => item.embeddingTaskId)+ .filter(Boolean) as string[];+ const embeddingTasks = await ctx.asyncTaskModel.findByIds(+ embeddingTaskIds,+ AsyncTaskType.Embedding,+ );++ // Combine all items with their metadata+ const resultItems = [] as any[];+ for (const item of knowledgeItems) {+ if (item.sourceType === 'file') {+ const chunkTask = item.chunkTaskId+ ? chunkTasks.find((task) => task.id === item.chunkTaskId)+ : null;+ const embeddingTask = item.embeddingTaskId+ ? embeddingTasks.find((task) => task.id === item.embeddingTaskId)+ : null;++ resultItems.push({+ ...item,+ chunkCount: chunks.find((chunk) => chunk.id === item.id)?.count ?? null,+ chunkingError: chunkTask?.error ?? null,+ chunkingStatus: chunkTask?.status as AsyncTaskStatus,+ editorData: null,+ embeddingError: embeddingTask?.error ?? null,+ embeddingStatus: embeddingTask?.status as AsyncTaskStatus,+ finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,+ url: await ctx.fileService.getFullFileUrl(item.url!),+ } as FileListItem);+ } else {+ // Document item - no chunk processing needed, includes editorData+ const documentItem = {+ ...item,+ chunkCount: null,+ chunkingError: null,+ chunkingStatus: null,+ embeddingError: null,+ embeddingStatus: null,+ finishEmbedding: false,+ } as FileListItem;+ console.log('[API getKnowledgeItems] Processing document:', {+ editorDataPreview: item.editorData ? JSON.stringify(item.editorData).slice(0, 100) : null,+ hasEditorData: !!item.editorData,+ id: item.id,+ name: item.name,+ });+ resultItems.push(documentItem);+ }+ }++ return resultItems;+ }),+removeAllFiles: fileProcedure.mutation(async ({ ctx }) => {return ctx.fileModel.clear();}),diff --git a/src/server/routers/lambda/knowledge.ts b/src/server/routers/lambda/knowledge.tsnew file mode 100644index 00000000000..e92e6cdd781--- /dev/null+++ b/src/server/routers/lambda/knowledge.ts@@ -0,0 +1,94 @@+import { AsyncTaskModel } from '@/database/models/asyncTask';+import { ChunkModel } from '@/database/models/chunk';+import { DocumentModel } from '@/database/models/document';+import { FileModel } from '@/database/models/file';+import { KnowledgeRepo } from '@/database/repositories/knowledge';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { FileService } from '@/server/services/file';+import { AsyncTaskStatus, AsyncTaskType } from '@/types/asyncTask';+import { FileListItem, QueryFileListSchema } from '@/types/files';++const knowledgeProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId),+ chunkModel: new ChunkModel(ctx.serverDB, ctx.userId),+ documentModel: new DocumentModel(ctx.serverDB, ctx.userId),+ fileModel: new FileModel(ctx.serverDB, ctx.userId),+ fileService: new FileService(ctx.serverDB, ctx.userId),+ knowledgeRepo: new KnowledgeRepo(ctx.serverDB, ctx.userId),+ },+ });+});++export const knowledgeRouter = router({+ getKnowledgeItems: knowledgeProcedure.input(QueryFileListSchema).query(async ({ ctx, input }) => {+ const knowledgeItems = await ctx.knowledgeRepo.query(input);++ // Process files (add chunk info and async task status)+ const fileItems = knowledgeItems.filter((item) => item.sourceType === 'file');+ const fileIds = fileItems.map((item) => item.id);+ const chunks = await ctx.chunkModel.countByFileIds(fileIds);++ const chunkTaskIds = fileItems.map((item) => item.chunkTaskId).filter(Boolean) as string[];+ const chunkTasks = await ctx.asyncTaskModel.findByIds(chunkTaskIds, AsyncTaskType.Chunking);++ const embeddingTaskIds = fileItems+ .map((item) => item.embeddingTaskId)+ .filter(Boolean) as string[];+ const embeddingTasks = await ctx.asyncTaskModel.findByIds(+ embeddingTaskIds,+ AsyncTaskType.Embedding,+ );++ // Combine all items with their metadata+ const resultItems = [] as any[];+ for (const item of knowledgeItems) {+ if (item.sourceType === 'file') {+ const chunkTask = item.chunkTaskId+ ? chunkTasks.find((task) => task.id === item.chunkTaskId)+ : null;+ const embeddingTask = item.embeddingTaskId+ ? embeddingTasks.find((task) => task.id === item.embeddingTaskId)+ : null;++ resultItems.push({+ ...item,+ chunkCount: chunks.find((chunk) => chunk.id === item.id)?.count ?? null,+ chunkingError: chunkTask?.error ?? null,+ chunkingStatus: chunkTask?.status as AsyncTaskStatus,+ editorData: null,+ embeddingError: embeddingTask?.error ?? null,+ embeddingStatus: embeddingTask?.status as AsyncTaskStatus,+ finishEmbedding: embeddingTask?.status === AsyncTaskStatus.Success,+ url: await ctx.fileService.getFullFileUrl(item.url!),+ } as FileListItem);+ } else {+ // Document item - no chunk processing needed, includes editorData+ const documentItem = {+ ...item,+ chunkCount: null,+ chunkingError: null,+ chunkingStatus: null,+ embeddingError: null,+ embeddingStatus: null,+ finishEmbedding: false,+ } as FileListItem;+ console.log('[API getKnowledgeItems] Processing document:', {+ editorDataPreview: item.editorData ? JSON.stringify(item.editorData).slice(0, 100) : null,+ hasEditorData: !!item.editorData,+ id: item.id,+ name: item.name,+ });+ resultItems.push(documentItem);+ }+ }++ return resultItems;+ }),+});++export type KnowledgeRouter = typeof knowledgeRouter;diff --git a/src/server/services/document/index.ts b/src/server/services/document/index.tsindex 1e000c428f2..00004e9ad2a 100644--- a/src/server/services/document/index.ts+++ b/src/server/services/document/index.ts@@ -1,4 +1,5 @@import { LobeChatDatabase } from '@lobechat/database';+import { DocumentItem } from '@lobechat/database/schemas';import { loadFile } from '@lobechat/file-loaders';import debug from 'debug';@@ -15,14 +16,116 @@ export class DocumentService {private fileModel: FileModel;private documentModel: DocumentModel;private fileService: FileService;+ private db: LobeChatDatabase;constructor(db: LobeChatDatabase, userId: string) {this.userId = userId;+ this.db = db;this.fileModel = new FileModel(db, userId);this.fileService = new FileService(db, userId);this.documentModel = new DocumentModel(db, userId);}+ /**+ * Create a document+ */+ async createDocument(params: {+ content?: string;+ editorData: Record<string, any>;+ fileType?: string;+ knowledgeBaseId?: string;+ metadata?: Record<string, any>;+ rawData?: string;+ title: string;+ }): Promise<DocumentItem> {+ const {+ content,+ editorData,+ title,+ fileType = 'custom/document',+ metadata,+ knowledgeBaseId,+ } = params;++ // Calculate character and line counts+ const totalCharCount = content?.length || 0;+ const totalLineCount = content?.split('\n').length || 0;++ const document = await this.documentModel.create({+ content,+ editorData,+ fileId: knowledgeBaseId ? null : undefined,+ fileType,+ filename: title,+ metadata,+ pages: undefined,+ source: 'document',+ sourceType: 'api',+ title,+ totalCharCount,+ totalLineCount,+ });++ return document;+ }++ /**+ * Query all documents+ */+ async queryDocuments() {+ return this.documentModel.query();+ }++ /**+ * Get document by ID+ */+ async getDocumentById(id: string) {+ return this.documentModel.findById(id);+ }++ /**+ * Delete document+ */+ async deleteDocument(id: string) {+ return this.documentModel.delete(id);+ }++ /**+ * Update document+ */+ async updateDocument(+ id: string,+ params: {+ content?: string;+ editorData?: Record<string, any>;+ metadata?: Record<string, any>;+ title?: string;+ },+ ) {+ const updates: any = {};++ if (params.content !== undefined) {+ updates.content = params.content;+ updates.totalCharCount = params.content.length;+ updates.totalLineCount = params.content.split('\n').length;+ }++ if (params.editorData !== undefined) {+ updates.editorData = params.editorData;+ }++ if (params.title !== undefined) {+ updates.title = params.title;+ updates.filename = params.title;+ }++ if (params.metadata !== undefined) {+ updates.metadata = params.metadata;+ }++ return this.documentModel.update(id, updates);+ }+/*** 解析文件内容*diff --git a/src/services/document/index.ts b/src/services/document/index.tsnew file mode 100644index 00000000000..d921e81eb33--- /dev/null+++ b/src/services/document/index.ts@@ -0,0 +1,44 @@+import { DocumentItem } from '@lobechat/database/schemas';++import { lambdaClient } from '@/libs/trpc/client';++export interface CreateDocumentParams {+ content?: string;+ editorData: string;+ fileType?: string;+ knowledgeBaseId?: string;+ metadata?: Record<string, any>;+ title: string;+}++export interface UpdateDocumentParams {+ content?: string;+ editorData?: string;+ id: string;+ metadata?: Record<string, any>;+ title?: string;+}++export class DocumentService {+ async createDocument(params: CreateDocumentParams): Promise<DocumentItem> {+ return lambdaClient.document.createDocument.mutate(params);+ }++ async queryDocuments(): Promise<DocumentItem[]> {+ return lambdaClient.document.queryDocuments.query();+ }++ async getDocumentById(id: string): Promise<DocumentItem | undefined> {+ return lambdaClient.document.getDocumentById.query({ id });+ }++ async deleteDocument(id: string): Promise<void> {+ await lambdaClient.document.deleteDocument.mutate({ id });+ }++ async updateDocument(params: UpdateDocumentParams): Promise<void> {+ await lambdaClient.document.updateDocument.mutate(params);+ }+}++export const documentService = new DocumentService();diff --git a/src/services/file/index.ts b/src/services/file/index.tsindex 6f9d7d4763e..a8b84271ec3 100644--- a/src/services/file/index.ts+++ b/src/services/file/index.ts@@ -42,11 +42,13 @@ export class FileService {await lambdaClient.file.removeAllFiles.mutate();};- getFiles = async (params: QueryFileListParams) => {- return lambdaClient.file.getFiles.query(params as QueryFileListSchemaType);+ // V2.0 Migrate from getFiles to getKnowledgeItems+ getKnowledgeItems = async (params: QueryFileListParams) => {+ return lambdaClient.file.getKnowledgeItems.query(params as QueryFileListSchemaType);};- getFileItem = async (id: string) => {+ // V2.0 Migrate from getFileItem to getKnowledgeItem+ getKnowledgeItem = async (id: string) => {return lambdaClient.file.getFileItemById.query({ id });};diff --git a/src/store/file/initialState.ts b/src/store/file/initialState.tsindex b9524936daf..1b6f7611546 100644--- a/src/store/file/initialState.ts+++ b/src/store/file/initialState.ts@@ -1,11 +1,16 @@import { ImageFileState, initialImageFileState } from './slices/chat';import { FileChunkState, initialFileChunkState } from './slices/chunk';+import { DocumentState, initialDocumentState } from './slices/document';import { FileManagerState, initialFileManagerState } from './slices/fileManager';-export type FilesStoreState = ImageFileState & FileManagerState & FileChunkState;+export type FilesStoreState = ImageFileState &+ DocumentState &+ FileManagerState &+ FileChunkState;export const initialState: FilesStoreState = {...initialImageFileState,+ ...initialDocumentState,...initialFileManagerState,...initialFileChunkState,};diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex f1bd298aee7..cf88687189a 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -23,14 +23,12 @@ const n = setNamespace('chat');export interface FileAction {clearChatUploadFileList: () => void;dispatchChatUploadFileList: (payload: UploadFileListDispatch) => void;-removeChatUploadFile: (id: string) => Promise<void>;startAsyncTask: (fileId: string,runner: (id: string) => Promise<string>,onFileItemChange: (fileItem: FileListItem) => void,) => Promise<void>;-uploadChatFiles: (files: File[]) => Promise<void>;}@@ -43,12 +41,14 @@ export const createFileSlice: StateCreator<clearChatUploadFileList: () => {set({ chatUploadFileList: [] }, false, n('clearChatUploadFileList'));},+dispatchChatUploadFileList: (payload) => {const nextValue = uploadFileListReducer(get().chatUploadFileList, payload);if (nextValue === get().chatUploadFileList) return;set({ chatUploadFileList: nextValue }, false, `dispatchChatFileList/${payload.type}`);},+removeChatUploadFile: async (id) => {const { dispatchChatUploadFileList } = get();@@ -68,7 +68,7 @@ export const createFileSlice: StateCreator<let fileItem: FileListItem | undefined = undefined;try {- fileItem = await fileService.getFileItem(id);+ fileItem = await fileService.getKnowledgeItem(id);} catch (e) {console.error('getFileItem Error:', e);continue;diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.tsnew file mode 100644index 00000000000..056e4e2eb8e--- /dev/null+++ b/src/store/file/slices/document/action.ts@@ -0,0 +1,359 @@+import { StateCreator } from 'zustand/vanilla';++import { documentService } from '@/services/document';+import { DocumentSourceType, LobeDocument } from '@/types/document';+import { setNamespace } from '@/utils/storeDebug';++import { FileStore } from '../../store';++const n = setNamespace('document');++const ALLOWED_DOCUMENT_SOURCE_TYPES = new Set(['editor', 'file', 'api']);+const ALLOWED_DOCUMENT_FILE_TYPES = new Set(['custom/document', 'application/pdf']);+const EDITOR_DOCUMENT_FILE_TYPE = 'custom/document';++/**+ * Check if a document should be displayed in the document list+ */+const isAllowedDocument = (document: { fileType: string; sourceType: string }) => {+ return (+ ALLOWED_DOCUMENT_SOURCE_TYPES.has(document.sourceType) &&+ ALLOWED_DOCUMENT_FILE_TYPES.has(document.fileType)+ );+};++export interface DocumentAction {+ /**+ * Create a new document with markdown content (not optimistic, waits for server response)+ * Returns the created document+ */+ createDocument: (params: {+ content: string;+ knowledgeBaseId?: string;+ title: string;+ }) => Promise<{ [key: string]: any; id: string }>;+ /**+ * Create a new optimistic document immediately in local map+ * Returns the temporary ID for the new document+ */+ createOptimisticDocument: (title?: string) => string;+ /**+ * Duplicate an existing document+ * Returns the created document+ */+ duplicateDocument: (documentId: string) => Promise<{ [key: string]: any; id: string }>;+ /**+ * Fetch all documents from the server+ */+ fetchDocuments: () => Promise<void>;+ /**+ * Get documents from local optimistic map merged with server data+ */+ getOptimisticDocuments: () => LobeDocument[];+ /**+ * Remove a document (deletes from documents table)+ */+ removeDocument: (documentId: string) => Promise<void>;+ /**+ * Remove a temp document from local map+ */+ removeTempDocument: (tempId: string) => void;+ /**+ * Replace a temp document with real document data (for smooth UX when creating documents)+ */+ replaceTempDocumentWithReal: (tempId: string, realDocument: LobeDocument) => void;+ /**+ * Optimistically update document in local map and queue for DB sync+ */+ updateDocumentOptimistically: (+ documentId: string,+ updates: Partial<LobeDocument>,+ ) => Promise<void>;+}++export const createDocumentSlice: StateCreator<+ FileStore,+ [['zustand/devtools', never]],+ [],+ DocumentAction+> = (set, get) => ({+ createDocument: async ({ title, content, knowledgeBaseId }) => {+ const now = Date.now();++ // Create document with markdown content, leave editorData as empty JSON object+ const newDoc = await documentService.createDocument({+ content,+ editorData: '{}', // Empty JSON object instead of empty string+ fileType: EDITOR_DOCUMENT_FILE_TYPE,+ knowledgeBaseId,+ metadata: {+ createdAt: now,+ },+ title,+ });++ // Don't refresh documents here - the caller will handle replacing the temp document+ // with the real one via replaceTempDocumentWithReal, which provides a smooth UX+ // without triggering the loading skeleton++ return newDoc;+ },++ createOptimisticDocument: (title = 'Untitled') => {+ const { localDocumentMap } = get();++ // Generate temporary ID with prefix to identify optimistic documents+ const tempId = `temp-document-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;+ const now = new Date();++ const newDocument: LobeDocument = {+ content: null,+ createdAt: now,+ editorData: null,+ fileType: EDITOR_DOCUMENT_FILE_TYPE,+ filename: title,+ id: tempId,+ metadata: {},+ source: 'document',+ sourceType: DocumentSourceType.EDITOR,+ title: title,+ totalCharCount: 0,+ totalLineCount: 0,+ updatedAt: now,+ };++ // Add to local map+ const newMap = new Map(localDocumentMap);+ newMap.set(tempId, newDocument);+ set({ localDocumentMap: newMap }, false, n('createOptimisticDocument'));++ return tempId;+ },++ duplicateDocument: async (documentId) => {+ // Fetch the source document+ const sourceDoc = await documentService.getDocumentById(documentId);++ if (!sourceDoc) {+ throw new Error(`Document with ID ${documentId} not found`);+ }++ // Create a new document with copied properties+ const newDoc = await documentService.createDocument({+ content: sourceDoc.content || '',+ editorData: sourceDoc.editorData+ ? typeof sourceDoc.editorData === 'string'+ ? sourceDoc.editorData+ : JSON.stringify(sourceDoc.editorData)+ : '{}',+ fileType: sourceDoc.fileType,+ metadata: {+ ...sourceDoc.metadata,+ createdAt: Date.now(),+ duplicatedFrom: documentId,+ },+ title: `${sourceDoc.title} (Copy)`,+ });++ // Add the new document to local map immediately for instant UI update+ const { localDocumentMap } = get();+ const newMap = new Map(localDocumentMap);+ const editorDoc: LobeDocument = {+ content: newDoc.content || null,+ createdAt: newDoc.createdAt ? new Date(newDoc.createdAt) : new Date(),+ editorData:+ typeof newDoc.editorData === 'string'+ ? JSON.parse(newDoc.editorData)+ : newDoc.editorData || null,+ fileType: newDoc.fileType,+ filename: newDoc.title || newDoc.filename || '',+ id: newDoc.id,+ metadata: newDoc.metadata || {},+ source: 'document',+ sourceType: DocumentSourceType.EDITOR,+ title: newDoc.title || '',+ totalCharCount: newDoc.content?.length || 0,+ totalLineCount: 0,+ updatedAt: newDoc.updatedAt ? new Date(newDoc.updatedAt) : new Date(),+ };+ newMap.set(newDoc.id, editorDoc);+ set({ localDocumentMap: newMap }, false, n('duplicateDocument'));++ // Don't refresh documents here - we've already added it to the local map+ // This prevents the loading skeleton from appearing++ return newDoc;+ },++ fetchDocuments: async () => {+ set({ isDocumentListLoading: true }, false, n('fetchDocuments/start'));++ try {+ const documentItems = await documentService.queryDocuments();+ const documents = documentItems.filter(isAllowedDocument).map((doc) => ({+ ...doc,+ filename: doc.filename ?? doc.title ?? 'Untitled',+ })) as LobeDocument[];+ set({ documents, isDocumentListLoading: false }, false, n('fetchDocuments/success'));++ // Sync with local map: remove temp documents that now exist on server+ const { localDocumentMap } = get();+ const newMap = new Map(localDocumentMap);++ for (const [id] of localDocumentMap.entries()) {+ if (id.startsWith('temp-document-')) {+ newMap.delete(id);+ }+ }++ set({ localDocumentMap: newMap }, false, n('fetchDocuments/syncLocalMap'));+ } catch (error) {+ console.error('Failed to fetch documents:', error);+ set({ isDocumentListLoading: false }, false, n('fetchDocuments/error'));+ throw error;+ }+ },++ getOptimisticDocuments: () => {+ const { localDocumentMap, documents } = get();++ // Track which documents we've added+ const addedIds = new Set<string>();++ // Create result array - start with server documents+ const result: LobeDocument[] = documents.map((document) => {+ addedIds.add(document.id);+ // Check if we have a local optimistic update for this document+ const localUpdate = localDocumentMap.get(document.id);+ // If local update exists and is newer, use it; otherwise use server version+ if (localUpdate && new Date(localUpdate.updatedAt) >= new Date(document.updatedAt)) {+ return localUpdate;+ }+ return document;+ });++ // Add any optimistic documents that aren't in server list yet (e.g., newly created temp documents)+ for (const [id, document] of localDocumentMap.entries()) {+ if (!addedIds.has(id)) {+ result.unshift(document); // Add new documents to the beginning+ }+ }++ return result;+ },++ removeDocument: async (documentId) => {+ // Remove from local optimistic map first (optimistic update)+ const { localDocumentMap, documents } = get();+ const newMap = new Map(localDocumentMap);+ newMap.delete(documentId);++ // Also remove from documents array to update the list immediately+ const newDocuments = documents.filter((doc) => doc.id !== documentId);++ set(+ { documents: newDocuments, localDocumentMap: newMap },+ false,+ n('removeDocument/optimistic'),+ );++ try {+ // Delete from documents table+ await documentService.deleteDocument(documentId);+ // No need to call fetchDocuments() - optimistic update is enough+ } catch (error) {+ console.error('Failed to delete document:', error);+ // Restore the document in local map and documents array on error+ const restoredMap = new Map(localDocumentMap);+ set({ documents, localDocumentMap: restoredMap }, false, n('removeDocument/restore'));+ throw error;+ }+ },++ removeTempDocument: (tempId) => {+ const { localDocumentMap } = get();+ const newMap = new Map(localDocumentMap);+ newMap.delete(tempId);+ set({ localDocumentMap: newMap }, false, n('removeTempDocument'));+ },++ replaceTempDocumentWithReal: (tempId, realDocument) => {+ const { localDocumentMap } = get();+ const newMap = new Map(localDocumentMap);++ // Remove temp document+ newMap.delete(tempId);++ // Add real document with same position+ newMap.set(realDocument.id, realDocument);++ set({ localDocumentMap: newMap }, false, n('replaceTempDocumentWithReal'));+ },++ updateDocumentOptimistically: async (documentId, updates) => {+ const { localDocumentMap, documents } = get();++ // Find the document either in local map or documents state+ let existingDocument = localDocumentMap.get(documentId);+ if (!existingDocument) {+ existingDocument = documents.find((doc) => doc.id === documentId);+ }++ if (!existingDocument) {+ console.warn('[updateDocumentOptimistically] Document not found:', documentId);+ return;+ }++ // Create updated document with new timestamp+ // Merge metadata if both exist, otherwise use the update's metadata or preserve existing+ const mergedMetadata =+ updates.metadata !== undefined+ ? { ...existingDocument.metadata, ...updates.metadata }+ : existingDocument.metadata;++ // Clean up undefined values from metadata+ const cleanedMetadata = mergedMetadata+ ? Object.fromEntries(Object.entries(mergedMetadata).filter(([, v]) => v !== undefined))+ : {};++ const updatedDocument: LobeDocument = {+ ...existingDocument,+ ...updates,+ metadata: cleanedMetadata,+ title: updates.title || existingDocument.title,+ updatedAt: new Date(),+ };++ // Update local map immediately for optimistic UI+ const newMap = new Map(localDocumentMap);+ newMap.set(documentId, updatedDocument);+ set({ localDocumentMap: newMap }, false, n('updateDocumentOptimistically'));++ // Queue background sync to DB+ try {+ await documentService.updateDocument({+ content: updatedDocument.content || '',+ editorData:+ typeof updatedDocument.editorData === 'string'+ ? updatedDocument.editorData+ : JSON.stringify(updatedDocument.editorData || {}),+ id: documentId,+ metadata: updatedDocument.metadata || {},+ title: updatedDocument.title || updatedDocument.filename,+ });++ // After successful sync, refresh file list to get server state+ // This will eventually sync back to the map via syncDocumentMapWithServer+ } catch (error) {+ console.error('[updateDocumentOptimistically] Failed to sync to DB:', error);+ // On error, revert the optimistic update+ const revertMap = new Map(localDocumentMap);+ if (existingDocument) {+ revertMap.set(documentId, existingDocument);+ } else {+ revertMap.delete(documentId);+ }+ set({ localDocumentMap: revertMap }, false, n('revertOptimisticUpdate'));+ }+ },+});diff --git a/src/store/file/slices/document/index.ts b/src/store/file/slices/document/index.tsnew file mode 100644index 00000000000..6bdd1f4b2ef--- /dev/null+++ b/src/store/file/slices/document/index.ts@@ -0,0 +1,3 @@+export * from './action';+export * from './initialState';+export * from './selectors';diff --git a/src/store/file/slices/document/initialState.ts b/src/store/file/slices/document/initialState.tsnew file mode 100644index 00000000000..ee199713a93--- /dev/null+++ b/src/store/file/slices/document/initialState.ts@@ -0,0 +1,22 @@+import { LobeDocument } from '@/types/document';++export interface DocumentState {+ /**+ * Server documents fetched from document service+ */+ documents: LobeDocument[];+ /**+ * Loading state for document fetching+ */+ isDocumentListLoading: boolean;+ /**+ * Local optimistic document map for immediate UI updates+ */+ localDocumentMap: Map<string, LobeDocument>;+}++export const initialDocumentState: DocumentState = {+ documents: [],+ isDocumentListLoading: false,+ localDocumentMap: new Map(),+};diff --git a/src/store/file/slices/document/selectors.ts b/src/store/file/slices/document/selectors.tsnew file mode 100644index 00000000000..ed01f44d0db--- /dev/null+++ b/src/store/file/slices/document/selectors.ts@@ -0,0 +1,25 @@+import { FilesStoreState } from '../../initialState';++const getDocumentById = (documentId: string | undefined) => (s: FilesStoreState) => {+ if (!documentId) return undefined;++ // First check local optimistic map+ const localDocument = s.localDocumentMap.get(documentId);++ // Then check server documents+ const serverDocument = s.documents.find((doc) => doc.id === documentId);++ // If both exist, prefer the local update if it's newer+ if (localDocument && serverDocument) {+ return new Date(localDocument.updatedAt) >= new Date(serverDocument.updatedAt)+ ? localDocument+ : serverDocument;+ }++ // Return whichever exists, or undefined if neither exists+ return localDocument || serverDocument;+};++export const documentSelectors = {+ getDocumentById,+};diff --git a/src/store/file/slices/fileManager/action.test.ts b/src/store/file/slices/fileManager/action.test.tsindex 304ed1d4347..86a097ef9f7 100644--- a/src/store/file/slices/fileManager/action.test.ts+++ b/src/store/file/slices/fileManager/action.test.ts@@ -61,6 +61,7 @@ vi.mock('@/libs/trpc/client', () => ({file: {getFileItemById: { query: vi.fn() },getFiles: { query: vi.fn() },+ getKnowledgeItems: { query: vi.fn() },removeFileAsyncTask: { mutate: vi.fn() },},},@@ -610,7 +611,7 @@ describe('FileManagerActions', () => {await result.current.refreshFileList();});- expect(mutate).toHaveBeenCalledWith(['useFetchFileManage', params]);+ expect(mutate).toHaveBeenCalledWith(['useFetchKnowledgeItems', params]);});it('should call mutate with undefined params', async () => {@@ -620,7 +621,7 @@ describe('FileManagerActions', () => {await result.current.refreshFileList();});- expect(mutate).toHaveBeenCalledWith(['useFetchFileManage', undefined]);+ expect(mutate).toHaveBeenCalledWith(['useFetchKnowledgeItems', undefined]);});});@@ -802,7 +803,7 @@ describe('FileManagerActions', () => {it('should not fetch when id is undefined', () => {const { result } = renderHook(() => useStore());- renderHook(() => result.current.useFetchFileItem(undefined));+ renderHook(() => result.current.useFetchKnowledgeItem(undefined));expect(lambdaClient.file.getFileItemById.query).not.toHaveBeenCalled();});@@ -820,13 +821,16 @@ describe('FileManagerActions', () => {id: 'file-1',name: 'test.txt',size: 100,+ sourceType: 'file',updatedAt: new Date(),url: 'http://example.com/test.txt',};vi.mocked(lambdaClient.file.getFileItemById.query).mockResolvedValue(mockFile);- const { result: swrResult } = renderHook(() => result.current.useFetchFileItem('file-1'));+ const { result: swrResult } = renderHook(() =>+ result.current.useFetchKnowledgeItem('file-1'),+ );await waitFor(() => {expect(swrResult.current.data).toEqual(mockFile);@@ -834,7 +838,7 @@ describe('FileManagerActions', () => {});});- describe('useFetchFileManage', () => {+ describe('useFetchKnowledgeItems', () => {it('should fetch file list with params', async () => {const { result } = renderHook(() => useStore());@@ -849,6 +853,7 @@ describe('FileManagerActions', () => {id: 'file-1',name: 'test1.txt',size: 100,+ sourceType: 'file',updatedAt: new Date(),url: 'http://example.com/test1.txt',},@@ -862,15 +867,16 @@ describe('FileManagerActions', () => {id: 'file-2',name: 'test2.txt',size: 200,+ sourceType: 'file',updatedAt: new Date(),url: 'http://example.com/test2.txt',},];- vi.mocked(lambdaClient.file.getFiles.query).mockResolvedValue(mockFiles);+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue(mockFiles);const params = { category: 'all' as any };- const { result: swrResult } = renderHook(() => result.current.useFetchFileManage(params));+ const { result: swrResult } = renderHook(() => result.current.useFetchKnowledgeItems(params));await waitFor(() => {expect(swrResult.current.data).toEqual(mockFiles);@@ -891,15 +897,16 @@ describe('FileManagerActions', () => {id: 'file-1',name: 'test.txt',size: 100,+ sourceType: 'file',updatedAt: new Date(),url: 'http://example.com/test.txt',},];- vi.mocked(lambdaClient.file.getFiles.query).mockResolvedValue(mockFiles);+ vi.mocked(lambdaClient.file.getKnowledgeItems.query).mockResolvedValue(mockFiles);const params = { category: 'all' as any };- renderHook(() => result.current.useFetchFileManage(params));+ renderHook(() => result.current.useFetchKnowledgeItems(params));await waitFor(() => {expect(result.current.fileList).toEqual(mockFiles);diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.tsindex 0eef4fea590..202a5384428 100644--- a/src/store/file/slices/fileManager/action.ts+++ b/src/store/file/slices/fileManager/action.ts@@ -4,7 +4,7 @@ import { StateCreator } from 'zustand/vanilla';import { FILE_UPLOAD_BLACKLIST, MAX_UPLOAD_FILE_COUNT } from '@/const/file';import { useClientDataSWR } from '@/libs/swr';-import { fileService , FileService } from '@/services/file';+import { FileService, fileService } from '@/services/file';import { ragService } from '@/services/rag';import {UploadFileListDispatch,@@ -35,11 +35,11 @@ export interface FileManageAction {toggleEmbeddingIds: (ids: string[], loading?: boolean) => void;toggleParsingIds: (ids: string[], loading?: boolean) => void;- useFetchFileItem: (id?: string) => SWRResponse<FileListItem | undefined>;- useFetchFileManage: (params: QueryFileListParams) => SWRResponse<FileListItem[]>;+ useFetchKnowledgeItem: (id?: string) => SWRResponse<FileListItem | undefined>;+ useFetchKnowledgeItems: (params: QueryFileListParams) => SWRResponse<FileListItem[]>;}-const FETCH_FILE_LIST_KEY = 'useFetchFileManage';+const FETCH_ALL_KNOWLEDGE_KEY = 'useFetchKnowledgeItems';export const createFileManageSlice: StateCreator<FileStore,@@ -171,7 +171,7 @@ export const createFileManageSlice: StateCreator<get().toggleParsingIds([id], false);},refreshFileList: async () => {- await mutate([FETCH_FILE_LIST_KEY, get().queryListParams]);+ await mutate([FETCH_ALL_KNOWLEDGE_KEY, get().queryListParams]);},removeAllFiles: async () => {await fileService.removeAllFiles();@@ -220,15 +220,15 @@ export const createFileManageSlice: StateCreator<});},- useFetchFileItem: (id) =>- useClientDataSWR<FileListItem | undefined>(!id ? null : ['useFetchFileItem', id], () =>- serverFileService.getFileItem(id!),+ useFetchKnowledgeItem: (id) =>+ useClientDataSWR<FileListItem | undefined>(!id ? null : ['useFetchKnowledgeItem', id], () =>+ serverFileService.getKnowledgeItem(id!),),- useFetchFileManage: (params) =>+ useFetchKnowledgeItems: (params) =>useClientDataSWR<FileListItem[]>(- [FETCH_FILE_LIST_KEY, params],- () => serverFileService.getFiles(params),+ [FETCH_ALL_KNOWLEDGE_KEY, params],+ () => serverFileService.getKnowledgeItems(params),{onSuccess: (data) => {set({ fileList: data, queryListParams: params });diff --git a/src/store/file/store.ts b/src/store/file/store.tsindex e2821ab419a..8e0d27513ae 100644--- a/src/store/file/store.ts+++ b/src/store/file/store.ts@@ -6,6 +6,7 @@ import { createDevtools } from '../middleware/createDevtools';import { FilesStoreState, initialState } from './initialState';import { FileAction, createFileSlice } from './slices/chat';import { FileChunkAction, createFileChunkSlice } from './slices/chunk';+import { DocumentAction, createDocumentSlice } from './slices/document';import { FileManageAction, createFileManageSlice } from './slices/fileManager';import { TTSFileAction, createTTSFileSlice } from './slices/tts';import { FileUploadAction, createFileUploadSlice } from './slices/upload/action';@@ -14,6 +15,7 @@ import { FileUploadAction, createFileUploadSlice } from './slices/upload/action'export type FileStore = FilesStoreState &FileAction &+ DocumentAction &TTSFileAction &FileManageAction &FileChunkAction &@@ -22,6 +24,7 @@ export type FileStore = FilesStoreState &const createStore: StateCreator<FileStore, [['zustand/devtools', never]]> = (...parameters) => ({...initialState,...createFileSlice(...parameters),+ ...createDocumentSlice(...parameters),...createFileManageSlice(...parameters),...createTTSFileSlice(...parameters),...createFileChunkSlice(...parameters),diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 824bd89d469..2a0f89b8466 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -9,7 +9,7 @@ import { AsyncLocalStorage } from '@/utils/localStorage';export enum SidebarTabKey {Chat = 'chat',Discover = 'discover',- Files = 'files',+ Files = 'knowledge',Image = 'image',Me = 'me',Setting = 'settings',@@ -72,6 +72,7 @@ export interface SystemStatus {*/isEnablePglite?: boolean;isShowCredit?: boolean;+ knowledgeBaseModalViewMode?: 'list' | 'masonry';language?: LocaleMode;/*** 记住用户最后选择的图像生成模型@@ -142,6 +143,7 @@ export const INITIAL_STATUS = {hideThreadLimitAlert: false,imagePanelWidth: 320,imageTopicPanelWidth: 80,+ knowledgeBaseModalViewMode: 'list' as const,mobileShowTopic: false,noWideScreen: true,portalWidth: 400,