Skip to content

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

fix: Resource manager (#12040)

René Wang8dd8ff929f4c
diff --git a/docs/usage/getting-started/lobe-ai.mdx b/docs/usage/getting-started/lobe-ai.mdx
index 9156b96d49b..8c022deb7dc 100644
--- a/docs/usage/getting-started/lobe-ai.mdx
+++ b/docs/usage/getting-started/lobe-ai.mdx
@@ -1,8 +1,9 @@
---
title: Lobe AI
description: >-
- Use Lobe AI to handle your daily tasks, including checking the weather,
- setting reminders, reading news, managing emails, and more.
+ Use Lobe AI to handle your daily tasks, including checking the weather, setting reminders, reading news, managing emails, and more.
+
+
tags:
- LobeHub
- Lobe AI
@@ -29,6 +30,6 @@ If you have specific needs, you can create a [custom assistant](/docs/usage/gett
Lobe AI comes with a variety of built-in tools to help you complete tasks more efficiently:
-- [GTD](/docs/usage/agents/gtd)
-- [Plan](/docs/usage/agents/plan)
-- [Notebook](/docs/usage/agents/notebook)
+- [GTD](/docs/usage/agent/gtd)
+- [Plan](/docs/usage/agent/plan)
+- [Notebook](/docs/usage/agent/notebook)
diff --git a/docs/usage/getting-started/lobe-ai.zh-CN.mdx b/docs/usage/getting-started/lobe-ai.zh-CN.mdx
index 07ddafb15fe..a45fe150533 100644
--- a/docs/usage/getting-started/lobe-ai.zh-CN.mdx
+++ b/docs/usage/getting-started/lobe-ai.zh-CN.mdx
@@ -27,6 +27,6 @@ Lobe AI 可以帮助你完成多种日常任务,例如:
Lobe AI 集成了多种内置工具,帮助你更高效地完成任务:
-- [GTD](/docs/usage/agents/gtd)
-- [Plan](/docs/usage/agents/plan)
-- [Notebook](/docs/usage/agents/notebook)
+- [GTD](/docs/usage/agent/gtd)
+- [Plan](/docs/usage/agent/plan)
+- [Notebook](/docs/usage/agent/notebook)
diff --git a/docs/usage/start.mdx b/docs/usage/start.mdx
index 3632411b892..2fd31571637 100644
--- a/docs/usage/start.mdx
+++ b/docs/usage/start.mdx
@@ -2,7 +2,6 @@
title: Getting Started
description: Getting started with LobeHub
tags:
- - LobeHub
- LobeHub
- Features
- Visual Recognition
@@ -18,16 +17,18 @@ tags:
Welcome to the official LobeHub User Guide.
<Callout type="info">
- For self-hosting assistance, please visit the [Self-Hosting Guide](/docs/self-hosting/start). For developer resources, check out the [Developer Guide](/docs/development/start).
+ For self-hosting, please visit the [Self-Hosting Guide](/docs/self-hosting/start). For developer
+ resources, check out the [Developer Guide](/docs/development/start).
</Callout>
## Getting Started
-- [Create Your First Agent](/docs/usage/getting-started/page)
-- [Create Your First Team](/docs/usage/getting-started/lobe-ai)
+- [Try Lobe AI](/docs/usage/getting-started/lobe-ai)
+- [Create Your First Agent](/docs/usage/getting-started/agent)
+- [Create Your First Team](/docs/usage/agent/agent-team)
- [Explore the LobeHub Community](/docs/usage/community/agent-market)
- [Migrate from v1.x Local Database to v2.x (Cloud / Self-hosted)](/docs/usage/migrate-from-local-database)
## Help & Support
-If you need assistance, please refer to our [Help & Support](/docs/usage/help) section.
+If you need help, please refer to our [Help & Support](/docs/usage/help) section.
diff --git a/docs/usage/start.zh-CN.mdx b/docs/usage/start.zh-CN.mdx
index 23bfc5e6979..d3de77c6fe8 100644
--- a/docs/usage/start.zh-CN.mdx
+++ b/docs/usage/start.zh-CN.mdx
@@ -2,7 +2,6 @@
title: 开始
description: 上手使用 LobeHub
tags:
- - LobeHub
- LobeHub
- 功能特性
- 视觉识别
@@ -23,8 +22,9 @@ tags:
## 开始
-- [创建你的第一个 Agent](/docs/usage/getting-started/page)
-- [创建你的第一个 Team](/docs/usage/getting-started/lobe-ai)
+- [使用 Lobe AI](/docs/usage/getting-started/lobe-ai)
+- [创建你的第一个 Agent](/docs/usage/getting-started/agent)
+- [创建你的第一个 Team](/docs/usage/agent/agent-team)
- [探索 LobeHub 社区](/docs/usage/community/agent-market)
- [从 v1.x 本地数据库迁移到 v2.x(云端 / 自部署)](/docs/usage/migrate-from-local-database)
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index d317baa4328..7ef15327473 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -6,8 +6,8 @@
"DragUpload.dragFileDesc": "Drag and drop images and files here to upload multiple images and files.",
"DragUpload.dragFileTitle": "Upload Files",
"DragUpload.dragTitle": "Upload Images",
- "FileManager.actions.addToKnowledgeBase": "Add to Library",
- "FileManager.actions.addToOtherKnowledgeBase": "Add to another Library",
+ "FileManager.actions.addToLibrary": "Add to Library",
+ "FileManager.actions.moveToOtherLibrary": "Move to another Library",
"FileManager.actions.batchChunking": "Batch Chunking",
"FileManager.actions.chunking": "Chunking",
"FileManager.actions.chunkingTooltip": "Split the file into multiple text chunks and embedding them for semantic search and file dialogue.",
@@ -15,7 +15,7 @@
"FileManager.actions.confirmDelete": "You are about to delete this file. Once deleted, it cannot be recovered. Please confirm your action.",
"FileManager.actions.confirmDeleteFolder": "You are about to delete this folder and all of its contents. This action cannot be undone. Please confirm your decision.",
"FileManager.actions.confirmDeleteMultiFiles": "You are about to delete the selected {{count}} files. Once deleted, they cannot be recovered. Please confirm your action.",
- "FileManager.actions.confirmRemoveFromKnowledgeBase": "You’re about to remove {{count}} selected file(s) from the Library. They’ll still be available in All Files. Confirm to continue.",
+ "FileManager.actions.confirmRemoveFromLibrary": "You're about to remove {{count}} selected file(s) from the Library. They'll still be available in All Files. Confirm to continue.",
"FileManager.actions.copyUrl": "Copy Link",
"FileManager.actions.copyUrlSuccess": "File url copied successfully.",
"FileManager.actions.createChunkingTask": "Preparing...",
@@ -30,13 +30,13 @@
"FileManager.actions.moveToFolder": "Move to...",
"FileManager.actions.moveToRoot": "Move to root directory",
"FileManager.actions.moving": "Moving...",
- "FileManager.actions.removeFromKnowledgeBase": "Remove from Library",
- "FileManager.actions.removeFromKnowledgeBaseSuccess": "File removed successfully.",
+ "FileManager.actions.removeFromLibrary": "Remove from Library",
+ "FileManager.actions.removeFromLibrarySuccess": "File removed successfully.",
"FileManager.actions.rename": "Rename",
"FileManager.actions.renameError": "Rename failed",
"FileManager.actions.renameSuccess": "Rename successful",
"FileManager.bottom": "You've reached the end.",
- "FileManager.config.showFilesInKnowledgeBase": "Show content in Library",
+ "FileManager.config.showFilesInLibrary": "Show content in Library",
"FileManager.emptyStatus.actions.file": "Upload File",
"FileManager.emptyStatus.actions.folder": "Upload Folder",
"FileManager.emptyStatus.actions.knowledgeBase": "Create Library",
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index 6d6e3a389c9..8b8a6657370 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -9,6 +9,7 @@
"detail.basic.type": "Format",
"detail.basic.updatedAt": "Update Time",
"detail.data.chunkCount": "Chunks",
+ "detail.data.noChunk": "No chunk",
"detail.data.embedding.default": "Not embedding",
"detail.data.embedding.error": "Failed",
"detail.data.embedding.pending": "Pending start",
diff --git a/locales/en-US/knowledgeBase.json b/locales/en-US/knowledgeBase.json
index 419e16e7504..a9cfbc82d34 100644
--- a/locales/en-US/knowledgeBase.json
+++ b/locales/en-US/knowledgeBase.json
@@ -1,5 +1,6 @@
{
"addToKnowledgeBase.addSuccess": "File added successfully",
+ "addToKnowledgeBase.alreadyExists": "This file is already in the library",
"addToKnowledgeBase.confirm": "Add",
"addToKnowledgeBase.error": "Failed to add file to Library",
"addToKnowledgeBase.id.placeholder": "Please select a library to add to",
@@ -7,6 +8,8 @@
"addToKnowledgeBase.id.title": "Target Library",
"addToKnowledgeBase.title": "Add to Library",
"addToKnowledgeBase.totalFiles": "{{count}} files selected",
+ "moveToKnowledgeBase.error": "Failed to move file to Library",
+ "moveToKnowledgeBase.success": "File moved successfully",
"createNew.confirm": "Create New",
"createNew.description.placeholder": "Library description (optional)",
"createNew.formTitle": "Basic Information",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index be9ee8ce641..c8aeea61acb 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -7,7 +7,7 @@
"DragUpload.dragFileTitle": "上传文件",
"DragUpload.dragTitle": "上传图片",
"FileManager.actions.addToKnowledgeBase": "添加到资源库",
- "FileManager.actions.addToOtherKnowledgeBase": "添加到其他资源库",
+ "FileManager.actions.moveToOtherKnowledgeBase": "移动到其他资源库",
"FileManager.actions.batchChunking": "批量分块",
"FileManager.actions.chunking": "分块",
"FileManager.actions.chunkingTooltip": "将文件拆分为多个文本块并向量化后,可用于语义检索和文件对话",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 5e308ad1f6f..9191eedc66f 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -9,6 +9,7 @@
"detail.basic.type": "格式",
"detail.basic.updatedAt": "更新时间",
"detail.data.chunkCount": "分块数",
+ "detail.data.noChunk": "无分块",
"detail.data.embedding.default": "暂未向量化",
"detail.data.embedding.error": "失败",
"detail.data.embedding.pending": "待启动",
diff --git a/locales/zh-CN/knowledgeBase.json b/locales/zh-CN/knowledgeBase.json
index a67d1ddafa8..25f329e711f 100644
--- a/locales/zh-CN/knowledgeBase.json
+++ b/locales/zh-CN/knowledgeBase.json
@@ -1,5 +1,6 @@
{
"addToKnowledgeBase.addSuccess": "文件添加成功",
+ "addToKnowledgeBase.alreadyExists": "该文件已在此资源库中",
"addToKnowledgeBase.confirm": "添加",
"addToKnowledgeBase.error": "添加文件到资源库失败",
"addToKnowledgeBase.id.placeholder": "请选择要添加的资源库",
@@ -7,6 +8,8 @@
"addToKnowledgeBase.id.title": "目标资源库",
"addToKnowledgeBase.title": "添加到资源库",
"addToKnowledgeBase.totalFiles": "已选择 {{count}} 个文件",
+ "moveToKnowledgeBase.error": "移动文件到资源库失败",
+ "moveToKnowledgeBase.success": "文件移动成功",
"createNew.confirm": "新建",
"createNew.description.placeholder": "资源库简介(选填)",
"createNew.formTitle": "基本信息",
diff --git a/packages/database/src/models/__tests__/knowledgeBase.test.ts b/packages/database/src/models/__tests__/knowledgeBase.test.ts
index dcce46ba388..8d2d7076d7e 100644
--- a/packages/database/src/models/__tests__/knowledgeBase.test.ts
+++ b/packages/database/src/models/__tests__/knowledgeBase.test.ts
@@ -206,7 +206,20 @@ describe('KnowledgeBaseModel', () => {
},
]);
- // Create document first
+ // Create mirror file first (document references it via fileId)
+ await serverDB.insert(files).values([
+ {
+ id: 'file1',
+ name: 'document.pdf',
+ url: 'https://example.com/document.pdf',
+ fileHash: 'hash1',
+ size: 1000,
+ fileType: 'application/pdf',
+ userId,
+ },
+ ]);
+
+ // Create document with fileId pointing to the mirror file
await serverDB.insert(documents).values([
{
id: 'docs_test123',
@@ -217,20 +230,7 @@ describe('KnowledgeBaseModel', () => {
totalLineCount: 10,
sourceType: 'file',
source: 'test.pdf',
- userId,
- },
- ]);
-
- // Create mirror file with parentId pointing to the document
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- fileHash: 'hash1',
- size: 1000,
- fileType: 'application/pdf',
- parentId: 'docs_test123', // Mirror file points to document
+ fileId: 'file1',
userId,
},
]);
@@ -278,21 +278,6 @@ describe('KnowledgeBaseModel', () => {
},
]);
- // Create document first
- await serverDB.insert(documents).values([
- {
- id: 'docs_test456',
- title: 'Test Document',
- content: 'Test content',
- fileType: 'application/pdf',
- totalCharCount: 100,
- totalLineCount: 10,
- sourceType: 'file',
- source: 'test.pdf',
- userId,
- },
- ]);
-
// Create files - file1 is mirror of the document, file2 is standalone
await serverDB.insert(files).values([
{
@@ -302,12 +287,27 @@ describe('KnowledgeBaseModel', () => {
fileHash: 'hash1',
size: 1000,
fileType: 'application/pdf',
- parentId: 'docs_test456', // Mirror file points to document
userId,
},
fileList[1], // file2 - standalone file
]);
+ // Create document with fileId pointing to the mirror file
+ await serverDB.insert(documents).values([
+ {
+ id: 'docs_test456',
+ title: 'Test Document',
+ content: 'Test content',
+ fileType: 'application/pdf',
+ totalCharCount: 100,
+ totalLineCount: 10,
+ sourceType: 'file',
+ source: 'test.pdf',
+ fileId: 'file1',
+ userId,
+ },
+ ]);
+
const { id: knowledgeBaseId } = await knowledgeBaseModel.create({ name: 'Test Group' });
// Mix of document ID and direct file ID
@@ -368,7 +368,20 @@ describe('KnowledgeBaseModel', () => {
},
]);
- // Create document first
+ // Create mirror file first (document references it via fileId)
+ await serverDB.insert(files).values([
+ {
+ id: 'file1',
+ name: 'document.pdf',
+ url: 'https://example.com/document.pdf',
+ fileHash: 'hash1',
+ size: 1000,
+ fileType: 'application/pdf',
+ userId,
+ },
+ ]);
+
+ // Create document with fileId pointing to the mirror file
await serverDB.insert(documents).values([
{
id: 'docs_test789',
@@ -379,20 +392,7 @@ describe('KnowledgeBaseModel', () => {
totalLineCount: 10,
sourceType: 'file',
source: 'test.pdf',
- userId,
- },
- ]);
-
- // Create mirror file with parentId pointing to the document
- await serverDB.insert(files).values([
- {
- id: 'file1',
- name: 'document.pdf',
- url: 'https://example.com/document.pdf',
- fileHash: 'hash1',
- size: 1000,
- fileType: 'application/pdf',
- parentId: 'docs_test789', // Mirror file points to document
+ fileId: 'file1',
userId,
},
]);
diff --git a/packages/database/src/models/knowledgeBase.ts b/packages/database/src/models/knowledgeBase.ts
index 70dc495606d..0afb9fdf5d8 100644
--- a/packages/database/src/models/knowledgeBase.ts
+++ b/packages/database/src/models/knowledgeBase.ts
@@ -1,7 +1,7 @@
import { KnowledgeBaseItem } from '@lobechat/types';
import { and, desc, eq, inArray } from 'drizzle-orm';
-import { NewKnowledgeBase, documents, files, knowledgeBaseFiles, knowledgeBases } from '../schemas';
+import { NewKnowledgeBase, documents, knowledgeBaseFiles, knowledgeBases } from '../schemas';
import { LobeChatDatabase } from '../type';
export class KnowledgeBaseModel {
@@ -29,16 +29,17 @@ export class KnowledgeBaseModel {
const documentIds = fileIds.filter((id) => id.startsWith('docs_'));
const directFileIds = fileIds.filter((id) => !id.startsWith('docs_'));
- // Resolve document IDs to their mirror file IDs
- // For Pages, files.parentId points to the document ID
+ // Resolve document IDs to their mirror file IDs via documents.fileId
let resolvedFileIds = [...directFileIds];
if (documentIds.length > 0) {
- const mirrorFiles = await this.db
- .select({ id: files.id })
- .from(files)
- .where(and(inArray(files.parentId, documentIds), eq(files.userId, this.userId)));
+ const docsWithFiles = await this.db
+ .select({ fileId: documents.fileId })
+ .from(documents)
+ .where(and(inArray(documents.id, documentIds), eq(documents.userId, this.userId)));
- const mirrorFileIds = mirrorFiles.map((file) => file.id);
+ const mirrorFileIds = docsWithFiles
+ .map((doc) => doc.fileId)
+ .filter((id): id is string => id !== null);
resolvedFileIds = [...resolvedFileIds, ...mirrorFileIds];
// Update documents.knowledgeBaseId for pages
@@ -77,16 +78,17 @@ export class KnowledgeBaseModel {
const documentIds = ids.filter((id) => id.startsWith('docs_'));
const directFileIds = ids.filter((id) => !id.startsWith('docs_'));
- // Resolve document IDs to their mirror file IDs
- // For Pages, files.parentId points to the document ID
+ // Resolve document IDs to their mirror file IDs via documents.fileId
let resolvedFileIds = [...directFileIds];
if (documentIds.length > 0) {
- const mirrorFiles = await this.db
- .select({ id: files.id })
- .from(files)
- .where(and(inArray(files.parentId, documentIds), eq(files.userId, this.userId)));
+ const docsWithFiles = await this.db
+ .select({ fileId: documents.fileId })
+ .from(documents)
+ .where(and(inArray(documents.id, documentIds), eq(documents.userId, this.userId)));
- const mirrorFileIds = mirrorFiles.map((file) => file.id);
+ const mirrorFileIds = docsWithFiles
+ .map((doc) => doc.fileId)
+ .filter((id): id is string => id !== null);
resolvedFileIds = [...resolvedFileIds, ...mirrorFileIds];
// Clear documents.knowledgeBaseId for pages
diff --git a/src/app/[variants]/(main)/resource/features/FileDetail.tsx b/src/app/[variants]/(main)/resource/features/FileDetail.tsx
index e176d1e3f92..9d157defde3 100644
--- a/src/app/[variants]/(main)/resource/features/FileDetail.tsx
+++ b/src/app/[variants]/(main)/resource/features/FileDetail.tsx
@@ -55,11 +55,13 @@ const FileDetail = memo<FileDetailProps>((props) => {
const dataItems = [
{
- children: (
+ children: chunkCount ? (
<Tag icon={<Icon icon={BoltIcon} />} variant={'filled'}>
{' '}
{chunkCount}
</Tag>
+ ) : (
+ t('detail.data.noChunk')
),
key: 'chunkCount',
label: t('detail.data.chunkCount'),
diff --git a/src/app/[variants]/(main)/resource/features/store/action.ts b/src/app/[variants]/(main)/resource/features/store/action.ts
index 82cfc2014eb..5b00c70faaa 100644
--- a/src/app/[variants]/(main)/resource/features/store/action.ts
+++ b/src/app/[variants]/(main)/resource/features/store/action.ts
@@ -7,7 +7,7 @@ import { type State, type ViewMode, initialState } from './initialState';
export type MultiSelectActionType =
| 'addToKnowledgeBase'
- | 'addToOtherKnowledgeBase'
+ | 'moveToOtherKnowledgeBase'
| 'batchChunking'
| 'delete'
| 'deleteLibrary'
@@ -138,9 +138,7 @@ export const store: CreateStore = (publicState) => (set, get) => ({
switch (type) {
case 'delete': {
- // Use optimistic deleteResource for instant batch delete
- // All items disappear immediately, sync happens in background
- await Promise.all(selectedFileIds.map((id) => fileStore.deleteResource(id)));
+ await fileStore.deleteResources(selectedFileIds);
set({ selectedFileIds: [] });
return;
@@ -160,7 +158,7 @@ export const store: CreateStore = (publicState) => (set, get) => ({
return;
}
- case 'addToOtherKnowledgeBase': {
+ case 'moveToOtherKnowledgeBase': {
// Modal operations need to be handled in component layer
// Store just marks that action was requested
// Component will handle opening modal via useAddFilesToKnowledgeBaseModal hook
diff --git a/src/app/[variants]/(main)/resource/library/index.tsx b/src/app/[variants]/(main)/resource/library/index.tsx
index 7a176289f25..9d669d55d86 100644
--- a/src/app/[variants]/(main)/resource/library/index.tsx
+++ b/src/app/[variants]/(main)/resource/library/index.tsx
@@ -4,6 +4,7 @@ import { memo, useLayoutEffect } from 'react';
import { useLocation, useParams } from 'react-router-dom';
import Container from '@/app/[variants]/(main)/resource/library/features/Container';
+import NotFound from '@/components/404';
import NProgress from '@/components/NProgress';
import ResourceManager from '@/features/ResourceManager';
@@ -17,7 +18,7 @@ const MainContent = memo(() => {
const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);
// Load knowledge base data
- useKnowledgeBaseItem(knowledgeBaseId || '');
+ const { data, isLoading } = useKnowledgeBaseItem(knowledgeBaseId || '');
// Sync libraryId from URL params using useLayoutEffect
// useLayoutEffect runs synchronously before browser paint, ensuring state is set
@@ -33,6 +34,8 @@ const MainContent = memo(() => {
// Sync file view mode from URL
useInitFileCheck();
+ if (!isLoading && !data) return <NotFound />;
+
return <ResourceManager />;
});
diff --git a/src/features/CommandMenu/AskAgentCommands.tsx b/src/features/CommandMenu/AskAgentCommands.tsx
index 00f02fabb78..4e749bf9efc 100644
--- a/src/features/CommandMenu/AskAgentCommands.tsx
+++ b/src/features/CommandMenu/AskAgentCommands.tsx
@@ -62,6 +62,7 @@ const AskAgentCommands = memo(() => {
{/* @Lobe AI option */}
{showLobeAI && (
<Command.Item
+ onMouseDown={(e) => e.preventDefault()}
onSelect={() => handleAgentSelect(inboxAgentId, 'Lobe AI', DEFAULT_INBOX_AVATAR)}
value="@lobe-ai"
>
@@ -76,6 +77,7 @@ const AskAgentCommands = memo(() => {
{filteredAgents.map((agent) => (
<Command.Item
key={agent.id}
+ onMouseDown={(e) => e.preventDefault()}
onSelect={() =>
handleAgentSelect(
agent.id,
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index 040bdace942..ad878ec7bbe 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -100,7 +100,7 @@ const SearchResults = memo<SearchResultsProps>(
break;
}
case 'plugin': {
- navigate(`/community/plugins/${result.identifier}`);
+ navigate(`/community/mcp/${result.identifier}`);
break;
}
case 'communityAgent': {
@@ -108,7 +108,7 @@ const SearchResults = memo<SearchResultsProps>(
break;
}
case 'memory': {
- navigate(`/memory`);
+ navigate(`/memory/preferences?preferenceId=${result.id}`);
break;
}
}
diff --git a/src/features/ResourceManager/components/Explorer/Header/index.tsx b/src/features/ResourceManager/components/Explorer/Header/index.tsx
index c05f05d36fa..c8267ea27e2 100644
--- a/src/features/ResourceManager/components/Explorer/Header/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/Header/index.tsx
@@ -18,6 +18,9 @@ import SortDropdown from '../ToolBar/SortDropdown';
import ViewSwitcher from '../ToolBar/ViewSwitcher';
import Breadcrumb from './Breadcrumb';
+/**
+ * Toolbar for the resource explorer
+ */
const Header = memo(() => {
const { t } = useTranslation(['components', 'common', 'file', 'knowledgeBase']);
const { modal, message } = App.useApp();
@@ -47,14 +50,14 @@ const Header = memo(() => {
},
onOk: async () => {
await onActionClick('removeFromKnowledgeBase');
- message.success(t('FileManager.actions.removeFromKnowledgeBaseSuccess'));
+ message.success(t('FileManager.actions.removeFromLibrarySuccess'));
},
- title: t('FileManager.actions.confirmRemoveFromKnowledgeBase', {
+ title: t('FileManager.actions.confirmRemoveFromLibrary', {
count: selectCount,
}),
});
}}
- title={t('FileManager.actions.removeFromKnowledgeBase')}
+ title={t('FileManager.actions.removeFromLibrary')}
/>
) : null}
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index 3faede62812..5cdcb4d2fcf 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -56,9 +56,10 @@ export const useFileItemDropdown = ({
const { message, modal } = App.useApp();
const appOrigin = useAppOrigin();
- const { deleteResource, refreshFileList } = useFileStore(
+ const { deleteResource, moveResource, refreshFileList } = useFileStore(
(s) => ({
deleteResource: s.deleteResource,
+ moveResource: s.moveResource,
refreshFileList: s.refreshFileList,
}),
shallow,
@@ -88,15 +89,17 @@ export const useFileItemDropdown = ({
lowerFilename?.endsWith('.ppt') ||
lowerFilename?.endsWith('.pptx') ||
lowerFilename?.endsWith('.odt');
- const isPage = !isPDF && !isOfficeFile && (sourceType === 'document' || fileType === PAGE_FILE_TYPE);
+ const isPage =
+ !isPDF && !isOfficeFile && (sourceType === 'document' || fileType === PAGE_FILE_TYPE);
const menuItems = useCallback(() => {
// Filter out current knowledge base and create submenu items
const availableKnowledgeBases = (libraries || []).filter((kb) => kb.id !== libraryId);
+ // Submenu for adding files to a library (used when NOT in a library)
const addToKnowledgeBaseSubmenu: ItemType[] = availableKnowledgeBases.map((kb) => ({
icon: <RepoIcon />,
- key: `add-to-kb-${kb.id}`,
+ key: `add-to-library-${kb.id}`,
label: <span style={{ marginLeft: 8 }}>{kb.name}</span>,
onClick: async ({ domEvent }) => {
domEvent.stopPropagation();
@@ -108,9 +111,48 @@ export const useFileItemDropdown = ({
ns: 'knowledgeBase',
}),
);
- } catch (e) {
+ } catch (e: any) {
console.error(e);
- message.error(t('addToKnowledgeBase.error', { ns: 'knowledgeBase' }));
+ // Check for duplicate key error (file already exists in the library)
+ // Server throws CONFLICT error code for duplicate entries
+ const isDuplicateError =
+ e?.data?.code === 'CONFLICT' || e?.message === 'FILE_ALREADY_IN_KNOWLEDGE_BASE';
+ if (isDuplicateError) {
+ message.warning(t('addToKnowledgeBase.alreadyExists', { ns: 'knowledgeBase' }));
+ } else {
+ message.error(t('addToKnowledgeBase.error', { ns: 'knowledgeBase' }));
+ }
+ }
+ },
+ }));
+
+ // Submenu for moving files to another library (used when IN a library)
+ // Move = remove from current library + clear folder relationship + add to target library
+ const moveToKnowledgeBaseSubmenu: ItemType[] = availableKnowledgeBases.map((kb) => ({
+ icon: <RepoIcon />,
+ key: `move-to-library-${kb.id}`,
+ label: <span style={{ marginLeft: 8 }}>{kb.name}</span>,
+ onClick: async ({ domEvent }) => {
+ domEvent.stopPropagation();
+ try {
+ // First remove from current library
+ if (libraryId) {
+ await removeFilesFromKnowledgeBase(libraryId, [id]);
+ }
+ // Clear folder relationship (parentId) since folders are library-specific
+ await moveResource(id, null);
+ // Then add to target library
+ await addFilesToKnowledgeBase(kb.id, [id]);
+ message.success(t('moveToKnowledgeBase.success', { ns: 'knowledgeBase' }));
+ } catch (e: any) {
+ console.error(e);
+ const isDuplicateError =
+ e?.data?.code === 'CONFLICT' || e?.message === 'FILE_ALREADY_IN_KNOWLEDGE_BASE';
+ if (isDuplicateError) {
+ message.warning(t('addToKnowledgeBase.alreadyExists', { ns: 'knowledgeBase' }));
+ } else {
+ message.error(t('moveToKnowledgeBase.error', { ns: 'knowledgeBase' }));
+ }
}
},
}));
@@ -119,15 +161,15 @@ export const useFileItemDropdown = ({
isInLibrary
? [
availableKnowledgeBases.length > 0 && {
- children: addToKnowledgeBaseSubmenu,
+ children: moveToKnowledgeBaseSubmenu,
icon: <Icon icon={BookPlusIcon} />,
- key: 'addToOtherKnowledgeBase',
- label: t('FileManager.actions.addToOtherKnowledgeBase'),
+ key: 'moveToOtherLibrary',
+ label: t('FileManager.actions.moveToOtherLibrary'),
},
{
icon: <Icon icon={BookMinusIcon} />,
- key: 'removeFromKnowledgeBase',
- label: t('FileManager.actions.removeFromKnowledgeBase'),
+ key: 'removeFromLibrary',
+ label: t('FileManager.actions.removeFromLibrary'),
onClick: async ({ domEvent }) => {
domEvent.stopPropagation();
@@ -138,9 +180,9 @@ export const useFileItemDropdown = ({
onOk: async () => {
await removeFilesFromKnowledgeBase(libraryId, [id]);
- message.success(t('FileManager.actions.removeFromKnowledgeBaseSuccess'));
+ message.success(t('FileManager.actions.removeFromLibrarySuccess'));
},
- title: t('FileManager.actions.confirmRemoveFromKnowledgeBase', {
+ title: t('FileManager.actions.confirmRemoveFromLibrary', {
count: 1,
}),
});
@@ -151,8 +193,8 @@ export const useFileItemDropdown = ({
availableKnowledgeBases.length > 0 && {
children: addToKnowledgeBaseSubmenu,
icon: <Icon icon={BookPlusIcon} />,
- key: 'addToKnowledgeBase',
- label: t('FileManager.actions.addToKnowledgeBase'),
+ key: 'addToLibrary',
+ label: t('FileManager.actions.addToLibrary'),
},
]
) as ItemType[];
@@ -299,6 +341,7 @@ export const useFileItemDropdown = ({
libraryId,
message,
modal,
+ moveResource,
onRenameStart,
refreshFileList,
removeFilesFromKnowledgeBase,
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/DefaultFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
similarity index 100%
rename from src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/DefaultFileItem.tsx
rename to src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/ImageFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
similarity index 86%
rename from src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/ImageFileItem.tsx
rename to src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
index e0dce336b94..6b6adb7cd19 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/ImageFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
@@ -50,16 +50,16 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
opacity: 1;
}
`,
- imagePlaceholder: css`
+ imageWrapper: css`
+ position: relative;
+
display: flex;
align-items: center;
justify-content: center;
- background: ${cssVar.colorFillQuaternary};
- `,
- imageWrapper: css`
- position: relative;
+
width: 100%;
min-height: 120px;
+
background: ${cssVar.colorFillQuaternary};
img {
@@ -144,29 +144,27 @@ const ImageFileItem = memo<ImageFileItemProps>(
<>
<div className={styles.imageWrapper}>
{!imageLoaded && (
- <div className={styles.imagePlaceholder}>
- <Flexbox
- align={'center'}
- gap={12}
- justify={'center'}
- paddingBlock={24}
- paddingInline={12}
+ <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',
+ }}
>
- <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>
+ {formatSize(size)}
+ </div>
+ </Flexbox>
)}
{isInView && url && (
<Image
@@ -186,7 +184,9 @@ const ImageFileItem = memo<ImageFileItemProps>(
width: '100%',
}}
wrapperStyle={{
- display: 'block',
+ inset: 0,
+ pointerEvents: imageLoaded ? 'auto' : 'none',
+ position: imageLoaded ? 'relative' : 'absolute',
width: '100%',
}}
/>
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/MarkdownFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MarkdownFileItem.tsx
similarity index 100%
rename from src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/MarkdownFileItem.tsx
rename to src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MarkdownFileItem.tsx
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/MasonryItemWrapper.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MasonryItemWrapper.tsx
similarity index 100%
rename from src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/MasonryItemWrapper.tsx
rename to src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MasonryItemWrapper.tsx
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/NoteFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx
similarity index 93%
rename from src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/NoteFileItem.tsx
rename to src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx
index 726a22cd8b5..413cd18526c 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/NoteFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx
@@ -177,8 +177,16 @@ const NoteFileItem = memo<NoteFileItemProps>(
)}
</div>
) : (
- <div className={styles.iconWrapper}>
- <FileIcon fileName={name} fileType={fileType} size={64} />
+ <div className={styles.noteContent}>
+ <div className={styles.noteTitle}>
+ {emoji && <span style={{ fontSize: 20 }}>{emoji}</span>}
+ <span>{displayTitle}</span>
+ </div>
+ <div className={styles.notePreview}>
+ <span style={{ color: 'var(--lobe-text-tertiary)', fontStyle: 'italic' }}>
+ No content
+ </span>
+ </div>
</div>
)}
</div>
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
similarity index 100%
rename from src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/index.tsx
rename to src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
index 0f1274aee00..a4819c47a9d 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryFileItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
@@ -10,9 +10,9 @@ import {
import { documentService } from '@/services/document';
import { type FileListItem } from '@/types/files';
-import { useFileItemClick } from '../../hooks/useFileItemClick';
import DropdownMenu from '../../ItemDropdown/DropdownMenu';
import { useFileItemDropdown } from '../../ItemDropdown/useFileItemDropdown';
+import { useFileItemClick } from '../../hooks/useFileItemClick';
import DefaultFileItem from './DefaultFileItem';
import ImageFileItem from './ImageFileItem';
import MarkdownFileItem from './MarkdownFileItem';
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx
index 7418f97b09d..154012b2df8 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx
@@ -13,7 +13,7 @@ import { useFetchResources } from '@/store/file/slices/resource/hooks';
import { type FileListItem } from '@/types/files';
import { useMasonryColumnCount } from '../useMasonryColumnCount';
-import MasonryItemWrapper from './MasonryFileItem/MasonryItemWrapper';
+import MasonryItemWrapper from './MasonryItem/MasonryItemWrapper';
import MasonryViewSkeleton from './Skeleton';
const MasonryView = memo(function MasonryView() {
diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
index beadc9c2178..d620f59f2ca 100644
--- a/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ToolBar/BatchActionsDropdown.tsx
@@ -18,7 +18,7 @@ import ActionIconWithChevron from './ActionIconWithChevron';
export type MultiSelectActionType =
| 'addToKnowledgeBase'
- | 'addToOtherKnowledgeBase'
+ | 'moveToOtherKnowledgeBase'
| 'batchChunking'
| 'delete'
| 'deleteLibrary'
@@ -97,7 +97,7 @@ const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onA
disabled: selectCount === 0,
icon: <Icon icon={BookMinusIcon} />,
key: 'removeFromKnowledgeBase',
- label: t('FileManager.actions.removeFromKnowledgeBase'),
+ label: t('FileManager.actions.removeFromLibrary'),
onClick: () => {
modal.confirm({
okButtonProps: {
@@ -105,9 +105,9 @@ const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onA
},
onOk: async () => {
await onActionClick('removeFromKnowledgeBase');
- message.success(t('FileManager.actions.removeFromKnowledgeBaseSuccess'));
+ message.success(t('FileManager.actions.removeFromLibrarySuccess'));
},
- title: t('FileManager.actions.confirmRemoveFromKnowledgeBase', {
+ title: t('FileManager.actions.confirmRemoveFromLibrary', {
count: selectCount,
}),
});
@@ -119,8 +119,8 @@ const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onA
children: addToKnowledgeBaseSubmenu as any,
disabled: selectCount === 0,
icon: <Icon icon={BookPlusIcon} />,
- key: 'addToOtherKnowledgeBase',
- label: t('FileManager.actions.addToOtherKnowledgeBase'),
+ key: 'moveToOtherKnowledgeBase',
+ label: t('FileManager.actions.moveToOtherLibrary'),
});
}
} else if (availableKnowledgeBases.length > 0) {
@@ -129,7 +129,7 @@ const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onA
disabled: selectCount === 0,
icon: <Icon icon={BookPlusIcon} />,
key: 'addToKnowledgeBase',
- label: t('FileManager.actions.addToKnowledgeBase'),
+ label: t('FileManager.actions.addToLibrary'),
});
}
diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/Config.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/Config.tsx
index 8524ec7148e..693c952e38d 100644
--- a/src/features/ResourceManager/components/Explorer/ToolBar/Config.tsx
+++ b/src/features/ResourceManager/components/Explorer/ToolBar/Config.tsx
@@ -20,7 +20,7 @@ const Config = memo<ConfigProps>(({ config, onConfigChange }) => {
onConfigChange({ showFilesInKnowledgeBase: !config.showFilesInKnowledgeBase });
}}
>
- {t('FileManager.config.showFilesInKnowledgeBase')}
+ {t('FileManager.config.showFilesInLibrary')}
<Switch size={'small'} value={config.showFilesInKnowledgeBase} />
</Flexbox>
);
diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/MultiSelectActions.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/MultiSelectActions.tsx
index 2f524386b33..16ad4b1278f 100644
--- a/src/features/ResourceManager/components/Explorer/ToolBar/MultiSelectActions.tsx
+++ b/src/features/ResourceManager/components/Explorer/ToolBar/MultiSelectActions.tsx
@@ -16,7 +16,7 @@ const styles = createStaticStyles(({ css }) => ({
export type MultiSelectActionType =
| 'addToKnowledgeBase'
- | 'addToOtherKnowledgeBase'
+ | 'moveToOtherKnowledgeBase'
| 'batchChunking'
| 'delete'
| 'deleteLibrary'
@@ -88,27 +88,27 @@ const MultiSelectActions = memo<MultiSelectActionsProps>(
},
onOk: async () => {
await onActionClick('removeFromKnowledgeBase');
- message.success(t('FileManager.actions.removeFromKnowledgeBaseSuccess'));
+ message.success(t('FileManager.actions.removeFromLibrarySuccess'));
},
- title: t('FileManager.actions.confirmRemoveFromKnowledgeBase', {
+ title: t('FileManager.actions.confirmRemoveFromLibrary', {
count: selectCount,
}),
});
}}
size={'small'}
>
- {t('FileManager.actions.removeFromKnowledgeBase')}
+ {t('FileManager.actions.removeFromLibrary')}
</Button>
<Button
color={'default'}
icon={<Icon icon={BookPlusIcon} />}
onClick={() => {
- onActionClick('addToOtherKnowledgeBase');
+ onActionClick('moveToOtherKnowledgeBase');
}}
size={'small'}
variant={'filled'}
>
- {t('FileManager.actions.addToOtherKnowledgeBase')}
+ {t('FileManager.actions.moveToOtherLibrary')}
</Button>
</>
) : (
@@ -121,7 +121,7 @@ const MultiSelectActions = memo<MultiSelectActionsProps>(
size={'small'}
variant={'filled'}
>
- {t('FileManager.actions.addToKnowledgeBase')}
+ {t('FileManager.actions.addToLibrary')}
</Button>
)}
<Button
diff --git a/src/features/ResourceManager/components/Explorer/ToolBar/SortDropdown.tsx b/src/features/ResourceManager/components/Explorer/ToolBar/SortDropdown.tsx
index 61b0e624a38..5216ed2e0fa 100644
--- a/src/features/ResourceManager/components/Explorer/ToolBar/SortDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ToolBar/SortDropdown.tsx
@@ -1,8 +1,10 @@
-import { DropdownMenu, type DropdownMenuCheckboxItem } from '@lobehub/ui';
-import { ArrowDownAZ } from 'lucide-react';
+import { DropdownMenu, Icon } from '@lobehub/ui';
+import { ArrowDownAZ, CalendarIcon, Check, HardDriveIcon, type LucideIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { type MenuProps } from '@/components/Menu';
+
import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';
import ActionIconWithChevron from './ActionIconWithChevron';
@@ -12,33 +14,26 @@ const SortDropdown = memo(() => {
const sorter = useResourceManagerStore((s) => s.sorter);
const setSorter = useResourceManagerStore((s) => s.setSorter);
- const sortOptions = useMemo(
+ const sortOptions: { icon: LucideIcon; key: string; label: string }[] = useMemo(
() => [
- { key: 'name', label: t('FileManager.sort.name') },
- { key: 'createdAt', label: t('FileManager.sort.dateAdded') },
- { key: 'size', label: t('FileManager.sort.size') },
+ { icon: ArrowDownAZ, key: 'name', label: t('FileManager.sort.name') },
+ { icon: CalendarIcon, key: 'createdAt', label: t('FileManager.sort.dateAdded') },
+ { icon: HardDriveIcon, key: 'size', label: t('FileManager.sort.size') },
],
[t],
);
const selectedKey = sorter || 'createdAt';
- const menuItems = useMemo<DropdownMenuCheckboxItem[]>(
+ const menuItems: MenuProps['items'] = useMemo(
() =>
- sortOptions.map(
- (option): DropdownMenuCheckboxItem => ({
- checked: option.key === selectedKey,
- closeOnClick: true,
- key: option.key,
- label: option.label,
- onCheckedChange: (checked: boolean) => {
- if (checked) {
- setSorter(option.key as 'name' | 'createdAt' | 'size');
- }
- },
- type: 'checkbox',
- }),
- ),
+ sortOptions.map((option) => ({
+ extra: option.key === selectedKey ? <Icon icon={Check} /> : undefined,
+ icon: <Icon icon={option.icon} />,
+ key: option.key,
+ label: option.label,
+ onClick: () => setSorter(option.key as 'name' | 'createdAt' | 'size'),
+ })),
[selectedKey, setSorter, sortOptions],
);
diff --git a/src/features/ResourceManager/components/Explorer/useResourceExplorer.ts b/src/features/ResourceManager/components/Explorer/useResourceExplorer.ts
index 9e8015c47fe..f0b1c17dcc0 100644
--- a/src/features/ResourceManager/components/Explorer/useResourceExplorer.ts
+++ b/src/features/ResourceManager/components/Explorer/useResourceExplorer.ts
@@ -108,7 +108,7 @@ export const useResourceExplorer = ({
return;
}
- if (type === 'addToOtherKnowledgeBase') {
+ if (type === 'moveToOtherKnowledgeBase') {
openAddModal({
fileIds: selectFileIds,
knowledgeBaseId: libraryId,
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
index d099a727e2b..7abf3f77cbe 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
@@ -14,11 +14,12 @@ import {
useDragActive,
useDragState,
} from '@/app/[variants]/(main)/resource/features/DndContextWrapper';
-import { useFolderPath } from '@/app/[variants]/(main)/resource/features/hooks/useFolderPath';
import { useResourceManagerStore } from '@/app/[variants]/(main)/resource/features/store';
import FileIcon from '@/components/FileIcon';
+import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';
import { useFileStore } from '@/store/file';
+import { useFileItemClick } from '../Explorer/hooks/useFileItemClick';
import { useFileItemDropdown } from '../Explorer/ItemDropdown/useFileItemDropdown';
import { styles } from './styles';
import { clearTreeFolderCache } from './treeState';
@@ -49,14 +50,9 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
folderChildrenCache,
}) => {
const navigate = useNavigate();
- const { currentFolderSlug } = useFolderPath();
const { message } = App.useApp();
- const [setMode, setCurrentViewItemId, libraryId] = useResourceManagerStore((s) => [
- s.setMode,
- s.setCurrentViewItemId,
- s.libraryId,
- ]);
+ const [setMode, libraryId] = useResourceManagerStore((s) => [s.setMode, s.libraryId]);
const renameFolder = useFileStore((s) => s.renameFolder);
@@ -65,12 +61,29 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
const inputRef = useRef<any>(null);
// Memoize computed values that don't change frequently
- const { itemKey } = useMemo(
- () => ({
+ const { itemKey, isPage, emoji } = useMemo(() => {
+ const lowerFileType = item.fileType?.toLowerCase();
+ const lowerName = item.name?.toLowerCase();
+ const isPDF = lowerFileType === 'pdf' || lowerName?.endsWith('.pdf');
+ const isOfficeFile =
+ lowerName?.endsWith('.xls') ||
+ lowerName?.endsWith('.xlsx') ||
+ lowerName?.endsWith('.doc') ||
+ lowerName?.endsWith('.docx') ||
+ lowerName?.endsWith('.ppt') ||
+ lowerName?.endsWith('.pptx') ||
+ lowerName?.endsWith('.odt');
+ const pageMatch =
+ !isPDF &&
+ !isOfficeFile &&
+ (item.sourceType === 'document' || item.fileType === PAGE_FILE_TYPE);
+
+ return {
+ emoji: pageMatch ? item.metadata?.emoji : null,
+ isPage: pageMatch,
itemKey: item.slug || item.id,
- }),
- [item.slug, item.id],
- );
+ };
+ }, [item.slug, item.id, item.fileType, item.sourceType, item.name, item.metadata?.emoji]);
const handleRenameStart = useCallback(() => {
setIsRenaming(true);
@@ -183,22 +196,13 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
setIsOver(false);
}, []);
- const handleItemClick = useCallback(() => {
- // Open file modal using slug-based routing
- const currentPath = currentFolderSlug
- ? `/resource/library/${libraryId}/${currentFolderSlug}`
- : `/resource/library/${libraryId}`;
-
- setCurrentViewItemId(itemKey);
- navigate(`${currentPath}?file=${itemKey}`);
-
- if (itemKey.startsWith('doc')) {
- setMode('page');
- } else {
- // Set mode to 'file' immediately to prevent flickering to list view
- setMode('editor');
- }
- }, [itemKey, currentFolderSlug, libraryId, navigate, setMode, setCurrentViewItemId]);
+ const handleItemClick = useFileItemClick({
+ id: item.id,
+ isFolder: item.isFolder,
+ isPage,
+ libraryId,
+ slug: item.slug,
+ });
const handleFolderClick = useCallback(
(folderId: string, folderSlug?: string | null) => {
@@ -357,8 +361,12 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
horizontal
style={{ minHeight: 28, minWidth: 0, overflow: 'hidden' }}
>
- {item.sourceType === 'document' ? (
- <Icon icon={FileText} size={18} />
+ {isPage ? (
+ emoji ? (
+ <span style={{ fontSize: 18 }}>{emoji}</span>
+ ) : (
+ <Icon icon={FileText} size={18} />
+ )
) : (
<FileIcon fileName={item.name} fileType={item.fileType} size={18} />
)}
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
index 95d4c273917..e78ec124b05 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
@@ -105,6 +105,7 @@ const LibraryHierarchy = memo(() => {
fileType: item.fileType,
id: item.id,
isFolder: item.fileType === 'custom/folder',
+ metadata: item.metadata ?? undefined,
name: item.name,
slug: item.slug,
sourceType: item.sourceType,
@@ -212,6 +213,7 @@ const LibraryHierarchy = memo(() => {
fileType: item.fileType,
id: item.id,
isFolder: item.fileType === 'custom/folder',
+ metadata: item.metadata ?? undefined,
name: item.name,
slug: item.slug,
sourceType: item.sourceType,
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/treeState.ts b/src/features/ResourceManager/components/LibraryHierarchy/treeState.ts
index b883f17c6c7..5ac2553fd74 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/treeState.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/treeState.ts
@@ -19,6 +19,7 @@ export const resourceItemToTreeItem = (item: ResourceItem): TreeItem => {
fileType: item.fileType,
id: item.id,
isFolder: item.fileType === 'custom/folder',
+ metadata: item.metadata,
name: item.name,
slug: item.slug,
sourceType: item.sourceType,
@@ -128,6 +129,7 @@ export const clearTreeFolderCache = async (knowledgeBaseId: string) => {
fileType: item.fileType,
id: item.id,
isFolder: item.fileType === 'custom/folder',
+ metadata: item.metadata,
name: item.name,
slug: item.slug,
sourceType: item.sourceType,
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/types.ts b/src/features/ResourceManager/components/LibraryHierarchy/types.ts
index fedc7da99a5..2cfae129a84 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/types.ts
+++ b/src/features/ResourceManager/components/LibraryHierarchy/types.ts
@@ -3,6 +3,7 @@ export interface TreeItem {
fileType: string;
id: string;
isFolder: boolean;
+ metadata?: Record<string, any>;
name: string;
slug?: string | null;
sourceType?: string;
diff --git a/src/features/ResourceManager/components/UploadDock/index.tsx b/src/features/ResourceManager/components/UploadDock/index.tsx
index 8f2d6103961..d9b3c33e3ee 100644
--- a/src/features/ResourceManager/components/UploadDock/index.tsx
+++ b/src/features/ResourceManager/components/UploadDock/index.tsx
@@ -48,6 +48,9 @@ const styles = createStaticStyles(({ css }) => {
};
});
+/**
+ * Show & manage current uploading tasks
+ */
const UploadDock = memo(() => {
const { t } = useTranslation('file');
const [show, setShow] = useState(true);
diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsx
index 2aa11f17753..04d65becda6 100644
--- a/src/features/ResourceManager/index.tsx
+++ b/src/features/ResourceManager/index.tsx
@@ -14,7 +14,7 @@ import { documentService } from '@/services/document';
import { useFileStore } from '@/store/file';
import { documentSelectors } from '@/store/file/slices/document/selectors';
-import Editor from './components/Editor';
+import FileEditor from './components/Editor';
import Explorer from './components/Explorer';
import UploadDock from './components/UploadDock';
@@ -135,11 +135,7 @@ const ResourceManager = memo(() => {
return (
<>
- <DragUploadZone
- enabledFiles
- onUploadFiles={handleUploadFiles}
- style={{ height: '100%' }}
- >
+ <DragUploadZone enabledFiles onUploadFiles={handleUploadFiles} style={{ height: '100%' }}>
<Flexbox className={styles.container} height={'100%'} style={cssVariables}>
{/* Explorer is always rendered to preserve its state */}
<Explorer />
@@ -147,7 +143,7 @@ const ResourceManager = memo(() => {
{/* Editor overlay */}
{mode === 'editor' && (
<Flexbox className={styles.editorOverlay}>
- <Editor onBack={handleBack} />
+ <FileEditor onBack={handleBack} />
</Flexbox>
)}
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 1fbb7a96c6a..d93d2b2e769 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -73,7 +73,7 @@ export default {
'emptyAgent': 'No Agents yet. Start with your first Agent—build your system over time.',
'emptyAgentAction': 'Create Agent',
'extendParams.disableContextCaching.desc':
- 'Reduce by up to 90% of the cost of generating a single conversation and bring a max of 4x speed. Enabling this will automatically disable the limit on the number of historical messages. <1>Learn more</1>',
+ 'Reduce by up to 90% of the cost of generating a single conversation and bring a max of 4x speed. <1>Learn more</1>',
'extendParams.disableContextCaching.title': 'Enable Context Caching',
'extendParams.effort.desc':
'Control how many tokens Claude uses when responding with the effort parameter.',
@@ -82,7 +82,7 @@ export default {
'Let Claude dynamically decide when and how much to think with adaptive thinking mode.',
'extendParams.enableAdaptiveThinking.title': 'Enable Adaptive Thinking',
'extendParams.enableReasoning.desc':
- 'Based on the Claude Thinking mechanism limit, enabling this will automatically disable the limit on the number of historical messages. <1>Learn more</1>',
+ 'Based on the Claude Thinking mechanism limit. <1>Learn more</1>',
'extendParams.enableReasoning.title': 'Enable Deep Thinking',
'extendParams.imageAspectRatio.title': 'Image Aspect Ratio',
'extendParams.imageResolution.title': 'Image Resolution',
diff --git a/src/locales/default/components.ts b/src/locales/default/components.ts
index 3d8631743c0..e938fc457c7 100644
--- a/src/locales/default/components.ts
+++ b/src/locales/default/components.ts
@@ -7,8 +7,7 @@ export default {
'Drag and drop images and files here to upload multiple images and files.',
'DragUpload.dragFileTitle': 'Upload Files',
'DragUpload.dragTitle': 'Upload Images',
- 'FileManager.actions.addToKnowledgeBase': 'Add to Library',
- 'FileManager.actions.addToOtherKnowledgeBase': 'Add to another Library',
+ 'FileManager.actions.addToLibrary': 'Add to Library',
'FileManager.actions.batchChunking': 'Batch Chunking',
'FileManager.actions.chunking': 'Chunking',
'FileManager.actions.chunkingTooltip':
@@ -20,8 +19,8 @@ export default {
'You are about to delete this folder and all of its contents. This action cannot be undone. Please confirm your decision.',
'FileManager.actions.confirmDeleteMultiFiles':
'You are about to delete the selected {{count}} files. Once deleted, they cannot be recovered. Please confirm your action.',
- 'FileManager.actions.confirmRemoveFromKnowledgeBase':
- 'You’re about to remove {{count}} selected file(s) from the Library. They’ll still be available in All Files. Confirm to continue.',
+ 'FileManager.actions.confirmRemoveFromLibrary':
+ "You're about to remove {{count}} selected file(s) from the Library. They'll still be available in All Files. Confirm to continue.",
'FileManager.actions.copyUrl': 'Copy Link',
'FileManager.actions.copyUrlSuccess': 'File url copied successfully.',
'FileManager.actions.createChunkingTask': 'Preparing...',
@@ -34,15 +33,16 @@ export default {
'FileManager.actions.moveHere': 'Move here',
'FileManager.actions.moveSuccess': 'File moved successfully',
'FileManager.actions.moveToFolder': 'Move to...',
+ 'FileManager.actions.moveToOtherLibrary': 'Move to another Library',
'FileManager.actions.moveToRoot': 'Move to root directory',
'FileManager.actions.moving': 'Moving...',
- 'FileManager.actions.removeFromKnowledgeBase': 'Remove from Library',
- 'FileManager.actions.removeFromKnowledgeBaseSuccess': 'File removed successfully.',
+ 'FileManager.actions.removeFromLibrary': 'Remove from Library',
+ 'FileManager.actions.removeFromLibrarySuccess': 'File removed successfully.',
'FileManager.actions.rename': 'Rename',
'FileManager.actions.renameError': 'Rename failed',
'FileManager.actions.renameSuccess': 'Rename successful',
'FileManager.bottom': "You've reached the end.",
- 'FileManager.config.showFilesInKnowledgeBase': 'Show content in Library',
+ 'FileManager.config.showFilesInLibrary': 'Show content in Library',
'FileManager.emptyStatus.actions.file': 'Upload File',
'FileManager.emptyStatus.actions.folder': 'Upload Folder',
'FileManager.emptyStatus.actions.knowledgeBase': 'Create Library',
diff --git a/src/locales/default/file.ts b/src/locales/default/file.ts
index d7cadc68e9b..cc50a2e66fc 100644
--- a/src/locales/default/file.ts
+++ b/src/locales/default/file.ts
@@ -9,6 +9,7 @@ export default {
'detail.basic.type': 'Format',
'detail.basic.updatedAt': 'Update Time',
'detail.data.chunkCount': 'Chunks',
+ 'detail.data.noChunk': 'No chunk',
'detail.data.embedding.default': 'Not embedding',
'detail.data.embedding.error': 'Failed',
'detail.data.embedding.pending': 'Pending start',
diff --git a/src/locales/default/knowledgeBase.ts b/src/locales/default/knowledgeBase.ts
index 504d2df720e..e5819f8063d 100644
--- a/src/locales/default/knowledgeBase.ts
+++ b/src/locales/default/knowledgeBase.ts
@@ -1,5 +1,6 @@
export default {
'addToKnowledgeBase.addSuccess': 'File added successfully',
+ 'addToKnowledgeBase.alreadyExists': 'This file is already in the library',
'addToKnowledgeBase.confirm': 'Add',
'addToKnowledgeBase.error': 'Failed to add file to Library',
'addToKnowledgeBase.id.placeholder': 'Please select a library to add to',
@@ -7,6 +8,8 @@ export default {
'addToKnowledgeBase.id.title': 'Target Library',
'addToKnowledgeBase.title': 'Add to Library',
'addToKnowledgeBase.totalFiles': '{{count}} files selected',
+ 'moveToKnowledgeBase.error': 'Failed to move file to Library',
+ 'moveToKnowledgeBase.success': 'File moved successfully',
'createNew.confirm': 'Create New',
'createNew.description.placeholder': 'Library description (optional)',
'createNew.formTitle': 'Basic Information',
diff --git a/src/server/routers/lambda/knowledgeBase.ts b/src/server/routers/lambda/knowledgeBase.ts
index 81d357b2cae..002f9a9e8ab 100644
--- a/src/server/routers/lambda/knowledgeBase.ts
+++ b/src/server/routers/lambda/knowledgeBase.ts
@@ -1,3 +1,4 @@
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
@@ -20,7 +21,19 @@ export const knowledgeBaseRouter = router({
addFilesToKnowledgeBase: knowledgeBaseProcedure
.input(z.object({ ids: z.array(z.string()), knowledgeBaseId: z.string() }))
.mutation(async ({ input, ctx }) => {
- return ctx.knowledgeBaseModel.addFilesToKnowledgeBase(input.knowledgeBaseId, input.ids);
+ try {
+ return await ctx.knowledgeBaseModel.addFilesToKnowledgeBase(input.knowledgeBaseId, input.ids);
+ } catch (e: any) {
+ // Check for PostgreSQL unique constraint violation (code 23505)
+ const pgErrorCode = e?.cause?.cause?.code || e?.cause?.code || e?.code;
+ if (pgErrorCode === '23505') {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'FILE_ALREADY_IN_KNOWLEDGE_BASE',
+ });
+ }
+ throw e;
+ }
}),
createKnowledgeBase: knowledgeBaseProcedure
diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.ts
index eac5dc2b77b..0fe5288493c 100644
--- a/src/store/file/slices/resource/action.ts
+++ b/src/store/file/slices/resource/action.ts
@@ -1,5 +1,7 @@
import debug from 'debug';
+import { documentService } from '@/services/document';
+import { fileService } from '@/services/file';
import { resourceService } from '@/services/resource';
import { type StoreSetter } from '@/store/types';
import type { CreateResourceParams, ResourceItem, UpdateResourceParams } from '@/types/resource';
@@ -219,6 +221,49 @@ export class ResourceActionImpl {
log('enqueue deleteResource', id, syncEngine);
};
+ deleteResources = async (ids: string[]) => {
+ if (ids.length === 0) return;
+
+ // 1. Read sourceType from resourceMap for each ID (client-side, no API call)
+ const { resourceMap, resourceList } = this.#get();
+ const fileIds: string[] = [];
+ const documentIds: string[] = [];
+
+ for (const id of ids) {
+ const resource = resourceMap.get(id);
+ if (resource?.sourceType === 'document') {
+ documentIds.push(id);
+ } else {
+ fileIds.push(id);
+ }
+ }
+
+ // 2. Optimistically remove all items from store in one set() call
+ const idsSet = new Set(ids);
+ const newMap = new Map(resourceMap);
+ for (const id of ids) {
+ newMap.delete(id);
+ }
+
+ this.#set(
+ {
+ resourceList: resourceList.filter((r) => !idsSet.has(r.id)),
+ resourceMap: newMap,
+ },
+ false,
+ 'deleteResources/optimistic',
+ );
+
+ // 3. Fire batch delete APIs in background (no await — UI already updated)
+ const promises: Promise<void>[] = [];
+ if (fileIds.length > 0) promises.push(fileService.removeFiles(fileIds));
+ if (documentIds.length > 0) promises.push(documentService.deleteDocuments(documentIds));
+
+ Promise.all(promises).catch((error) => {
+ console.error('Failed to delete resources:', error);
+ });
+ };
+
/**
* Flush pending sync operations immediately
*/