🤯 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(explorer-tree): add generic ExplorerTree component built on @pierre/trees (#14094)
Innei03621d0664a8
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b4097f73a96..80e6503cfe4 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -848,6 +848,14 @@"workingPanel.resources.renameEmpty": "Title cannot be empty","workingPanel.resources.renameError": "Failed to rename document","workingPanel.resources.renameSuccess": "Document renamed",+ "workingPanel.resources.tree.createError": "Failed to create",+ "workingPanel.resources.tree.moveError": "Failed to move",+ "workingPanel.resources.tree.newDocument": "New document",+ "workingPanel.resources.tree.newFolder": "New folder",+ "workingPanel.resources.tree.parentMissing": "Parent folder is unavailable",+ "workingPanel.resources.tree.rename": "Rename",+ "workingPanel.resources.tree.untitledDocument": "Untitled document",+ "workingPanel.resources.tree.untitledFolder": "Untitled folder","workingPanel.resources.updatedAt": "Updated {{time}}","workingPanel.resources.viewMode.list": "List view","workingPanel.resources.viewMode.tree": "Tree view",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex a0992c43b41..84cdd665054 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -848,6 +848,14 @@"workingPanel.resources.renameEmpty": "标题不能为空","workingPanel.resources.renameError": "重命名失败","workingPanel.resources.renameSuccess": "重命名成功",+ "workingPanel.resources.tree.createError": "创建失败",+ "workingPanel.resources.tree.moveError": "移动失败",+ "workingPanel.resources.tree.newDocument": "新建文档",+ "workingPanel.resources.tree.newFolder": "新建文件夹",+ "workingPanel.resources.tree.parentMissing": "上级目录不可用",+ "workingPanel.resources.tree.rename": "重命名",+ "workingPanel.resources.tree.untitledDocument": "未命名文档",+ "workingPanel.resources.tree.untitledFolder": "未命名文件夹","workingPanel.resources.updatedAt": "更新于 {{time}}","workingPanel.resources.viewMode.list": "列表视图","workingPanel.resources.viewMode.tree": "树状视图",diff --git a/package.json b/package.jsonindex 6997d987d13..36a08f53965 100644--- a/package.json+++ b/package.json@@ -290,6 +290,7 @@"@opentelemetry/resources": "^2.2.0","@opentelemetry/sdk-metrics": "^2.2.0","@opentelemetry/winston-transport": "^0.19.0",+ "@pierre/trees": "1.0.0-beta.3","@react-pdf/renderer": "4.4.1","@react-three/drei": "^10.7.7","@react-three/fiber": "^9.5.0",diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsxnew file mode 100644index 00000000000..6b991eddf79--- /dev/null+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx@@ -0,0 +1,53 @@+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { FilePlusIcon, FolderPlusIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++const styles = createStaticStyles(({ css, cssVar }) => ({+ toolbar: css`+ padding-block: 4px;+ padding-inline: 12px 4px;+ color: ${cssVar.colorTextSecondary};+ `,+ title: css`+ font-size: 11px;+ font-weight: 500;+ text-transform: uppercase;+ letter-spacing: 0.02em;+ `,+}));++interface Props {+ onCreateDocument: () => void;+ onCreateFolder: () => void;+}++const DocumentExplorerToolbar = memo<Props>(({ onCreateDocument, onCreateFolder }) => {+ const { t } = useTranslation('chat');+ return (+ <Flexbox horizontal align={'center'} className={styles.toolbar} distribution={'space-between'}>+ <Text className={styles.title} type={'secondary'}>+ {t('workingPanel.resources.filter.documents')}+ </Text>+ <Flexbox horizontal gap={2}>+ <ActionIcon+ icon={FolderPlusIcon}+ size={'small'}+ title={t('workingPanel.resources.tree.newFolder')}+ onClick={onCreateFolder}+ />+ <ActionIcon+ icon={FilePlusIcon}+ size={'small'}+ title={t('workingPanel.resources.tree.newDocument')}+ onClick={onCreateDocument}+ />+ </Flexbox>+ </Flexbox>+ );+});++DocumentExplorerToolbar.displayName = 'DocumentExplorerToolbar';++export default DocumentExplorerToolbar;diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxnew file mode 100644index 00000000000..1c3f1d5d745--- /dev/null+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -0,0 +1,232 @@+import type { MenuProps } from 'antd';+import { createStaticStyles } from 'antd-style';+import { Trash2Icon } from 'lucide-react';+import { type CSSProperties, memo, useCallback, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';+import { useMatch, useNavigate } from 'react-router-dom';+import type { KeyedMutator } from 'swr';++import {+ ExplorerTree,+ type ExplorerTreeCanDropCtx,+ type ExplorerTreeHandle,+ type ExplorerTreeNode,+} from '@/features/ExplorerTree';+import { useChatStore } from '@/store/chat';++import DocumentExplorerToolbar from './DocumentExplorerToolbar';+import { useDocumentTreeOps } from './hooks/useDocumentTreeOps';+import { type AgentDocumentItem, isFolderItem } from './types';+import { canDropDocument } from './utils/canDrop';++const PAGE_ROUTE_PATTERN = '/agent/:aid/:topicId/page/:docId?';++const styles = createStaticStyles(({ css, cssVar }) => ({+ tree: css`+ --trees-bg-override: transparent;+ --trees-border-color-override: transparent;+ --trees-selected-bg-override: ${cssVar.colorFillSecondary};+ --trees-bg-muted-override: ${cssVar.colorFillTertiary};+ --trees-fg-override: ${cssVar.colorText};+ --trees-fg-muted-override: ${cssVar.colorTextSecondary};+ --trees-accent-override: ${cssVar.colorPrimary};+ --trees-padding-inline-override: 0px;+ --trees-font-size-override: 12px;+ --trees-border-radius-override: 6px;+ `,+}));++interface Props {+ agentId: string;+ data: AgentDocumentItem[];+ mutate: KeyedMutator<AgentDocumentItem[]>;+ style?: CSSProperties;+}++const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {+ const { t } = useTranslation(['chat', 'common']);+ const navigate = useNavigate();+ const pageMatch = useMatch(PAGE_ROUTE_PATTERN);+ const openDocument = useChatStore((s) => s.openDocument);+ const treeRef = useRef<ExplorerTreeHandle | null>(null);++ const startInlineRename = useCallback((id: string) => {+ treeRef.current?.startRenaming(id);+ }, []);++ const ops = useDocumentTreeOps({+ agentId,+ data,+ mutate,+ topicId: pageMatch?.params.topicId,+ });++ const documents = useMemo(() => data.filter((doc) => doc.sourceType !== 'web'), [data]);++ // AgentDocument.parentId references the parent's documentId (FK to documents.id),+ // but ExplorerTree's flat layout expects parentId to point at another node's+ // tree-node id (= row id here). Translate via documentId → row id.+ const rowIdByDocumentId = useMemo(() => {+ const map = new Map<string, string>();+ for (const doc of documents) map.set(doc.documentId, doc.id);+ return map;+ }, [documents]);++ const resolveParentRowId = useCallback(+ (parentDocumentId: string | null): string | null => {+ if (!parentDocumentId) return null;+ return rowIdByDocumentId.get(parentDocumentId) ?? null;+ },+ [rowIdByDocumentId],+ );++ const nodes = useMemo<ExplorerTreeNode<AgentDocumentItem>[]>(+ () =>+ documents.map((doc) => ({+ data: doc,+ id: doc.id,+ isFolder: isFolderItem(doc),+ name: doc.title || doc.filename || '',+ parentId: resolveParentRowId(doc.parentId),+ })),+ [documents, resolveParentRowId],+ );++ const parentMap = useMemo(() => {+ const map = new Map<string, string | null>();+ for (const doc of documents) map.set(doc.id, resolveParentRowId(doc.parentId));+ return map;+ }, [documents, resolveParentRowId]);++ const handleCreateFolder = useCallback(+ (parentId: string | null) => ops.createFolder(parentId),+ [ops],+ );+ const handleCreateDocument = useCallback(+ (parentId: string | null) => ops.createDocument(parentId),+ [ops],+ );++ const handleNodeClick = useCallback(+ (node: ExplorerTreeNode<AgentDocumentItem>) => {+ const doc = node.data;+ if (!doc || node.isFolder) return;+ if (pageMatch?.params.aid && pageMatch.params.topicId) {+ navigate(+ `/agent/${pageMatch.params.aid}/${pageMatch.params.topicId}/page/${doc.documentId}`,+ );+ return;+ }+ openDocument(doc.documentId);+ },+ [navigate, openDocument, pageMatch?.params.aid, pageMatch?.params.topicId],+ );++ const handleCommitRename = useCallback(+ async (node: ExplorerTreeNode<AgentDocumentItem>, newName: string) => {+ await ops.renameDocument(node.id, newName);+ },+ [ops],+ );++ const handleMove = useCallback(+ async (event: {+ newParentId: string | null;+ sourceIds: string[];+ sourceNodes: ExplorerTreeNode<AgentDocumentItem>[];+ }) => {+ await ops.moveDocument({+ sourceIds: event.sourceIds,+ sourceNodes: event.sourceNodes,+ targetId: event.newParentId,+ });+ },+ [ops],+ );++ const canDrag = useCallback(+ (node: ExplorerTreeNode<AgentDocumentItem>) => node.data?.sourceType !== 'web',+ [],+ );++ const canRename = useCallback(+ (node: ExplorerTreeNode<AgentDocumentItem>) => node.data?.sourceType !== 'web',+ [],+ );++ const canDrop = useCallback(+ (ctx: ExplorerTreeCanDropCtx<AgentDocumentItem>) => canDropDocument({ ctx, parentMap }),+ [parentMap],+ );++ const getContextMenuItems = useCallback(+ (node: ExplorerTreeNode<AgentDocumentItem>): MenuProps['items'] => {+ const isFolder = !!node.isFolder;+ const targetParentId = isFolder ? node.id : (node.parentId ?? null);++ const items: NonNullable<MenuProps['items']> = [];++ if (isFolder) {+ items.push(+ {+ key: 'new-folder',+ label: t('workingPanel.resources.tree.newFolder'),+ onClick: () => handleCreateFolder(targetParentId),+ },+ {+ key: 'new-document',+ label: t('workingPanel.resources.tree.newDocument'),+ onClick: () => handleCreateDocument(targetParentId),+ },+ { key: 'div-1', type: 'divider' },+ );+ }++ items.push(+ {+ key: 'rename',+ label: t('workingPanel.resources.tree.rename'),+ onClick: () => startInlineRename(node.id),+ },+ {+ danger: true,+ icon: <Trash2Icon size={14} />,+ key: 'delete',+ label: t('delete', { ns: 'common' }),+ onClick: () => ops.deleteDocument(node.id),+ },+ );++ return items;+ },+ [handleCreateDocument, handleCreateFolder, ops, startInlineRename, t],+ );++ return (+ <div className={styles.tree} style={style}>+ <ExplorerTree<AgentDocumentItem>+ canDrag={canDrag}+ canDrop={canDrop}+ canRename={canRename}+ density="relaxed"+ getContextMenuItems={getContextMenuItems}+ nodes={nodes}+ ref={treeRef}+ style={{ height: '100%' }}+ header={+ <DocumentExplorerToolbar+ onCreateDocument={() => handleCreateDocument(null)}+ onCreateFolder={() => handleCreateFolder(null)}+ />+ }+ onCommitRename={handleCommitRename}+ onMove={handleMove}+ onNodeClick={handleNodeClick}+ />+ </div>+ );+});++DocumentExplorerTree.displayName = 'DocumentExplorerTree';++export default DocumentExplorerTree;diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.tsnew file mode 100644index 00000000000..528a3bdd5a1--- /dev/null+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts@@ -0,0 +1,323 @@+import { confirmModal } from '@lobehub/ui/base-ui';+import { App } from 'antd';+import { useCallback, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';+import type { KeyedMutator } from 'swr';++import { agentDocumentService } from '@/services/agentDocument';++import { type AgentDocumentItem, FOLDER_FILE_TYPE } from '../types';++interface UseDocumentTreeOpsArgs {+ agentId: string;+ data: AgentDocumentItem[];+ mutate: KeyedMutator<AgentDocumentItem[]>;+ topicId?: string;+}++const ROOT_PATH = './';++const joinPath = (parentPath: string, segment: string) =>+ parentPath === ROOT_PATH ? `${ROOT_PATH}${segment}` : `${parentPath}/${segment}`;++export interface DocumentTreeOps {+ createDocument: (parentId: string | null) => Promise<void>;+ createFolder: (parentId: string | null) => Promise<void>;+ deleteDocument: (id: string) => void;+ moveDocument: (params: {+ sourceIds: string[];+ sourceNodes: { data?: AgentDocumentItem }[];+ targetId: string | null;+ }) => Promise<void>;+ renameDocument: (id: string, newName: string) => Promise<void>;+}++export const useDocumentTreeOps = ({+ agentId,+ data,+ mutate,+ topicId,+}: UseDocumentTreeOpsArgs): DocumentTreeOps => {+ const { t } = useTranslation(['chat', 'common']);+ const { message } = App.useApp();+ const dataRef = useRef(data);+ dataRef.current = data;++ const byRowId = useMemo(() => {+ const map = new Map<string, AgentDocumentItem>();+ for (const doc of data) map.set(doc.id, doc);+ return map;+ }, [data]);++ const byDocumentId = useMemo(() => {+ const map = new Map<string, AgentDocumentItem>();+ for (const doc of data) map.set(doc.documentId, doc);+ return map;+ }, [data]);++ // Walk up via item.parentId (= parent's documentId) until we hit the root.+ const buildItemPath = useCallback(+ (item: AgentDocumentItem): string | null => {+ const segments: string[] = [item.filename];+ let parentDocId = item.parentId;+ while (parentDocId) {+ const parent = byDocumentId.get(parentDocId);+ if (!parent) return null;+ segments.unshift(parent.filename);+ parentDocId = parent.parentId;+ }+ return `${ROOT_PATH}${segments.join('/')}`;+ },+ [byDocumentId],+ );++ // Resolves the parent's path given a tree-node parent id (= row id) or null.+ const buildParentPathFromRowId = useCallback(+ (parentRowId: string | null): string | null => {+ if (parentRowId === null) return ROOT_PATH;+ const parent = byRowId.get(parentRowId);+ if (!parent) return null;+ return buildItemPath(parent);+ },+ [byRowId, buildItemPath],+ );++ // Picks a unique filename within the given parent. Used for client-side+ // dedup of "Untitled" rows because the path-based VFS mkdir is idempotent+ // (same name re-uses the existing folder), and writeByPath in always-new+ // mode rejects collisions outright.+ const pickUniqueFilename = useCallback(+ (parentDocumentId: string | null, baseName: string): string => {+ const siblings = dataRef.current.filter((doc) => (doc.parentId ?? null) === parentDocumentId);+ const taken = new Set(siblings.map((doc) => doc.filename));+ if (!taken.has(baseName)) return baseName;+ for (let i = 2; i < 1000; i += 1) {+ const candidate = `${baseName} ${i}`;+ if (!taken.has(candidate)) return candidate;+ }+ return `${baseName} ${Date.now()}`;+ },+ [],+ );++ const createFolder = useCallback(+ async (parentId: string | null) => {+ const parentPath = buildParentPathFromRowId(parentId);+ if (parentPath === null) {+ message.error(t('workingPanel.resources.tree.parentMissing'));+ return;+ }++ const parentDocumentId = parentId ? (byRowId.get(parentId)?.documentId ?? null) : null;+ const baseName = t('workingPanel.resources.tree.untitledFolder');+ const filename = pickUniqueFilename(parentDocumentId, baseName);+ const targetPath = joinPath(parentPath, filename);++ try {+ await agentDocumentService.createFolder({ agentId, path: targetPath });+ await mutate();+ } catch (error) {+ message.error(+ error instanceof Error+ ? `${t('workingPanel.resources.tree.createError')}: ${error.message}`+ : t('workingPanel.resources.tree.createError'),+ );+ }+ },+ [agentId, buildParentPathFromRowId, byRowId, message, mutate, pickUniqueFilename, t],+ );++ const createDocument = useCallback(+ async (parentId: string | null) => {+ const parentPath = buildParentPathFromRowId(parentId);+ if (parentPath === null) {+ message.error(t('workingPanel.resources.tree.parentMissing'));+ return;+ }++ const baseName = t('workingPanel.resources.tree.untitledDocument');++ try {+ if (parentPath === ROOT_PATH) {+ // Server's createDocument auto-deduplicates filenames at the root.+ await agentDocumentService.createDocument({+ agentId,+ content: '',+ title: baseName,+ });+ } else {+ const parentDocumentId = parentId ? (byRowId.get(parentId)?.documentId ?? null) : null;+ const filename = pickUniqueFilename(parentDocumentId, baseName);+ await agentDocumentService.writeByPath({+ agentId,+ content: '',+ createMode: 'always-new',+ path: joinPath(parentPath, filename),+ });+ }+ await mutate();+ } catch (error) {+ message.error(+ error instanceof Error+ ? `${t('workingPanel.resources.tree.createError')}: ${error.message}`+ : t('workingPanel.resources.tree.createError'),+ );+ }+ },+ [agentId, buildParentPathFromRowId, byRowId, message, mutate, pickUniqueFilename, t],+ );++ const renameDocument = useCallback(+ async (id: string, newName: string) => {+ const target = dataRef.current.find((doc) => doc.id === id);+ if (!target) return;++ const trimmed = newName.trim();+ if (!trimmed) {+ message.warning(t('workingPanel.resources.renameEmpty'));+ return;+ }+ if (trimmed === target.title) return;++ mutate(+ (prev) =>+ (prev ?? []).map((doc) =>+ doc.id === id ? { ...doc, filename: trimmed, title: trimmed } : doc,+ ),+ { revalidate: false },+ );++ try {+ await agentDocumentService.renameDocument({ agentId, id, newTitle: trimmed });+ message.success(t('workingPanel.resources.renameSuccess'));+ } catch (error) {+ // rollback+ mutate(+ (prev) =>+ (prev ?? []).map((doc) =>+ doc.id === id ? { ...doc, filename: target.filename, title: target.title } : doc,+ ),+ { revalidate: false },+ );+ message.error(+ error instanceof Error ? error.message : t('workingPanel.resources.renameError'),+ );+ }+ },+ [agentId, message, mutate, t],+ );++ const moveDocument: DocumentTreeOps['moveDocument'] = useCallback(+ async ({ sourceIds, sourceNodes, targetId }) => {+ if (sourceIds.length === 0) return;++ const targetParentPath = buildParentPathFromRowId(targetId);+ if (targetParentPath === null) {+ message.error(t('workingPanel.resources.tree.parentMissing'));+ return;+ }++ const targetItem = targetId ? byRowId.get(targetId) : null;+ const targetParentDocId = targetItem ? targetItem.documentId : null;++ const moves: Array<{ fromPath: string; id: string; toPath: string }> = [];+ for (const id of sourceIds) {+ const node = sourceNodes.find((n) => n.data?.id === id)?.data;+ if (!node) continue;+ const fromPath = buildItemPath(node);+ if (!fromPath) continue;+ const toPath = joinPath(targetParentPath, node.filename);+ if (fromPath === toPath) continue;+ moves.push({ fromPath, id, toPath });+ }++ if (moves.length === 0) return;++ // Optimistic: reparent each source row to the new parent's documentId.+ const movedIds = new Set(moves.map((m) => m.id));+ mutate(+ (prev) =>+ (prev ?? []).map((doc) =>+ movedIds.has(doc.id) ? { ...doc, parentId: targetParentDocId } : doc,+ ),+ { revalidate: false },+ );++ const errors: Error[] = [];+ for (const move of moves) {+ try {+ await agentDocumentService.moveDocument({+ agentId,+ fromPath: move.fromPath,+ toPath: move.toPath,+ });+ } catch (error) {+ errors.push(error instanceof Error ? error : new Error(String(error)));+ }+ }++ await mutate();++ if (errors.length > 0) {+ const detail = errors.map((e) => e.message).join('; ');+ message.error(`${t('workingPanel.resources.tree.moveError')}: ${detail}`);+ }+ },+ [agentId, buildItemPath, buildParentPathFromRowId, byRowId, message, mutate, t],+ );++ const deleteDocument = useCallback(+ (id: string) => {+ const target = dataRef.current.find((doc) => doc.id === id);+ if (!target) return;++ confirmModal({+ content: t('workingPanel.resources.deleteConfirm'),+ okButtonProps: { danger: true },+ okText: t('delete', { ns: 'common' }),+ onOk: async () => {+ try {+ const isFolder = target.fileType === FOLDER_FILE_TYPE;+ if (isFolder) {+ const path = buildItemPath(target);+ if (path === null) {+ throw new Error(t('workingPanel.resources.tree.parentMissing'));+ }+ await agentDocumentService.deleteByPath({+ agentId,+ path,+ recursive: true,+ });+ } else {+ await agentDocumentService.removeDocument({+ agentId,+ documentId: target.documentId,+ id: target.id,+ topicId,+ });+ }+ await mutate();+ message.success(t('workingPanel.resources.deleteSuccess'));+ } catch (error) {+ message.error(+ error instanceof Error ? error.message : t('workingPanel.resources.deleteError'),+ );+ }+ },+ title: t('workingPanel.resources.deleteTitle'),+ });+ },+ [agentId, buildItemPath, message, mutate, t, topicId],+ );++ return useMemo(+ () => ({+ createDocument,+ createFolder,+ deleteDocument,+ moveDocument,+ renameDocument,+ }),+ [createDocument, createFolder, deleteDocument, moveDocument, renameDocument],+ );+};diff --git a/src/features/AgentDocumentsExplorer/index.ts b/src/features/AgentDocumentsExplorer/index.tsnew file mode 100644index 00000000000..085be76d122--- /dev/null+++ b/src/features/AgentDocumentsExplorer/index.ts@@ -0,0 +1,2 @@+export { default as DocumentExplorerTree } from './DocumentExplorerTree';+export type { AgentDocumentItem } from './types';diff --git a/src/features/AgentDocumentsExplorer/types.ts b/src/features/AgentDocumentsExplorer/types.tsnew file mode 100644index 00000000000..cc787fa3c28--- /dev/null+++ b/src/features/AgentDocumentsExplorer/types.ts@@ -0,0 +1,13 @@+import type { agentDocumentService } from '@/services/agentDocument';++export type AgentDocumentItem = Awaited<+ ReturnType<typeof agentDocumentService.getDocuments>+>[number];++export const PENDING_ID_PREFIX = 'pending:';++export const isPendingId = (id: string): boolean => id.startsWith(PENDING_ID_PREFIX);++export const FOLDER_FILE_TYPE = 'custom/folder';++export const isFolderItem = (doc: AgentDocumentItem): boolean => doc.fileType === FOLDER_FILE_TYPE;diff --git a/src/features/AgentDocumentsExplorer/utils/canDrop.ts b/src/features/AgentDocumentsExplorer/utils/canDrop.tsnew file mode 100644index 00000000000..e1dc41e3554--- /dev/null+++ b/src/features/AgentDocumentsExplorer/utils/canDrop.ts@@ -0,0 +1,54 @@+import type { ExplorerTreeCanDropCtx } from '@/features/ExplorerTree';++import { type AgentDocumentItem, isPendingId } from '../types';++interface CanDropArgs {+ ctx: ExplorerTreeCanDropCtx<AgentDocumentItem>;+ parentMap: Map<string, string | null>;+}++const isAncestor = (+ ancestorId: string,+ descendantId: string,+ parentMap: Map<string, string | null>,+): boolean => {+ let cursor: string | null | undefined = parentMap.get(descendantId);+ while (cursor) {+ if (cursor === ancestorId) return true;+ cursor = parentMap.get(cursor);+ }+ return false;+};++export const canDropDocument = ({ ctx, parentMap }: CanDropArgs): boolean => {+ const { sourceIds, sourceNodes, targetId, targetNode } = ctx;+ if (sourceIds.length === 0) return false;++ // Drop target must be a folder or root+ if (targetNode && !targetNode.isFolder) return false;++ // Pending targets have no server-side row yet — refuse the drop instead of+ // surfacing an error after the fact.+ if (targetId && isPendingId(targetId)) return false;++ for (let i = 0; i < sourceNodes.length; i += 1) {+ const node = sourceNodes[i];+ const sourceId = sourceIds[i];++ // No-op: dropping into current parent+ const currentParent = parentMap.get(sourceId) ?? null;+ if (currentParent === targetId) return false;++ // Cycle: folder cannot be dropped into itself or any descendant+ if (node.isFolder && targetId) {+ if (sourceId === targetId) return false;+ if (isAncestor(sourceId, targetId, parentMap)) return false;+ }++ // Web docs cannot move (not part of tree management)+ const data = node.data;+ if (data && data.sourceType === 'web') return false;+ }++ return true;+};diff --git a/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts b/src/features/AgentDocumentsExplorer/utils/pendingDocument.tsnew file mode 100644index 00000000000..784d804984d--- /dev/null+++ b/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts@@ -0,0 +1,52 @@+import { nanoid } from 'nanoid';++import { type AgentDocumentItem, FOLDER_FILE_TYPE, PENDING_ID_PREFIX } from '../types';++interface MakePendingArgs {+ agentId: string;+ isFolder: boolean;+ parentId: string | null;+ title: string;+}++export const makePendingDocument = ({+ agentId,+ isFolder,+ parentId,+ title,+}: MakePendingArgs): AgentDocumentItem => {+ const id = `${PENDING_ID_PREFIX}${nanoid(10)}`;+ const now = new Date();+ return {+ accessPublic: 0,+ accessSelf: 1,+ accessShared: 0,+ agentId,+ content: '',+ createdAt: now,+ deletedAt: null,+ deletedByAgentId: null,+ deletedByUserId: null,+ deleteReason: null,+ description: null,+ documentId: id,+ editorData: null,+ filename: title,+ fileType: isFolder ? FOLDER_FILE_TYPE : 'custom/document',+ id,+ loadRules: {} as AgentDocumentItem['loadRules'],+ metadata: null,+ parentId,+ policy: null,+ policyLoad: 'always' as AgentDocumentItem['policyLoad'],+ policyLoadFormat: 'raw' as AgentDocumentItem['policyLoadFormat'],+ policyLoadPosition: '',+ policyLoadRule: '',+ source: null,+ sourceType: 'agent',+ templateId: null,+ title,+ updatedAt: now,+ userId: '',+ };+};diff --git a/src/features/ExplorerTree/adapter/index.ts b/src/features/ExplorerTree/adapter/index.tsnew file mode 100644index 00000000000..ec417b8a95a--- /dev/null+++ b/src/features/ExplorerTree/adapter/index.ts@@ -0,0 +1,9 @@+export {+ arrayEqual,+ isDescendantOf,+ type NormalizedTree,+ normalizeTree,+ remapIdsToPaths,+ remapPathsToIds,+} from './normalize';+export { buildSegment, extractName } from './path';diff --git a/src/features/ExplorerTree/adapter/normalize.test.ts b/src/features/ExplorerTree/adapter/normalize.test.tsnew file mode 100644index 00000000000..23fc7691708--- /dev/null+++ b/src/features/ExplorerTree/adapter/normalize.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import type { ExplorerTreeNode } from '../types';+import { isDescendantOf, normalizeTree, remapIdsToPaths, remapPathsToIds } from './normalize';++describe('normalizeTree', () => {+ it('keeps duplicate sibling names addressable by stable ids', () => {+ const nodes: ExplorerTreeNode[] = [+ { id: 'folder-a', isFolder: true, name: 'Docs', parentId: null },+ { id: 'folder-b', isFolder: true, name: 'Docs', parentId: null },+ { id: 'file-a', name: 'README.md', parentId: 'folder-a' },+ ];++ const tree = normalizeTree(nodes);++ expect(tree.pathById.get('folder-a')).toBe('Docs/');+ expect(tree.pathById.get('folder-b')).toBe('Docs (2)/');+ expect(tree.pathById.get('file-a')).toBe('Docs/README.md');+ expect(+ remapPathsToIds(remapIdsToPaths(['folder-b', 'file-a'], tree.pathById), tree.idByPath),+ ).toEqual(['folder-b', 'file-a']);+ });++ it('detects descendants by parent id mapping', () => {+ const tree = normalizeTree([+ {+ children: [+ {+ children: [{ id: 'file-a', name: 'a.md' }],+ id: 'folder-child',+ isFolder: true,+ name: 'Child',+ },+ ],+ id: 'folder-root',+ isFolder: true,+ name: 'Root',+ },+ ]);++ expect(isDescendantOf('folder-child', 'folder-root', tree.parentIdById)).toBe(true);+ expect(isDescendantOf('file-a', 'folder-root', tree.parentIdById)).toBe(true);+ expect(isDescendantOf('folder-root', 'folder-child', tree.parentIdById)).toBe(false);+ });+});diff --git a/src/features/ExplorerTree/adapter/normalize.ts b/src/features/ExplorerTree/adapter/normalize.tsnew file mode 100644index 00000000000..48d53a680d4--- /dev/null+++ b/src/features/ExplorerTree/adapter/normalize.ts@@ -0,0 +1,142 @@+import type { ExplorerTreeNode } from '../types';+import { buildSegment } from './path';++export interface NormalizedTree<TData> {+ idByPath: Map<string, string>;+ nodeById: Map<string, ExplorerTreeNode<TData>>;+ parentIdById: Map<string, string | null>;+ pathById: Map<string, string>;+ paths: string[];+}++const dedupeName = (taken: Set<string>, baseName: string, isFolder: boolean): string => {+ const segment = buildSegment(baseName, isFolder);+ if (!taken.has(segment)) {+ taken.add(segment);+ return baseName;+ }+ // split name / ext for nicer suffixes on files+ const dotIndex = isFolder ? -1 : baseName.lastIndexOf('.');+ const stem = dotIndex > 0 ? baseName.slice(0, dotIndex) : baseName;+ const ext = dotIndex > 0 ? baseName.slice(dotIndex) : '';+ for (let i = 2; i < 10_000; i += 1) {+ const candidate = `${stem} (${i})${ext}`;+ const seg = buildSegment(candidate, isFolder);+ if (!taken.has(seg)) {+ taken.add(seg);+ return candidate;+ }+ }+ const fallback = `${stem}-${Math.random().toString(36).slice(2, 8)}${ext}`;+ taken.add(buildSegment(fallback, isFolder));+ return fallback;+};++export const normalizeTree = <TData>(nodes: ExplorerTreeNode<TData>[]): NormalizedTree<TData> => {+ const pathById = new Map<string, string>();+ const idByPath = new Map<string, string>();+ const nodeById = new Map<string, ExplorerTreeNode<TData>>();+ const parentIdById = new Map<string, string | null>();+ const paths: string[] = [];++ const hasChildrenTree = nodes.some((n) => Array.isArray(n.children));+ if (hasChildrenTree) {+ const walk = (+ siblings: ExplorerTreeNode<TData>[],+ parentPath: string,+ parentId: string | null,+ ) => {+ const taken = new Set<string>();+ for (const node of siblings) {+ const uniqueName = dedupeName(taken, node.name, !!node.isFolder);+ const segment = buildSegment(uniqueName, !!node.isFolder);+ const fullPath = parentPath + segment;+ pathById.set(node.id, fullPath);+ idByPath.set(fullPath, node.id);+ nodeById.set(node.id, node);+ parentIdById.set(node.id, parentId);+ paths.push(fullPath);+ if (node.children?.length) {+ const nextParent = node.isFolder ? fullPath : parentPath;+ walk(node.children, nextParent, node.id);+ }+ }+ };+ walk(nodes, '', null);+ return { idByPath, nodeById, parentIdById, pathById, paths };+ }++ // flat form (parentId)+ const byParent = new Map<string | null, ExplorerTreeNode<TData>[]>();+ for (const node of nodes) {+ const key = node.parentId ?? null;+ const bucket = byParent.get(key);+ if (bucket) bucket.push(node);+ else byParent.set(key, [node]);+ }++ const walkFlat = (parentId: string | null, parentPath: string) => {+ const siblings = byParent.get(parentId);+ if (!siblings) return;+ const taken = new Set<string>();+ for (const node of siblings) {+ const uniqueName = dedupeName(taken, node.name, !!node.isFolder);+ const segment = buildSegment(uniqueName, !!node.isFolder);+ const fullPath = parentPath + segment;+ pathById.set(node.id, fullPath);+ idByPath.set(fullPath, node.id);+ nodeById.set(node.id, node);+ parentIdById.set(node.id, parentId);+ paths.push(fullPath);+ if (node.isFolder) walkFlat(node.id, fullPath);+ }+ };+ walkFlat(null, '');+ return { idByPath, nodeById, parentIdById, pathById, paths };+};++export const remapIdsToPaths = (+ ids: readonly string[] | undefined,+ pathById: Map<string, string>,+): string[] => {+ if (!ids?.length) return [];+ const out: string[] = [];+ for (const id of ids) {+ const p = pathById.get(id);+ if (p) out.push(p);+ }+ return out;+};++export const remapPathsToIds = (+ paths: readonly string[] | undefined,+ idByPath: Map<string, string>,+): string[] => {+ if (!paths?.length) return [];+ const out: string[] = [];+ for (const p of paths) {+ const id = idByPath.get(p);+ if (id) out.push(id);+ }+ return out;+};++export const arrayEqual = (a: readonly string[], b: readonly string[]): boolean => {+ if (a === b) return true;+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;+ return true;+};++export const isDescendantOf = (+ nodeId: string,+ possibleAncestorId: string,+ parentIdById: Map<string, string | null>,+): boolean => {+ let cursor = parentIdById.get(nodeId) ?? null;+ while (cursor) {+ if (cursor === possibleAncestorId) return true;+ cursor = parentIdById.get(cursor) ?? null;+ }+ return false;+};diff --git a/src/features/ExplorerTree/adapter/path.ts b/src/features/ExplorerTree/adapter/path.tsnew file mode 100644index 00000000000..caccd3d6a89--- /dev/null+++ b/src/features/ExplorerTree/adapter/path.ts@@ -0,0 +1,13 @@+const encodeSegment = (value: string): string => value.replaceAll('/', '/').replaceAll('\\', '\');++export const buildSegment = (name: string, isFolder: boolean): string => {+ const segment = encodeSegment(name);+ return isFolder ? `${segment}/` : segment;+};++export const extractName = (path: string): string => {+ const trimmed = path.endsWith('/') ? path.slice(0, -1) : path;+ const lastSep = trimmed.lastIndexOf('/');+ const leaf = lastSep >= 0 ? trimmed.slice(lastSep + 1) : trimmed;+ return leaf.replaceAll('/', '/').replaceAll('\', '\\');+};diff --git a/src/features/ExplorerTree/index.tsx b/src/features/ExplorerTree/index.tsxnew file mode 100644index 00000000000..5ebda21b31e--- /dev/null+++ b/src/features/ExplorerTree/index.tsx@@ -0,0 +1,9 @@+export type {+ ExplorerTreeCanDropCtx,+ ExplorerTreeHandle,+ ExplorerTreeMoveEvent,+ ExplorerTreeNode,+ ExplorerTreeProps,+ ExplorerTreeRowDecorationCtx,+} from './types';+export { default as ExplorerTree } from './view/ExplorerTree';diff --git a/src/features/ExplorerTree/types.ts b/src/features/ExplorerTree/types.tsnew file mode 100644index 00000000000..06479894609--- /dev/null+++ b/src/features/ExplorerTree/types.ts@@ -0,0 +1,82 @@+import type { FileTreeRowDecoration } from '@pierre/trees';+import type { MenuProps } from 'antd';+import type { CSSProperties, DragEvent, MouseEvent, ReactNode } from 'react';++export interface ExplorerTreeNode<TData = unknown> {+ children?: ExplorerTreeNode<TData>[];+ data?: TData;+ id: string;+ isFolder?: boolean;+ name: string;+ parentId?: string | null;+}++export interface ExplorerTreeMoveEvent<TData = unknown> {+ /** @deprecated Transitional compatibility for the current @pierre/trees bridge. */+ index?: number;+ newParentId: string | null;+ oldParentId: string | null;+ sourceIds: string[];+ sourceNodes: ExplorerTreeNode<TData>[];+ targetId: string | null;+ targetNode: ExplorerTreeNode<TData> | null;+}++export interface ExplorerTreeCanDropCtx<TData = unknown> {+ sourceIds: string[];+ sourceNodes: ExplorerTreeNode<TData>[];+ targetId: string | null;+ targetNode: ExplorerTreeNode<TData> | null;+}++export interface ExplorerTreeRowDecorationCtx<TData = unknown> {+ node: ExplorerTreeNode<TData>;+}++export interface ExplorerTreeHandle {+ deselect: (id: string) => void;+ focus: (id: string) => void;+ getSelectedIds: () => string[];+ select: (id: string, opts?: { additive?: boolean }) => void;+ setExpanded: (ids: string[]) => void;+ startRenaming: (id: string) => void;+}++export interface ExplorerTreeProps<TData = unknown> {+ canDrag?: (node: ExplorerTreeNode<TData>) => boolean;+ canDrop?: (ctx: ExplorerTreeCanDropCtx<TData>) => boolean;+ canRename?: (node: ExplorerTreeNode<TData>) => boolean;+ className?: string;+ /** @deprecated Use defaultExpandedIds instead. */+ defaultExpanded?: string[];+ defaultExpandedIds?: string[];+ /** @deprecated Use defaultSelectedIds instead. */+ defaultSelected?: string[];+ defaultSelectedIds?: string[];+ density?: 'compact' | 'default' | 'relaxed' | number;+ expandedIds?: string[];+ getContextMenuItems?: (node: ExplorerTreeNode<TData>) => MenuProps['items'];+ getRowDecoration?: (+ ctx: ExplorerTreeRowDecorationCtx<TData>,+ ) => FileTreeRowDecoration | null | undefined;+ header?: ReactNode;+ iconsColored?: boolean;+ iconSet?: 'minimal' | 'standard' | 'complete' | 'none';+ itemHeight?: number;+ nodes: ExplorerTreeNode<TData>[];+ onCommitRename?: (node: ExplorerTreeNode<TData>, newName: string) => void | Promise<void>;+ onExpandedChange?: (ids: string[]) => void;+ onExternalDrop?: (event: {+ nativeEvent: DragEvent<HTMLElement>;+ targetId: string | null;+ targetNode: ExplorerTreeNode<TData> | null;+ }) => void;+ onMove?: (event: ExplorerTreeMoveEvent<TData>) => void | Promise<void>;+ onNodeClick?: (node: ExplorerTreeNode<TData>, event: MouseEvent<HTMLElement>) => void;+ onNodeDragStart?: (node: ExplorerTreeNode<TData>, event: DragEvent<HTMLElement>) => void;+ onRenameError?: (error: unknown, node: ExplorerTreeNode<TData>) => void;+ onSelectedChange?: (ids: string[]) => void;+ overscan?: number;+ selectedIds?: string[];+ style?: CSSProperties;+}diff --git a/src/features/ExplorerTree/view/ContextMenu.tsx b/src/features/ExplorerTree/view/ContextMenu.tsxnew file mode 100644index 00000000000..6a535ae9524--- /dev/null+++ b/src/features/ExplorerTree/view/ContextMenu.tsx@@ -0,0 +1,28 @@+import { type ContextMenuItem, showContextMenu } from '@lobehub/ui';+import type { MenuProps } from 'antd';++type AntdItem = NonNullable<MenuProps['items']>[number];++// Defers the user's onClick to the next frame so base-ui's focus restoration+// on close completes before the action runs. Without this, actions like+// inline-rename briefly take focus and then lose it back to whatever was+// active before the menu opened, which makes the rename input invisible.+const wrapItem = (item: AntdItem): ContextMenuItem => {+ if (!item || typeof item !== 'object') return item as ContextMenuItem;+ const next = { ...(item as unknown as Record<string, unknown>) };+ if ('children' in item && Array.isArray((item as { children?: unknown }).children)) {+ next.children = (item as { children: AntdItem[] }).children.map((child) => wrapItem(child));+ }+ const original = (item as { onClick?: (...args: unknown[]) => void }).onClick;+ if (original) {+ next.onClick = (...args: unknown[]) => {+ requestAnimationFrame(() => original(...args));+ };+ }+ return next as unknown as ContextMenuItem;+};++export const openExplorerContextMenu = (items: MenuProps['items']) => {+ if (!items || items.length === 0) return;+ showContextMenu(items.map((item) => wrapItem(item as AntdItem)));+};diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsxnew file mode 100644index 00000000000..053afa06f31--- /dev/null+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx@@ -0,0 +1,510 @@+'use client';++import type {+ FileTreeDirectoryHandle,+ FileTreeItemHandle,+ FileTreeOptions,+ FileTreeRowDecoration,+} from '@pierre/trees';+import { FileTree as PierreFileTree, useFileTree, useFileTreeSelection } from '@pierre/trees/react';+import type { DragEvent, ForwardedRef, MouseEvent } from 'react';+import { forwardRef, useImperativeHandle, useLayoutEffect, useMemo, useRef } from 'react';++import {+ arrayEqual,+ type NormalizedTree,+ normalizeTree,+ remapIdsToPaths,+ remapPathsToIds,+} from '../adapter';+import { extractName } from '../adapter/path';+import type {+ ExplorerTreeHandle,+ ExplorerTreeMoveEvent,+ ExplorerTreeNode,+ ExplorerTreeProps,+} from '../types';+import { openExplorerContextMenu } from './ContextMenu';++const asDirectory = (+ handle: FileTreeItemHandle | null | undefined,+): FileTreeDirectoryHandle | null =>+ handle && handle.isDirectory() ? (handle as FileTreeDirectoryHandle) : null;++type ExplorerTreeHostEvent = DragEvent<HTMLElement> | MouseEvent<HTMLElement>;++const isHTMLElement = (target: EventTarget): target is HTMLElement => target instanceof HTMLElement;++const getComposedPath = (event: ExplorerTreeHostEvent): EventTarget[] => {+ const path = event.nativeEvent.composedPath();+ if (path.length > 0) return path;++ return [event.target, event.currentTarget].filter(+ (target): target is EventTarget => target != null,+ );+};++const getItemPathFromHostEvent = (event: ExplorerTreeHostEvent): string | null => {+ for (const target of getComposedPath(event)) {+ if (!isHTMLElement(target)) continue;+ if (target.dataset.type !== 'item') continue;+ const path = target.dataset.itemPath;+ if (path) return path;+ }++ return null;+};++function ExplorerTreeInner<TData>(+ props: ExplorerTreeProps<TData>,+ ref: ForwardedRef<ExplorerTreeHandle>,+) {+ const propsRef = useRef(props);+ propsRef.current = props;++ const adapterRef = useRef<NormalizedTree<TData>>(normalizeTree(props.nodes));++ // emitted values so we don't fire feedback loops on change listeners+ const lastEmittedSelectedIds = useRef<string[]>(+ props.defaultSelectedIds ?? props.defaultSelected ?? [],+ );+ const suppressModelEventsRef = useRef(false);+ const renamingRef = useRef(false);++ const initialOptions = useMemo((): FileTreeOptions => {+ const initial = adapterRef.current;+ const initialExpandedPaths = remapIdsToPaths(+ props.defaultExpandedIds ?? props.defaultExpanded,+ initial.pathById,+ );+ const initialSelectedPaths = remapIdsToPaths(+ props.defaultSelectedIds ?? props.defaultSelected,+ initial.pathById,+ );++ const toNodeOrNull = (path: string | null) =>+ path == null+ ? null+ : (adapterRef.current.nodeById.get(adapterRef.current.idByPath.get(path) ?? '') ?? null);++ return {+ density: props.density,+ dragAndDrop: {+ canDrag: (paths) => {+ const fn = propsRef.current.canDrag;+ if (!fn) return true;+ for (const p of paths) {+ const node = toNodeOrNull(p);+ if (!node || !fn(node)) return false;+ }+ return true;+ },+ canDrop: (event) => {+ const fn = propsRef.current.canDrop;+ if (!fn) return true;+ const a = adapterRef.current;+ const sourceIds = remapPathsToIds(event.draggedPaths, a.idByPath);+ const sourceNodes = sourceIds+ .map((id) => a.nodeById.get(id))+ .filter((n): n is ExplorerTreeNode<TData> => !!n);+ if (+ sourceIds.length !== event.draggedPaths.length ||+ sourceNodes.length !== sourceIds.length+ ) {+ return false;+ }+ // Use directoryPath (= the new parent), not hoveredPath. Hovering a+ // file row at root yields directoryPath=null (root) but hoveredPath+ // points at the file itself; conflating them blocks legitimate drops+ // because canDrop sees a file as the target zone.+ const newParentPath = event.target.directoryPath;+ const targetId = newParentPath ? (a.idByPath.get(newParentPath) ?? null) : null;+ return fn({+ sourceIds,+ sourceNodes,+ targetId,+ targetNode: targetId ? (a.nodeById.get(targetId) ?? null) : null,+ });+ },+ onDropComplete: (event) => {+ const onMove = propsRef.current.onMove;+ if (!onMove) return;+ const a = adapterRef.current;+ const sourceIds = remapPathsToIds(event.draggedPaths, a.idByPath);+ const sourceNodes = sourceIds+ .map((id) => a.nodeById.get(id))+ .filter((n): n is ExplorerTreeNode<TData> => !!n);+ const targetPath = event.target.hoveredPath ?? event.target.directoryPath;+ const targetId = targetPath ? (a.idByPath.get(targetPath) ?? null) : null;+ const newParentPath = event.target.directoryPath;+ const newParentId = newParentPath ? (a.idByPath.get(newParentPath) ?? null) : null;+ const parents = new Set(sourceIds.map((id) => a.parentIdById.get(id) ?? null));+ const oldParentId = parents.size === 1 ? [...parents][0] : null;+ const moveEvent: ExplorerTreeMoveEvent<TData> = {+ newParentId,+ oldParentId,+ sourceIds,+ sourceNodes,+ targetId,+ targetNode: targetId ? (a.nodeById.get(targetId) ?? null) : null,+ };+ void onMove(moveEvent);+ },+ },+ icons: {+ colored: props.iconsColored ?? true,+ set: props.iconSet ?? 'standard',+ },+ initialExpandedPaths,+ initialSelectedPaths,+ itemHeight: props.itemHeight,+ onSelectionChange: (paths) => {+ if (suppressModelEventsRef.current) return;+ const ids = remapPathsToIds(paths, adapterRef.current.idByPath);+ if (arrayEqual(ids, lastEmittedSelectedIds.current)) return;+ lastEmittedSelectedIds.current = ids;+ propsRef.current.onSelectedChange?.(ids);+ },+ overscan: props.overscan,+ paths: initial.paths,+ renaming: {+ canRename: (item) => {+ const node = adapterRef.current.nodeById.get(+ adapterRef.current.idByPath.get(item.path) ?? '',+ );+ if (!node) return false;+ const fn = propsRef.current.canRename;+ return fn ? fn(node) : !!propsRef.current.onCommitRename;+ },+ onError: (error) => {+ const node = renamingNodeRef.current;+ if (node) propsRef.current.onRenameError?.(error, node);+ },+ onRename: ({ sourcePath, destinationPath }) => {+ const a = adapterRef.current;+ const id = a.idByPath.get(sourcePath);+ if (!id) return;+ const node = a.nodeById.get(id);+ if (!node) return;+ renamingNodeRef.current = node;+ const newName = extractName(destinationPath);+ const result = propsRef.current.onCommitRename?.(node, newName);+ if (result && typeof (result as Promise<void>).then === 'function') {+ (result as Promise<void>).finally(() => {+ renamingNodeRef.current = null;+ renamingRef.current = false;+ });+ } else {+ renamingNodeRef.current = null;+ renamingRef.current = false;+ }+ },+ },+ renderRowDecoration: (ctx) => {+ const fn = propsRef.current.getRowDecoration;+ if (!fn) return null;+ const a = adapterRef.current;+ const id = a.idByPath.get(ctx.item.path);+ if (!id) return null;+ const node = a.nodeById.get(id);+ if (!node) return null;+ return (fn({ node }) as FileTreeRowDecoration | null) ?? null;+ },+ };+ // we build options ONCE; callbacks read propsRef to stay fresh+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const renamingNodeRef = useRef<ExplorerTreeNode<TData> | null>(null);+ const { model } = useFileTree(initialOptions);++ // Observe selection changes so external consumers see updates without needing to pass a selection listener.+ useFileTreeSelection(model);++ // Track expansion by subscribing to mutation events (expansion isn't a mutation — use subscribe).+ // We read expanded paths on demand from the visible rows via getItem; emit when defaultExpanded or nodes changes.+ useLayoutEffect(() => {+ return model.subscribe(() => {+ if (suppressModelEventsRef.current) return;+ const onChange = propsRef.current.onExpandedChange;+ if (!onChange) return;+ const a = adapterRef.current;+ const nextExpanded: string[] = [];+ for (const [id, path] of a.pathById) {+ const dir = asDirectory(model.getItem(path));+ if (dir?.isExpanded()) nextExpanded.push(id);+ }+ // Fire only when set differs; cheap comparison via sorted join+ const signature = nextExpanded.slice().sort().join('\n');+ if (signature === lastExpandedSignatureRef.current) return;+ lastExpandedSignatureRef.current = signature;+ onChange(nextExpanded);+ });+ }, [model]);++ const lastExpandedSignatureRef = useRef<string>('');++ useLayoutEffect(() => {+ const selectedIds = props.selectedIds;+ if (!selectedIds) return;+ const a = adapterRef.current;+ const nextSelectedPaths = remapIdsToPaths(selectedIds, a.pathById);+ const nextSelectedIds = remapPathsToIds(nextSelectedPaths, a.idByPath);+ const currentSelectedPaths = model.getSelectedPaths();+ const currentSelectedIds = remapPathsToIds(currentSelectedPaths, a.idByPath);+ lastEmittedSelectedIds.current = nextSelectedIds;+ if (arrayEqual(currentSelectedIds, nextSelectedIds)) return;++ const nextSelectedPathSet = new Set(nextSelectedPaths);+ suppressModelEventsRef.current = true;+ try {+ for (const path of currentSelectedPaths) {+ if (!nextSelectedPathSet.has(path)) model.getItem(path)?.deselect();+ }+ const currentSelectedPathSet = new Set(currentSelectedPaths);+ for (const path of nextSelectedPaths) {+ if (!currentSelectedPathSet.has(path)) model.getItem(path)?.select();+ }+ } finally {+ suppressModelEventsRef.current = false;+ }+ }, [props.selectedIds, model]);++ useLayoutEffect(() => {+ const expandedIds = props.expandedIds;+ if (!expandedIds) return;+ const a = adapterRef.current;+ const nextExpandedIdSet = new Set(expandedIds);+ const nextExpandedIds: string[] = [];+ const directoryEntries: { dir: FileTreeDirectoryHandle; shouldExpand: boolean }[] = [];+ for (const [id, path] of a.pathById) {+ const dir = asDirectory(model.getItem(path));+ if (!dir) continue;+ const shouldExpand = nextExpandedIdSet.has(id);+ if (shouldExpand) nextExpandedIds.push(id);+ directoryEntries.push({ dir, shouldExpand });+ }+ lastExpandedSignatureRef.current = nextExpandedIds.slice().sort().join('\n');+ suppressModelEventsRef.current = true;+ try {+ for (const { dir, shouldExpand } of directoryEntries) {+ if (shouldExpand && !dir.isExpanded()) dir.expand();+ else if (!shouldExpand && dir.isExpanded()) dir.collapse();+ }+ } finally {+ suppressModelEventsRef.current = false;+ }+ }, [props.expandedIds, model]);++ // nodes prop changes → resetPaths+ useLayoutEffect(() => {+ const next = normalizeTree(propsRef.current.nodes);+ const prev = adapterRef.current;+ if (arrayEqual(next.paths, prev.paths)) {+ adapterRef.current = next; // keep metadata fresh (name/data) even if paths identical+ const selectedIds = propsRef.current.selectedIds;+ if (selectedIds) {+ const nextSelectedPaths = remapIdsToPaths(selectedIds, next.pathById);+ const nextSelectedIds = remapPathsToIds(nextSelectedPaths, next.idByPath);+ const currentSelectedPaths = model.getSelectedPaths();+ const currentSelectedIds = remapPathsToIds(currentSelectedPaths, next.idByPath);+ lastEmittedSelectedIds.current = nextSelectedIds;+ if (!arrayEqual(currentSelectedIds, nextSelectedIds)) {+ const nextSelectedPathSet = new Set(nextSelectedPaths);+ suppressModelEventsRef.current = true;+ try {+ for (const path of currentSelectedPaths) {+ if (!nextSelectedPathSet.has(path)) model.getItem(path)?.deselect();+ }+ const currentSelectedPathSet = new Set(currentSelectedPaths);+ for (const path of nextSelectedPaths) {+ if (!currentSelectedPathSet.has(path)) model.getItem(path)?.select();+ }+ } finally {+ suppressModelEventsRef.current = false;+ }+ }+ }++ const expandedIds = propsRef.current.expandedIds;+ if (expandedIds) {+ const nextExpandedIdSet = new Set(expandedIds);+ const nextExpandedIds: string[] = [];+ const directoryEntries: { dir: FileTreeDirectoryHandle; shouldExpand: boolean }[] = [];+ for (const [id, path] of next.pathById) {+ const dir = asDirectory(model.getItem(path));+ if (!dir) continue;+ const shouldExpand = nextExpandedIdSet.has(id);+ if (shouldExpand) nextExpandedIds.push(id);+ directoryEntries.push({ dir, shouldExpand });+ }+ lastExpandedSignatureRef.current = nextExpandedIds.slice().sort().join('\n');+ suppressModelEventsRef.current = true;+ try {+ for (const { dir, shouldExpand } of directoryEntries) {+ if (shouldExpand && !dir.isExpanded()) dir.expand();+ else if (!shouldExpand && dir.isExpanded()) dir.collapse();+ }+ } finally {+ suppressModelEventsRef.current = false;+ }+ }+ return;+ }+ let nextExpandedIds = propsRef.current.expandedIds;+ if (!nextExpandedIds) {+ nextExpandedIds = [];+ for (const [id, path] of prev.pathById) {+ const dir = asDirectory(model.getItem(path));+ if (dir?.isExpanded()) nextExpandedIds.push(id);+ }+ }+ const nextSelectedIds =+ propsRef.current.selectedIds ?? remapPathsToIds(model.getSelectedPaths(), prev.idByPath);+ const focusedPath = model.getFocusedPath();+ const focusedId = focusedPath ? prev.idByPath.get(focusedPath) : null;++ adapterRef.current = next;+ const initialExpandedPaths = remapIdsToPaths(nextExpandedIds, next.pathById);+ lastExpandedSignatureRef.current = remapPathsToIds(initialExpandedPaths, next.idByPath)+ .slice()+ .sort()+ .join('\n');+ // restore selection+ const nextSelectedPaths = remapIdsToPaths(nextSelectedIds, next.pathById);+ lastEmittedSelectedIds.current = remapPathsToIds(nextSelectedPaths, next.idByPath);+ suppressModelEventsRef.current = true;+ try {+ model.resetPaths(next.paths, {+ initialExpandedPaths,+ });+ for (const path of nextSelectedPaths) {+ model.getItem(path)?.select();+ }+ if (focusedId) {+ const path = next.pathById.get(focusedId);+ if (path) model.focusPath(path);+ }+ } finally {+ suppressModelEventsRef.current = false;+ }+ }, [props.nodes, model]);++ useImperativeHandle(+ ref,+ (): ExplorerTreeHandle => ({+ deselect: (id) => {+ const path = adapterRef.current.pathById.get(id);+ if (!path) return;+ model.getItem(path)?.deselect();+ },+ focus: (id) => {+ const path = adapterRef.current.pathById.get(id);+ if (path) model.focusPath(path);+ },+ getSelectedIds: () => remapPathsToIds(model.getSelectedPaths(), adapterRef.current.idByPath),+ select: (id, opts) => {+ const path = adapterRef.current.pathById.get(id);+ if (!path) return;+ const item = model.getItem(path);+ if (!item) return;+ if (opts?.additive) item.toggleSelect();+ else item.select();+ },+ setExpanded: (ids) => {+ const want = new Set(ids);+ const a = adapterRef.current;+ for (const [nodeId, path] of a.pathById) {+ const dir = asDirectory(model.getItem(path));+ if (!dir) continue;+ const shouldExpand = want.has(nodeId);+ if (shouldExpand && !dir.isExpanded()) dir.expand();+ else if (!shouldExpand && dir.isExpanded()) dir.collapse();+ }+ },+ startRenaming: (id) => {+ const path = adapterRef.current.pathById.get(id);+ if (!path) return;+ renamingRef.current = true;+ model.startRenaming(path);+ },+ }),+ [model],+ );++ const handleContextMenu = (event: MouseEvent<HTMLElement>) => {+ const fn = propsRef.current.getContextMenuItems;+ if (!fn) return;+ const itemPath = getItemPathFromHostEvent(event);+ if (!itemPath) return;+ const a = adapterRef.current;+ const id = a.idByPath.get(itemPath);+ if (!id) return;+ const node = a.nodeById.get(id);+ if (!node) return;+ const items = fn(node);+ if (!items || items.length === 0) return;+ event.preventDefault();+ openExplorerContextMenu(items);+ };++ const handleClick = (event: MouseEvent<HTMLElement>) => {+ const onNodeClick = propsRef.current.onNodeClick;+ if (!onNodeClick) return;+ const itemPath = getItemPathFromHostEvent(event);+ if (!itemPath) return;+ const a = adapterRef.current;+ const id = a.idByPath.get(itemPath);+ if (!id) return;+ const node = a.nodeById.get(id);+ if (!node) return;+ onNodeClick(node, event);+ };++ const handleDropCapture = (event: DragEvent<HTMLElement>) => {+ const onExternalDrop = propsRef.current.onExternalDrop;+ if (!onExternalDrop) return;+ const itemPath = getItemPathFromHostEvent(event);+ if (!itemPath) return;+ const a = adapterRef.current;+ const targetId = a.idByPath.get(itemPath) ?? null;+ const targetNode = targetId ? (a.nodeById.get(targetId) ?? null) : null;+ onExternalDrop({+ nativeEvent: event,+ targetId,+ targetNode,+ });+ };++ const handleDragStart = (event: DragEvent<HTMLElement>) => {+ const onNodeDragStart = propsRef.current.onNodeDragStart;+ if (!onNodeDragStart) return;+ const itemPath = getItemPathFromHostEvent(event);+ if (!itemPath) return;+ const a = adapterRef.current;+ const id = a.idByPath.get(itemPath);+ if (!id) return;+ const node = a.nodeById.get(id);+ if (!node) return;+ onNodeDragStart(node, event);+ };++ return (+ <PierreFileTree+ className={props.className}+ header={props.header}+ model={model}+ style={props.style}+ onClick={handleClick}+ onContextMenu={handleContextMenu}+ onDragStart={handleDragStart}+ onDropCapture={handleDropCapture}+ />+ );+}++const ExplorerTree = forwardRef(ExplorerTreeInner) as <TData>(+ props: ExplorerTreeProps<TData> & { ref?: ForwardedRef<ExplorerTreeHandle> },+) => ReturnType<typeof ExplorerTreeInner>;++export default ExplorerTree;diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 4c4e7416d9a..07f9f7961e7 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -903,6 +903,14 @@ export default {'workingPanel.resources.renameEmpty': 'Title cannot be empty','workingPanel.resources.renameError': 'Failed to rename document','workingPanel.resources.renameSuccess': 'Document renamed',+ 'workingPanel.resources.tree.createError': 'Failed to create',+ 'workingPanel.resources.tree.moveError': 'Failed to move',+ 'workingPanel.resources.tree.parentMissing': 'Parent folder is unavailable',+ 'workingPanel.resources.tree.newDocument': 'New document',+ 'workingPanel.resources.tree.newFolder': 'New folder',+ 'workingPanel.resources.tree.rename': 'Rename',+ 'workingPanel.resources.tree.untitledDocument': 'Untitled document',+ 'workingPanel.resources.tree.untitledFolder': 'Untitled folder','workingPanel.resources.updatedAt': 'Updated {{time}}','workingPanel.resources.viewMode.list': 'List view','workingPanel.resources.viewMode.tree': 'Tree view',diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsxindex 0527a92bc66..313566549de 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx@@ -71,6 +71,12 @@ vi.mock('react-router-dom', () => ({useNavigate: () => useNavigateMock,}));+vi.mock('@/features/AgentDocumentsExplorer', () => ({+ DocumentExplorerTree: ({ data }: { data: unknown[] }) => (+ <div data-doc-count={data.length} data-testid="document-explorer-tree" />+ ),+}));+vi.mock('@/services/agentDocument', () => ({agentDocumentSWRKeys: {documents: (agentId: string) => ['agent-documents', agentId],@@ -188,15 +194,20 @@ describe('AgentDocumentsGroup', () => {expect(screen.getByText('Brief')).toBeInTheDocument();expect(screen.getByText('Example')).toBeInTheDocument();+ expect(screen.queryByTestId('document-explorer-tree')).not.toBeInTheDocument();fireEvent.click(screen.getByText('Web'));expect(screen.queryByText('Brief')).not.toBeInTheDocument();expect(screen.getByText('Example')).toBeInTheDocument();+ expect(screen.queryByTestId('document-explorer-tree')).not.toBeInTheDocument();fireEvent.click(screen.getByText('Documents'));- expect(screen.getByText('Brief')).toBeInTheDocument();+ const tree = screen.getByTestId('document-explorer-tree');+ expect(tree).toBeInTheDocument();+ expect(tree).toHaveAttribute('data-doc-count', '2');+ expect(screen.queryByText('Brief')).not.toBeInTheDocument();expect(screen.queryByText('Example')).not.toBeInTheDocument();});diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsxindex 7022eb16e7f..cad7314cf39 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx@@ -4,10 +4,11 @@ import { createStaticStyles, cx } from 'antd-style';import dayjs from 'dayjs';import relativeTime from 'dayjs/plugin/relativeTime';import { FileTextIcon, GlobeIcon, type LucideIcon, Trash2Icon } from 'lucide-react';-import { memo, type MouseEvent, useMemo, useState } from 'react';+import { type CSSProperties, memo, type MouseEvent, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useMatch, useNavigate } from 'react-router-dom';+import { DocumentExplorerTree } from '@/features/AgentDocumentsExplorer';import { useClientDataSWR } from '@/libs/swr';import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';import { useAgentStore } from '@/store/agent';@@ -204,10 +205,11 @@ const DocumentItem = memo<DocumentItemProps>(({ agentId, document, mutate }) =>DocumentItem.displayName = 'AgentDocumentsGroupItem';interface AgentDocumentsGroupProps {+ style?: CSSProperties;viewMode?: 'list' | 'tree';}-const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ viewMode = 'list' }) => {+const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, viewMode = 'list' }) => {const { t } = useTranslation('chat');const agentId = useAgentStore((s) => s.activeAgentId);const [filter, setFilter] = useState<ResourceFilter>('all');@@ -256,7 +258,9 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ viewMode = 'list');}- if (data.length === 0) {+ // For filter==='documents' we still render the tree even when empty, so the+ // toolbar (new folder / new doc) remains reachable.+ if (data.length === 0 && filter !== 'documents') {return (<Center flex={1} gap={8} paddingBlock={24}><Empty description={t('workingPanel.resources.empty')} icon={FileTextIcon} />@@ -284,7 +288,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ viewMode = 'list'}return (- <Flexbox gap={12}>+ <Flexbox gap={12} style={style}><Flexbox horizontal gap={4} role={'tablist'}>{FILTER_OPTIONS.map((option) => {const active = filter === option.value;@@ -301,7 +305,16 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ viewMode = 'list');})}</Flexbox>- {filteredData.length === 0 ? (+ {filter === 'documents' ? (+ <Flexbox flex={1} style={{ minHeight: 0 }}>+ <DocumentExplorerTree+ agentId={agentId}+ data={data}+ mutate={mutate}+ style={{ height: '100%' }}+ />+ </Flexbox>+ ) : filteredData.length === 0 ? (<Center flex={1} gap={8} paddingBlock={24}><Emptydescription={t('workingPanel.resources.empty')}diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsxindex 85dbae3e804..9aaa8f63412 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx@@ -7,8 +7,14 @@ export type ResourceViewMode = 'list' | 'tree';const ResourcesSection = memo(() => {return (- <Flexbox data-testid="workspace-resources" paddingBlock={8} paddingInline={16}>- <AgentDocumentsGroup viewMode={'list'} />+ <Flexbox+ data-testid="workspace-resources"+ flex={1}+ paddingBlock={8}+ paddingInline={16}+ style={{ minHeight: 0 }}+ >+ <AgentDocumentsGroup style={{ flex: 1, minHeight: 0 }} viewMode={'list'} /></Flexbox>);});diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex ec29f131d3c..a360255f5e7 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -209,6 +209,44 @@ class AgentDocumentService {return result;};+ createFolder = async (params: { agentId: string; path: string; recursive?: boolean }) => {+ const result = await lambdaClient.agentDocument.mkdirDocumentByPath.mutate(params);+ await revalidateAgentDocuments(params.agentId);++ return result;+ };++ moveDocument = async (params: {+ agentId: string;+ force?: boolean;+ fromPath: string;+ toPath: string;+ }) => {+ const result = await lambdaClient.agentDocument.renameDocumentByPath.mutate(params);+ await revalidateAgentDocuments(params.agentId);++ return result;+ };++ writeByPath = async (params: {+ agentId: string;+ content: string;+ createMode?: 'always-new' | 'if-missing' | 'must-exist';+ path: string;+ }) => {+ const result = await lambdaClient.agentDocument.writeDocumentByPath.mutate(params);+ await revalidateAgentDocuments(params.agentId);++ return result;+ };++ deleteByPath = async (params: { agentId: string; path: string; recursive?: boolean }) => {+ const result = await lambdaClient.agentDocument.deleteDocumentByPath.mutate(params);+ await revalidateAgentDocuments(params.agentId);++ return result;+ };+updateLoadRule = async (params: {agentId: string;id: string;