Skip to content

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

✨ feat(documents): add optimistic create/delete and inline rename for document tree (#14714)

Innei9e0e76fda2ad
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
index e8f4509a2a3..b83ab5b25f4 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -282,15 +282,21 @@ describe('DocumentExplorerTree', () => {
const [firstConfirmCall] = modalConfirm.mock.calls;
const [{ onOk }] = firstConfirmCall;
- await onOk();
+ // onOk now returns synchronously so the modal closes immediately; the
+ // server call runs in the background.
+ onOk();
- expect(removeDocumentMock).toHaveBeenCalledWith({
- agentId: 'agent-1',
- documentId: 'skill-bundle-doc',
- id: 'skill-bundle-row',
- topicId: undefined,
- });
+ // Optimistic removal happens before the server call.
expect(mutate).toHaveBeenCalled();
- expect(messageSuccess).toHaveBeenCalledWith('workingPanel.resources.deleteSuccess');
+
+ await waitFor(() => {
+ expect(removeDocumentMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ documentId: 'skill-bundle-doc',
+ id: 'skill-bundle-row',
+ topicId: undefined,
+ });
+ });
+ expect(messageSuccess).not.toHaveBeenCalled();
});
});
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
index 5af5b6dcfe4..c1e9c07078b 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
@@ -111,13 +111,21 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
[documents],
);
+ const focusNewRowForRename = useCallback((pendingId: string) => {
+ // Defer past the current task so React commits the inserted row and the
+ // tree adapter rebuilds its id→path map before we trigger rename.
+ setTimeout(() => treeRef.current?.startRenaming(pendingId), 0);
+ }, []);
+
const handleCreateFolder = useCallback(
- (parentId: string | null) => ops.createFolder(parentId),
- [ops],
+ (parentId: string | null) =>
+ ops.createFolder(parentId, { onPendingInserted: focusNewRowForRename }),
+ [focusNewRowForRename, ops],
);
const handleCreateDocument = useCallback(
- (parentId: string | null) => ops.createDocument(parentId),
- [ops],
+ (parentId: string | null) =>
+ ops.createDocument(parentId, { onPendingInserted: focusNewRowForRename }),
+ [focusNewRowForRename, ops],
);
const handleNodeClick = useCallback(
diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
index f8c50f5d010..8537282f8a2 100644
--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
@@ -9,9 +9,11 @@ import type { AgentDocumentItem } from '../types';
import {
FOLDER_FILE_TYPE,
isManagedSkillItem,
+ isPendingId,
isProtectedManagedSkillItem,
isSkillBundleItem,
} from '../types';
+import { makePendingDocument } from '../utils/pendingDocument';
interface UseDocumentTreeOpsArgs {
agentId: string;
@@ -25,9 +27,29 @@ const ROOT_PATH = './';
const joinPath = (parentPath: string, segment: string) =>
parentPath === ROOT_PATH ? `${ROOT_PATH}${segment}` : `${parentPath}/${segment}`;
+// Service mutations return AgentDocumentStats-shaped payloads where the
+// agentDocumentItems row id is exposed as `id` (and mirrored on
+// `agentDocumentId`). Extract defensively since tRPC narrows the type
+// per-route.
+const extractRowId = (result: unknown): string | null => {
+ if (!result || typeof result !== 'object') return null;
+ const obj = result as Record<string, unknown>;
+ const id = obj.id ?? obj.agentDocumentId;
+ return typeof id === 'string' && id.length > 0 ? id : null;
+};
+
+export interface CreateOptions {
+ /**
+ * Fires synchronously right after the optimistic pending row is inserted,
+ * passing the pending row's id. Used by the tree to immediately enter the
+ * rename input on the new row, before the server response lands.
+ */
+ onPendingInserted?: (pendingId: string) => void;
+}
+
export interface DocumentTreeOps {
- createDocument: (parentId: string | null) => Promise<void>;
- createFolder: (parentId: string | null) => Promise<void>;
+ createDocument: (parentId: string | null, opts?: CreateOptions) => Promise<void>;
+ createFolder: (parentId: string | null, opts?: CreateOptions) => Promise<void>;
deleteDocument: (id: string) => void;
moveDocument: (params: {
sourceIds: string[];
@@ -48,6 +70,10 @@ export const useDocumentTreeOps = ({
const dataRef = useRef(data);
dataRef.current = data;
+ // Tracks in-flight creates so a rename committed before the server response
+ // lands can be deferred to the real row id once the create resolves.
+ const pendingCreatesRef = useRef(new Map<string, Promise<string | null>>());
+
const byRowId = useMemo(() => {
const map = new Map<string, AgentDocumentItem>();
for (const doc of data) map.set(doc.id, doc);
@@ -107,7 +133,7 @@ export const useDocumentTreeOps = ({
);
const createFolder = useCallback(
- async (parentId: string | null) => {
+ async (parentId: string | null, opts?: CreateOptions) => {
const parentPath = buildParentPathFromRowId(parentId);
if (parentPath === null) {
message.error(t('workingPanel.resources.tree.parentMissing'));
@@ -119,22 +145,43 @@ export const useDocumentTreeOps = ({
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'),
- );
- }
+ const pending = makePendingDocument({
+ agentId,
+ isFolder: true,
+ parentId: parentDocumentId,
+ title: filename,
+ });
+ mutate((prev) => [...(prev ?? []), pending], { revalidate: false });
+ opts?.onPendingInserted?.(pending.id);
+
+ const createPromise = (async (): Promise<string | null> => {
+ try {
+ const result = await agentDocumentService.createFolder({ agentId, path: targetPath });
+ await mutate();
+ return extractRowId(result);
+ } catch (error) {
+ mutate((prev) => (prev ?? []).filter((doc) => doc.id !== pending.id), {
+ revalidate: false,
+ });
+ message.error(
+ error instanceof Error
+ ? `${t('workingPanel.resources.tree.createError')}: ${error.message}`
+ : t('workingPanel.resources.tree.createError'),
+ );
+ return null;
+ } finally {
+ pendingCreatesRef.current.delete(pending.id);
+ }
+ })();
+
+ pendingCreatesRef.current.set(pending.id, createPromise);
+ await createPromise;
},
[agentId, buildParentPathFromRowId, byRowId, message, mutate, pickUniqueFilename, t],
);
const createDocument = useCallback(
- async (parentId: string | null) => {
+ async (parentId: string | null, opts?: CreateOptions) => {
const parentPath = buildParentPathFromRowId(parentId);
if (parentPath === null) {
message.error(t('workingPanel.resources.tree.parentMissing'));
@@ -142,33 +189,53 @@ export const useDocumentTreeOps = ({
}
const baseName = t('workingPanel.resources.tree.untitledDocument');
+ const parentDocumentId = parentId ? (byRowId.get(parentId)?.documentId ?? null) : null;
+ const pendingFilename = pickUniqueFilename(parentDocumentId, baseName);
- 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),
+ const pending = makePendingDocument({
+ agentId,
+ isFolder: false,
+ parentId: parentDocumentId,
+ title: pendingFilename,
+ });
+ mutate((prev) => [...(prev ?? []), pending], { revalidate: false });
+ opts?.onPendingInserted?.(pending.id);
+
+ const createPromise = (async (): Promise<string | null> => {
+ try {
+ const result =
+ parentPath === ROOT_PATH
+ ? // Server's createDocument auto-deduplicates filenames at the root.
+ await agentDocumentService.createDocument({
+ agentId,
+ content: '',
+ title: baseName,
+ })
+ : await agentDocumentService.writeByPath({
+ agentId,
+ content: '',
+ createMode: 'always-new',
+ path: joinPath(parentPath, pendingFilename),
+ });
+ await mutate();
+ return extractRowId(result);
+ } catch (error) {
+ mutate((prev) => (prev ?? []).filter((doc) => doc.id !== pending.id), {
+ revalidate: false,
});
+ message.error(
+ error instanceof Error
+ ? `${t('workingPanel.resources.tree.createError')}: ${error.message}`
+ : t('workingPanel.resources.tree.createError'),
+ );
+ return null;
+ } finally {
+ pendingCreatesRef.current.delete(pending.id);
}
- await mutate();
- } catch (error) {
- message.error(
- error instanceof Error
- ? `${t('workingPanel.resources.tree.createError')}: ${error.message}`
- : t('workingPanel.resources.tree.createError'),
- );
- }
+ })();
+
+ pendingCreatesRef.current.set(pending.id, createPromise);
+ await createPromise;
},
[agentId, buildParentPathFromRowId, byRowId, message, mutate, pickUniqueFilename, t],
);
@@ -186,6 +253,23 @@ export const useDocumentTreeOps = ({
}
if (trimmed === target.title) return;
+ // If the row is a pending optimistic insert, wait for the create to
+ // resolve so we can rename against the real server-side id. Once the
+ // pending row is replaced by the real row (same path) the tree's
+ // path-based rename state survives the hydration, so the user's input
+ // stays intact.
+ if (isPendingId(id)) {
+ const pendingPromise = pendingCreatesRef.current.get(id);
+ if (!pendingPromise) return;
+ const realId = await pendingPromise;
+ if (!realId) return;
+ // Bail out if the real row already carries the desired name (e.g.
+ // server returned with the trimmed name applied).
+ const real = dataRef.current.find((doc) => doc.id === realId);
+ if (real && real.title === trimmed) return;
+ return renameDocument(realId, trimmed);
+ }
+
mutate(
(prev) =>
(prev ?? []).map((doc) =>
@@ -288,34 +372,64 @@ export const useDocumentTreeOps = ({
content: t('workingPanel.resources.deleteConfirm'),
okButtonProps: { danger: true, type: 'primary' },
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'));
+ onOk: () => {
+ const isFolder = target.fileType === FOLDER_FILE_TYPE;
+ const folderPath = isFolder ? buildItemPath(target) : null;
+ if (isFolder && folderPath === null) {
+ message.error(t('workingPanel.resources.tree.parentMissing'));
+ return;
+ }
+
+ // Collect target + all descendants (parentId chain via documentId) for
+ // optimistic recursive removal. Server is the source of truth and a
+ // final `mutate()` reconciles either way.
+ const removedIds = new Set<string>([target.id]);
+ if (isFolder) {
+ const queue: string[] = [target.documentId];
+ while (queue.length > 0) {
+ const parentDocId = queue.shift()!;
+ for (const doc of dataRef.current) {
+ if (doc.parentId === parentDocId && !removedIds.has(doc.id)) {
+ removedIds.add(doc.id);
+ queue.push(doc.documentId);
+ }
}
- 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'),
- );
}
+
+ const snapshot = dataRef.current;
+ mutate((prev) => (prev ?? []).filter((doc) => !removedIds.has(doc.id)), {
+ revalidate: false,
+ });
+
+ // Returning synchronously closes the modal immediately; the server
+ // call runs in the background and toasts on success/rollback.
+ void (async () => {
+ try {
+ if (isFolder) {
+ await agentDocumentService.deleteByPath({
+ agentId,
+ path: folderPath!,
+ recursive: true,
+ });
+ } else {
+ await agentDocumentService.removeDocument({
+ agentId,
+ documentId: target.documentId,
+ id: target.id,
+ topicId,
+ });
+ }
+ await mutate();
+ } catch (error) {
+ mutate(snapshot, { revalidate: false });
+ message.error(
+ error instanceof Error
+ ? `${t('workingPanel.resources.deleteError')}: ${error.message}`
+ : t('workingPanel.resources.deleteError'),
+ );
+ }
+ })();
},
title: t('workingPanel.resources.deleteTitle'),
});
diff --git a/src/features/ExplorerTree/adapter/index.ts b/src/features/ExplorerTree/adapter/index.ts
index ec417b8a95a..0dc45dbff47 100644
--- a/src/features/ExplorerTree/adapter/index.ts
+++ b/src/features/ExplorerTree/adapter/index.ts
@@ -6,4 +6,4 @@ export {
remapIdsToPaths,
remapPathsToIds,
} from './normalize';
-export { buildSegment, extractName } from './path';
+export { buildSegment, extractName, toCanonicalTreePath } from './path';
diff --git a/src/features/ExplorerTree/adapter/path.test.ts b/src/features/ExplorerTree/adapter/path.test.ts
new file mode 100644
index 00000000000..b16775204a7
--- /dev/null
+++ b/src/features/ExplorerTree/adapter/path.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+
+import { toCanonicalTreePath } from './path';
+
+describe('toCanonicalTreePath', () => {
+ it('restores the canonical folder path used by the tree adapter', () => {
+ expect(toCanonicalTreePath('Notes', true)).toBe('Notes/');
+ expect(toCanonicalTreePath('Notes/', true)).toBe('Notes/');
+ });
+
+ it('keeps file paths unchanged', () => {
+ expect(toCanonicalTreePath('Notes/readme.md', false)).toBe('Notes/readme.md');
+ });
+});
diff --git a/src/features/ExplorerTree/adapter/path.ts b/src/features/ExplorerTree/adapter/path.ts
index caccd3d6a89..e66ca4b202f 100644
--- a/src/features/ExplorerTree/adapter/path.ts
+++ b/src/features/ExplorerTree/adapter/path.ts
@@ -5,6 +5,9 @@ export const buildSegment = (name: string, isFolder: boolean): string => {
return isFolder ? `${segment}/` : segment;
};
+export const toCanonicalTreePath = (path: string, isFolder: boolean): string =>
+ isFolder && !path.endsWith('/') ? `${path}/` : path;
+
export const extractName = (path: string): string => {
const trimmed = path.endsWith('/') ? path.slice(0, -1) : path;
const lastSep = trimmed.lastIndexOf('/');
diff --git a/src/features/ExplorerTree/view/ExplorerTree.test.tsx b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
new file mode 100644
index 00000000000..6b8ba72d7e3
--- /dev/null
+++ b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
@@ -0,0 +1,71 @@
+import { act, fireEvent, render, waitFor } from '@testing-library/react';
+import { useRef } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ExplorerTreeHandle } from '../types';
+import ExplorerTree, { getItemPathFromEventPath } from './ExplorerTree';
+
+const showContextMenu = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui', () => ({
+ showContextMenu,
+}));
+
+describe('ExplorerTree', () => {
+ it('commits folder renames through the canonical adapter path', async () => {
+ let handleRef: React.RefObject<ExplorerTreeHandle | null>;
+ const onCommitRename = vi.fn();
+
+ function TestWrapper() {
+ handleRef = useRef<ExplorerTreeHandle>(null);
+ return (
+ <ExplorerTree
+ nodes={[{ id: 'folder', isFolder: true, name: 'Notes', parentId: null }]}
+ ref={handleRef}
+ onCommitRename={onCommitRename}
+ />
+ );
+ }
+
+ const { container } = render(<TestWrapper />);
+
+ act(() => {
+ handleRef.current?.startRenaming('folder');
+ });
+
+ const host = container.querySelector('file-tree-container');
+
+ await waitFor(() => {
+ expect(host?.shadowRoot?.querySelector('[data-item-rename-input]')).toBeInstanceOf(
+ HTMLInputElement,
+ );
+ });
+
+ const input = host?.shadowRoot?.querySelector('[data-item-rename-input]');
+ expect(input).toBeInstanceOf(HTMLInputElement);
+
+ fireEvent.input(input!, { target: { value: 'Archive' } });
+ fireEvent.blur(input!);
+
+ expect(onCommitRename).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'folder', isFolder: true }),
+ 'Archive',
+ );
+ });
+
+ it('resolves the clicked segment inside a flattened directory row', () => {
+ const parentSegment = document.createElement('span');
+ parentSegment.setAttribute('data-item-flattened-subitem', 'Parent/');
+
+ const childSegment = document.createElement('span');
+ childSegment.setAttribute('data-item-flattened-subitem', 'Parent/Child/');
+
+ const row = document.createElement('button');
+ row.dataset.type = 'item';
+ row.dataset.itemPath = 'Parent/Child/';
+
+ expect(getItemPathFromEventPath([parentSegment, row])).toBe('Parent/');
+ expect(getItemPathFromEventPath([childSegment, row])).toBe('Parent/Child/');
+ expect(getItemPathFromEventPath([row])).toBe('Parent/Child/');
+ });
+});
diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsx
index 053afa06f31..da7cfa64c69 100644
--- a/src/features/ExplorerTree/view/ExplorerTree.tsx
+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx
@@ -17,7 +17,7 @@ import {
remapIdsToPaths,
remapPathsToIds,
} from '../adapter';
-import { extractName } from '../adapter/path';
+import { extractName, toCanonicalTreePath } from '../adapter/path';
import type {
ExplorerTreeHandle,
ExplorerTreeMoveEvent,
@@ -44,9 +44,11 @@ const getComposedPath = (event: ExplorerTreeHostEvent): EventTarget[] => {
);
};
-const getItemPathFromHostEvent = (event: ExplorerTreeHostEvent): string | null => {
- for (const target of getComposedPath(event)) {
+export const getItemPathFromEventPath = (path: EventTarget[]): string | null => {
+ for (const target of path) {
if (!isHTMLElement(target)) continue;
+ const flattenedSegmentPath = target.getAttribute('data-item-flattened-subitem');
+ if (flattenedSegmentPath) return flattenedSegmentPath;
if (target.dataset.type !== 'item') continue;
const path = target.dataset.itemPath;
if (path) return path;
@@ -55,6 +57,9 @@ const getItemPathFromHostEvent = (event: ExplorerTreeHostEvent): string | null =
return null;
};
+const getItemPathFromHostEvent = (event: ExplorerTreeHostEvent): string | null =>
+ getItemPathFromEventPath(getComposedPath(event));
+
function ExplorerTreeInner<TData>(
props: ExplorerTreeProps<TData>,
ref: ForwardedRef<ExplorerTreeHandle>,
@@ -169,9 +174,8 @@ function ExplorerTreeInner<TData>(
paths: initial.paths,
renaming: {
canRename: (item) => {
- const node = adapterRef.current.nodeById.get(
- adapterRef.current.idByPath.get(item.path) ?? '',
- );
+ const path = toCanonicalTreePath(item.path, item.isFolder);
+ const node = adapterRef.current.nodeById.get(adapterRef.current.idByPath.get(path) ?? '');
if (!node) return false;
const fn = propsRef.current.canRename;
return fn ? fn(node) : !!propsRef.current.onCommitRename;
@@ -180,9 +184,9 @@ function ExplorerTreeInner<TData>(
const node = renamingNodeRef.current;
if (node) propsRef.current.onRenameError?.(error, node);
},
- onRename: ({ sourcePath, destinationPath }) => {
+ onRename: ({ sourcePath, destinationPath, isFolder }) => {
const a = adapterRef.current;
- const id = a.idByPath.get(sourcePath);
+ const id = a.idByPath.get(toCanonicalTreePath(sourcePath, isFolder));
if (!id) return;
const node = a.nodeById.get(id);
if (!node) return;