🤯 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(agent-documents): folders, batch moves and documents as parents (#20761)
Arvin Xue62010981de8
diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.tsindex 66a0695efd1..9d981303384 100644--- a/apps/server/src/routers/lambda/agentDocument.ts+++ b/apps/server/src/routers/lambda/agentDocument.ts@@ -3,6 +3,7 @@ import {DocumentLoadFormat,DocumentLoadRule,} from '@lobechat/agent-templates';+import { MOVE_DOCUMENTS_MAX_IDS } from '@lobechat/builtin-tool-agent-documents';import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';import { TRPCError } from '@trpc/server';import matter from 'gray-matter';@@ -524,29 +525,48 @@ export const agentDocumentRouter = router({scope: z.enum(['agent', 'currentTopic']).optional().default('agent'),sourceType: z.enum(['all', 'file', 'web']).optional().default('all'),topicId: z.string().optional(),+ // Stamp `childCount` on entries with something nested under them (the+ // agent tool needs it to spot a workflow document holding its runs).+ withChildCount: z.boolean().optional().default(false),}),).query(async ({ ctx, input }) => {const { excludeWeb, includeArchivedToolResults, parentId } = input;- if (input.scope === 'currentTopic') {- if (!input.topicId) throw new Error('topicId is required to list current topic documents');+ const withChildCounts = async <T extends { documentId: string }>(docs: T[]) => {+ if (!input.withChildCount) return docs;+ const counts = await ctx.agentDocumentService.countChildren(input.agentId);+ return docs.map((doc) => ({ ...doc, childCount: counts.get(doc.documentId) ?? 0 }));+ };+ try {+ if (input.scope === 'currentTopic') {+ if (!input.topicId) {+ throw new Error('topicId is required to list current topic documents');+ }++ const docs = await ctx.agentDocumentService.listDocumentsForTopic(+ input.agentId,+ input.topicId,+ input.sourceType,+ { includeArchivedToolResults },+ );+ if (!parentId) return await withChildCounts(docs);++ // Topic listing joins through topic associations rather than the agent+ // folder tree, so the parent filter is applied in-memory here.+ const parent = await ctx.agentDocumentService.resolveParent(input.agentId, parentId);+ return await withChildCounts(docs.filter((d) => d.parentId === parent.documentId));+ }- const docs = await ctx.agentDocumentService.listDocumentsForTopic(- input.agentId,- input.topicId,- input.sourceType,- { includeArchivedToolResults },+ return await withChildCounts(+ await ctx.agentDocumentService.listDocuments(input.agentId, input.sourceType, {+ excludeWeb,+ includeArchivedToolResults,+ parentId,+ }),);- // Topic listing joins through topic associations rather than the agent- // folder tree, so the folder filter is applied in-memory here.- return parentId ? docs.filter((d) => d.parentId === parentId) : docs;+ } catch (error) {+ return handleAgentDocumentVfsError(error);}-- return ctx.agentDocumentService.listDocuments(input.agentId, input.sourceType, {- excludeWeb,- includeArchivedToolResults,- parentId,- });}),/**@@ -1233,12 +1253,17 @@ export const agentDocumentRouter = router({.object({agentId: z.string(),id: z.string(),+ // Also delete documents nested under it; without it a parent with+ // children is refused instead of stranding them.+ withChildren: z.boolean().optional(),}).and(agentDocumentToolTriggerSchema),).mutation(async ({ ctx, input }) => {const doc = await ctx.agentDocumentService.getDocumentById(input.id, input.agentId);- const deleted = await ctx.agentDocumentService.removeDocumentById(input.id, input.agentId);+ const deleted = await ctx.agentDocumentService+ .removeDocumentById(input.id, input.agentId, { withChildren: input.withChildren })+ .catch(handleAgentDocumentVfsError);if (deleted && input.trigger === 'tool') {await ctx.documentWorkRegistrar.deleteDocumentWork({agentDocumentId: input.id,@@ -1304,6 +1329,52 @@ export const agentDocumentRouter = router({}}),+ /**+ * Tool-oriented: create a folder by name, under the root or a parent (folder or document) id+ */+ createFolder: agentDocumentProcedureWrite+ .input(+ z.object({+ agentId: z.string(),+ parentId: z.string().nullish(),+ title: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.agentDocumentService.createFolder(+ input.agentId,+ input.title,+ input.parentId,+ );+ } catch (error) {+ handleAgentDocumentVfsError(error);+ }+ }),++ /**+ * Tool-oriented: move documents/folders by id under a parent (folder or document), or to the root with `null`+ */+ moveDocuments: agentDocumentProcedureWrite+ .input(+ z.object({+ agentId: z.string(),+ ids: z.array(z.string()).min(1).max(MOVE_DOCUMENTS_MAX_IDS),+ parentId: z.string().nullable(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.agentDocumentService.moveDocuments(+ input.agentId,+ input.ids,+ input.parentId,+ );+ } catch (error) {+ handleAgentDocumentVfsError(error);+ }+ }),+/*** Tool-oriented: update document load rule by id*/diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.tsindex b5619a2e38d..046bcbb24e7 100644--- a/apps/server/src/services/agentDocuments/index.test.ts+++ b/apps/server/src/services/agentDocuments/index.test.ts@@ -96,6 +96,10 @@ vi.mock('@lobehub/editor/headless', () => ({}),}));+const FOLDER_ROW_ID = '23d908ac-0a43-440d-a67f-1f57b8427c53';+const DOC_ROW_ID = 'ae743612-eef4-4c46-879f-9db9c346e760';+const SKILL_ROW_ID = '8716f7a5-1234-4d35-80fd-5d4354f1a439';+describe('AgentDocumentsService', () => {const db = {} as LobeChatDatabase;const userId = 'user-1';@@ -103,7 +107,10 @@ describe('AgentDocumentsService', () => {const mockModel = {associate: vi.fn(),copy: vi.fn(),+ countChildrenByParentIds: vi.fn(),create: vi.fn(),+ delete: vi.fn(),+ deleteSubtreeByDocumentId: vi.fn(),findById: vi.fn(),findByAgent: vi.fn(),findContextByAgent: vi.fn(),@@ -115,6 +122,7 @@ describe('AgentDocumentsService', () => {hasByAgent: vi.fn(),listByAgent: vi.fn(),listByDocumentIds: vi.fn(),+ movePath: vi.fn(),rename: vi.fn(),update: vi.fn(),updateEditorSnapshotIfUnchanged: vi.fn(),@@ -152,6 +160,7 @@ describe('AgentDocumentsService', () => {beforeEach(() => {vi.clearAllMocks();mockModel.updateEditorSnapshotIfUnchanged.mockResolvedValue(true);+ mockModel.countChildrenByParentIds.mockResolvedValue(new Map());(AgentDocumentModel as any).mockImplementation(function () {return mockModel;});@@ -434,6 +443,7 @@ describe('AgentDocumentsService', () => {it('creates a document under a parent folder and scopes filename collisions to it', async () => {mockModel.findByDocumentId.mockResolvedValue({+ agentId: 'agent-1',documentId: 'folder-doc-id',fileType: DOCUMENT_FOLDER_TYPE,id: 'folder-agent-doc-id',@@ -458,20 +468,285 @@ describe('AgentDocumentsService', () => {});});- it('rejects a parentId that does not identify an agent folder', async () => {+ // A workflow document holds its run records: an ordinary document is a valid parent.+ it('creates under an ordinary document parent', async () => {mockModel.findByDocumentId.mockResolvedValue({- documentId: 'file-doc-id',- fileType: 'text/markdown',- id: 'file-agent-doc-id',+ agentId: 'agent-1',+ documentId: 'sop-doc-id',+ fileType: 'agent/document',+ id: 'sop-agent-doc-id',+ sourceType: 'agent',+ templateId: null,+ title: 'Vent fix-round SOP',+ });+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'run' });++ const service = new AgentDocumentsService(db, userId);+ await service.createDocument('agent-1', 'run', 'content', { parentId: 'sop-doc-id' });++ expect(mockModel.create).toHaveBeenCalledWith(+ 'agent-1',+ 'run',+ 'content',+ expect.objectContaining({ parentId: 'sop-doc-id' }),+ );+ });++ it.each([+ ['a skill', { fileType: 'skills/index' }],+ ['a web clip', { fileType: 'agent/document', sourceType: 'web' }],+ ])('rejects %s as parent', async (_label, overrides) => {+ mockModel.findByDocumentId.mockResolvedValue({+ agentId: 'agent-1',+ documentId: 'other-doc-id',+ id: 'other-agent-doc-id',+ sourceType: 'agent',+ templateId: null,+ title: 'Other',+ ...overrides,});const service = new AgentDocumentsService(db, userId);await expect(- service.createDocument('agent-1', 'note', 'content', { parentId: 'file-doc-id' }),- ).rejects.toThrow('Parent document is not a folder: file-doc-id');+ service.createDocument('agent-1', 'note', 'content', { parentId: 'other-doc-id' }),+ ).rejects.toThrow('cannot contain other documents');expect(mockModel.create).not.toHaveBeenCalled();});++ it('accepts the folder agent-document row id as parentId', async () => {+ mockModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ documentId: 'folder-doc-id',+ fileType: DOCUMENT_FOLDER_TYPE,+ id: FOLDER_ROW_ID,+ });+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'note' });++ const service = new AgentDocumentsService(db, userId);+ await service.createDocument('agent-1', 'note', 'content', { parentId: FOLDER_ROW_ID });++ expect(mockModel.create).toHaveBeenCalledWith(+ 'agent-1',+ 'note',+ 'content',+ expect.objectContaining({ parentId: 'folder-doc-id' }),+ );+ });+ });++ describe('folders', () => {+ const folder = {+ agentId: 'agent-1',+ documentId: 'docs_folder',+ fileType: DOCUMENT_FOLDER_TYPE,+ filename: 'P95 Reports',+ id: FOLDER_ROW_ID,+ parentId: null,+ title: 'P95 Reports',+ };+ const doc = (overrides: Record<string, unknown> = {}) => ({+ agentId: 'agent-1',+ documentId: 'docs_a',+ fileType: 'agent/document',+ filename: 'P95 Report — 2026-10-10',+ id: DOC_ROW_ID,+ parentId: null,+ templateId: null,+ title: 'P95 Report — 2026-10-10',+ ...overrides,+ });++ describe('resolveParent', () => {+ it('resolves a folder by its documents id or its agent-document row id', async () => {+ mockModel.findByDocumentId.mockResolvedValue(folder);+ mockModel.findById.mockResolvedValue(folder);+ const service = new AgentDocumentsService(db, userId);++ await expect(service.resolveParent('agent-1', 'docs_folder')).resolves.toBe(folder);+ await expect(service.resolveParent('agent-1', FOLDER_ROW_ID)).resolves.toBe(folder);+ expect(mockModel.findByDocumentId).toHaveBeenCalledWith('agent-1', 'docs_folder');+ expect(mockModel.findById).toHaveBeenCalledWith(FOLDER_ROW_ID);+ });++ it('throws instead of resolving a folder owned by another agent', async () => {+ mockModel.findById.mockResolvedValue({ ...folder, agentId: 'agent-2' });+ const service = new AgentDocumentsService(db, userId);++ await expect(service.resolveParent('agent-1', FOLDER_ROW_ID)).rejects.toThrow(+ `Parent not found: ${FOLDER_ROW_ID}`,+ );+ });+ });++ describe('createFolder', () => {+ it('creates a folder under the resolved parent', async () => {+ mockModel.findByDocumentId.mockResolvedValue(folder);+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ ...folder, documentId: 'docs_new', id: 'new' });+ const service = new AgentDocumentsService(db, userId);++ const result = await service.createFolder('agent-1', ' 2026-10 ', 'docs_folder');++ expect(result.created).toBe(true);+ expect(mockModel.create).toHaveBeenCalledWith('agent-1', '2026-10', '', {+ fileType: DOCUMENT_FOLDER_TYPE,+ parentId: 'docs_folder',+ title: '2026-10',+ });+ });++ it('reuses an existing folder with the same name instead of duplicating it', async () => {+ mockModel.findByParentAndFilename.mockResolvedValue(folder);+ const service = new AgentDocumentsService(db, userId);++ const result = await service.createFolder('agent-1', 'P95 Reports');++ expect(result).toEqual({ created: false, folder });+ expect(mockModel.findByParentAndFilename).toHaveBeenCalledWith(+ 'agent-1',+ null,+ 'P95 Reports',+ );+ expect(mockModel.create).not.toHaveBeenCalled();+ });++ it('refuses a name taken by a document, or a name with a path separator', async () => {+ mockModel.findByParentAndFilename.mockResolvedValue(doc({ filename: 'Notes' }));+ const service = new AgentDocumentsService(db, userId);++ await expect(service.createFolder('agent-1', 'Notes')).rejects.toThrow('already exists');+ await expect(service.createFolder('agent-1', 'a/b')).rejects.toThrow('cannot contain');+ expect(mockModel.create).not.toHaveBeenCalled();+ });+ });++ describe('moveDocuments', () => {+ beforeEach(() => {+ mockModel.findByDocumentId.mockImplementation(async (_agentId: string, id: string) =>+ id === folder.documentId ? folder : undefined,+ );+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.movePath = vi.fn(async (id: string) => ({ id }));+ });++ it('moves a document into the folder and keeps its title', async () => {+ mockModel.findById.mockImplementation(async (id: string) =>+ id === FOLDER_ROW_ID ? folder : doc(),+ );+ const service = new AgentDocumentsService(db, userId);++ const results = await service.moveDocuments('agent-1', [DOC_ROW_ID], FOLDER_ROW_ID);++ expect(results).toEqual([+ {+ documentId: 'docs_a',+ id: DOC_ROW_ID,+ status: 'moved',+ title: 'P95 Report — 2026-10-10',+ },+ ]);+ expect(mockModel.movePath).toHaveBeenCalledWith(DOC_ROW_ID, {+ filename: 'P95 Report — 2026-10-10',+ parentId: 'docs_folder',+ title: 'P95 Report — 2026-10-10',+ });+ });++ it('reports each failure without stopping the rest', async () => {+ mockModel.findById.mockImplementation(async (id: string) => {+ if (id === DOC_ROW_ID) return doc();+ if (id === SKILL_ROW_ID) return doc({ fileType: 'skills/index', id: SKILL_ROW_ID });+ return undefined;+ });+ mockModel.findByParentAndFilename.mockImplementation(async () =>+ doc({ id: 'other-row', parentId: 'docs_folder' }),+ );+ const service = new AgentDocumentsService(db, userId);++ const results = await service.moveDocuments(+ 'agent-1',+ [DOC_ROW_ID, SKILL_ROW_ID, 'docs_missing'],+ 'docs_folder',+ );++ expect(results.map((r) => [r.status, r.error])).toEqual([+ ['failed', '"P95 Report — 2026-10-10" already exists in the destination folder.'],+ ['failed', 'Skill documents cannot be moved.'],+ ['failed', 'Document not found: docs_missing'],+ ]);+ expect(mockModel.movePath).not.toHaveBeenCalled();+ });++ it('leaves documents already in the destination untouched', async () => {+ mockModel.findById.mockResolvedValue(doc({ parentId: 'docs_folder' }));+ const service = new AgentDocumentsService(db, userId);++ const [result] = await service.moveDocuments('agent-1', [DOC_ROW_ID], 'docs_folder');++ expect(result.status).toBe('unchanged');+ expect(mockModel.movePath).not.toHaveBeenCalled();+ });++ it('refuses to move a folder into its own subfolder', async () => {+ const child = {+ ...folder,+ documentId: 'docs_child',+ id: 'child-row',+ parentId: 'docs_folder',+ };+ mockModel.findByDocumentId.mockImplementation(async (_agentId: string, id: string) =>+ id === 'docs_child' ? child : id === 'docs_folder' ? folder : undefined,+ );+ mockModel.findById.mockResolvedValue(folder);+ const service = new AgentDocumentsService(db, userId);++ const [result] = await service.moveDocuments('agent-1', [FOLDER_ROW_ID], 'docs_child');++ expect(result).toMatchObject({+ error: 'Cannot move a document or folder under itself or one of its descendants.',+ status: 'failed',+ });+ expect(mockModel.movePath).not.toHaveBeenCalled();+ });++ it('moves records under a workflow document', async () => {+ const sop = doc({+ documentId: 'docs_sop',+ filename: 'Vent fix-round SOP',+ id: 'sop-row',+ title: 'Vent fix-round SOP',+ });+ mockModel.findByDocumentId.mockImplementation(async (_agentId: string, id: string) =>+ id === 'docs_sop' ? sop : undefined,+ );+ mockModel.findById.mockResolvedValue(doc());+ const service = new AgentDocumentsService(db, userId);++ const [result] = await service.moveDocuments('agent-1', [DOC_ROW_ID], 'docs_sop');++ expect(result.status).toBe('moved');+ expect(mockModel.movePath).toHaveBeenCalledWith(+ DOC_ROW_ID,+ expect.objectContaining({ parentId: 'docs_sop' }),+ );+ });++ it('moves to the root with a null parent', async () => {+ mockModel.findById.mockResolvedValue(doc({ parentId: 'docs_folder' }));+ const service = new AgentDocumentsService(db, userId);++ const [result] = await service.moveDocuments('agent-1', [DOC_ROW_ID], null);++ expect(result.status).toBe('moved');+ expect(mockModel.movePath).toHaveBeenCalledWith(+ DOC_ROW_ID,+ expect.objectContaining({ parentId: null }),+ );+ });+ });});describe('createForTopic', () => {@@ -500,6 +775,49 @@ describe('AgentDocumentsService', () => {});});+ describe('removeDocumentById', () => {+ const parentDoc = {+ agentId: 'agent-1',+ content: '',+ documentId: 'docs_sop',+ fileType: 'agent/document',+ id: DOC_ROW_ID,+ title: 'Vent fix-round SOP',+ };++ it('refuses a document with nested children unless asked to take them', async () => {+ mockModel.findById.mockResolvedValue(parentDoc);+ mockModel.countChildrenByParentIds.mockResolvedValue(new Map([['docs_sop', 24]]));+ const service = new AgentDocumentsService(db, userId);++ await expect(service.removeDocumentById(DOC_ROW_ID, 'agent-1')).rejects.toThrow(+ '"Vent fix-round SOP" has 24 nested document(s)',+ );+ expect(mockModel.delete).not.toHaveBeenCalled();+ expect(mockModel.deleteSubtreeByDocumentId).not.toHaveBeenCalled();+ });++ it('deletes the whole subtree with withChildren', async () => {+ mockModel.findById.mockResolvedValue(parentDoc);+ mockModel.countChildrenByParentIds.mockResolvedValue(new Map([['docs_sop', 24]]));+ const service = new AgentDocumentsService(db, userId);++ await expect(+ service.removeDocumentById(DOC_ROW_ID, 'agent-1', { withChildren: true }),+ ).resolves.toBe(true);+ expect(mockModel.deleteSubtreeByDocumentId).toHaveBeenCalledWith('agent-1', 'docs_sop');+ expect(mockModel.delete).not.toHaveBeenCalled();+ });++ it('deletes a leaf document on its own', async () => {+ mockModel.findById.mockResolvedValue(parentDoc);+ const service = new AgentDocumentsService(db, userId);++ await expect(service.removeDocumentById(DOC_ROW_ID, 'agent-1')).resolves.toBe(true);+ expect(mockModel.delete).toHaveBeenCalledWith(DOC_ROW_ID);+ });+ });+describe('listDocuments', () => {it('should return a list of documents with documentId, filename, id, and title', async () => {mockModel.listByAgent.mockResolvedValue([@@ -560,6 +878,11 @@ describe('AgentDocumentsService', () => {it('should pass the parentId folder filter to the model', async () => {mockModel.listByAgent.mockResolvedValue([]);+ mockModel.findByDocumentId.mockResolvedValue({+ agentId: 'agent-1',+ documentId: 'folder-1',+ fileType: DOCUMENT_FOLDER_TYPE,+ });const service = new AgentDocumentsService(db, userId);await service.listDocuments('agent-1', undefined, { parentId: 'folder-1' });@@ -570,6 +893,36 @@ describe('AgentDocumentsService', () => {});});+ // An agent passed the folder's row uuid here and got an empty list back,+ // which read as "the folder is empty".+ it('resolves a folder row id to its documents id before filtering', async () => {+ mockModel.listByAgent.mockResolvedValue([]);+ mockModel.findById.mockResolvedValue({+ agentId: 'agent-1',+ documentId: 'docs_tool_results',+ fileType: DOCUMENT_FOLDER_TYPE,+ });++ const service = new AgentDocumentsService(db, userId);+ await service.listDocuments('agent-1', undefined, { parentId: FOLDER_ROW_ID });++ expect(mockModel.listByAgent).toHaveBeenCalledWith('agent-1', {+ parentId: 'docs_tool_results',+ sourceType: undefined,+ });+ });++ it('throws for an unknown folder instead of returning an empty list', async () => {+ mockModel.findByDocumentId.mockResolvedValue(undefined);++ const service = new AgentDocumentsService(db, userId);++ await expect(+ service.listDocuments('agent-1', undefined, { parentId: 'docs_gone' }),+ ).rejects.toThrow('Parent not found: docs_gone');+ expect(mockModel.listByAgent).not.toHaveBeenCalled();+ });+it('should hide the .tool-results archive folder and its children by default', async () => {mockModel.listByAgent.mockResolvedValue([{diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex 567b98da1ac..0b4a785aec1 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -5,7 +5,7 @@ import type {DocumentTemplateSet,} from '@lobechat/agent-templates';import { DocumentLoadPosition, getDocumentTemplate, PolicyLoad } from '@lobechat/agent-templates';-import { buildAgentSkillIdentifier } from '@lobechat/const';+import { buildAgentSkillIdentifier, WEB_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';import type { DocumentAccessScope } from '@lobechat/types';@@ -45,6 +45,35 @@ import {} from './headlessEditor';const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;+/** Guards the ancestor walk against a corrupt parent cycle. */+const MAX_TREE_DEPTH = 64;++/**+ * Whether a document may hold children. Folders group; an ordinary document can+ * also be a parent — e.g. a workflow/SOP with its execution records nested under+ * it. Skills keep their own bundle layout and web clips are not tree-managed.+ */+const canHoldChildren = (doc: AgentDocument) =>+ !isManagedSkillDocument(doc) &&+ !doc.fileType.startsWith('skills/') &&+ doc.sourceType !== WEB_DOCUMENT_SOURCE_TYPE;++export type MoveAgentDocumentStatus = 'failed' | 'moved' | 'unchanged';++export interface MoveAgentDocumentResult {+ documentId?: string;+ error?: string;+ /** The agent-document row id when resolved, otherwise the reference the caller passed. */+ id: string;+ status: MoveAgentDocumentStatus;+ title?: string;+}++export interface CreateAgentFolderResult {+ /** False when a folder with the same name already existed under the same parent. */+ created: boolean;+ folder: AgentDocument;+}const appendFilenameSuffix = (filename: string, suffix: number): string => {const dotIndex = filename.lastIndexOf('.');@@ -638,13 +667,9 @@ export class AgentDocumentsService {content: string,options: CreateAgentDocumentOptions = {},) {- if (options.parentId) {- const parent = await this.agentDocumentModel.findByDocumentId(agentId, options.parentId);- if (!parent) throw new Error(`Parent folder not found: ${options.parentId}`);- if (parent.fileType !== DOCUMENT_FOLDER_TYPE) {- throw new Error(`Parent document is not a folder: ${options.parentId}`);- }- }+ const parentId = options.parentId+ ? (await this.resolveParent(agentId, options.parentId)).documentId+ : undefined;// The caller's explicit title wins; a leading H1 only names untitled documents.// The leading H1 is always dropped from the body: the document title renders@@ -665,8 +690,150 @@ export class AgentDocumentsService {return this.createWithUniqueFilename(agentId, finalTitle, finalContent, {...(metadata ? { metadata } : {}),- ...(options.parentId ? { parentId: options.parentId } : {}),+ ...(parentId ? { parentId } : {}),+ });+ }++ /**+ * Resolve a parent — a folder or an ordinary document — from either of its ids:+ * the backing `documentId` (`docs_…`, which listDocuments and the context index+ * show) or the agent-document row id (uuid). Models routinely pass the other id+ * of the pair, and a miss used to read back as an empty folder, so an unknown+ * reference, a skill, or a web clip throws.+ */+ async resolveParent(agentId: string, parentRef: string): Promise<AgentDocument> {+ const parent = await this.findReadableDocumentById(parentRef, agentId);+ if (!parent) throw new AgentDocumentVfsError(`Parent not found: ${parentRef}`, 'NOT_FOUND');+ if (!canHoldChildren(parent)) {+ throw new AgentDocumentVfsError(+ `"${parent.title}" cannot contain other documents (skills and web clips cannot be parents).`,+ 'BAD_REQUEST',+ );+ }++ return parent;+ }++ /**+ * Live children per parent `documentId`; parents without children are absent.+ * Omit `parentIds` to count every parent of the agent.+ */+ async countChildren(agentId: string, parentIds?: string[]): Promise<Map<string, number>> {+ return this.agentDocumentModel.countChildrenByParentIds(agentId, parentIds);+ }++ /**+ * Create a folder by name under the root or under an existing folder. Idempotent+ * like `mkdir -p`: an existing folder with the same name is returned as-is so a+ * scheduled task can call this on every run.+ */+ async createFolder(+ agentId: string,+ title: string,+ parentRef?: string | null,+ ): Promise<CreateAgentFolderResult> {+ const name = typeof title === 'string' ? title.trim() : '';+ if (!name || /[\\/]/.test(name)) {+ throw new AgentDocumentVfsError(+ 'Folder name must be non-empty and cannot contain "/" or "\\".',+ 'BAD_REQUEST',+ );+ }++ const parentId = parentRef ? (await this.resolveParent(agentId, parentRef)).documentId : null;+ const existing = await this.agentDocumentModel.findByParentAndFilename(agentId, parentId, name);+ if (existing) {+ if (existing.fileType === DOCUMENT_FOLDER_TYPE) return { created: false, folder: existing };++ throw new AgentDocumentVfsError(+ `A document named "${name}" already exists in that location.`,+ 'CONFLICT',+ );+ }++ const folder = await this.agentDocumentModel.create(agentId, name, '', {+ fileType: DOCUMENT_FOLDER_TYPE,+ parentId,+ title: name,});++ return { created: true, folder };+ }++ /**+ * Move documents or folders under a parent folder or document (or to the root+ * with `null`). Each+ * entry is applied and reported on its own so one bad id does not abort a bulk+ * reorganisation. Titles, ids, history and load rules are kept.+ */+ async moveDocuments(+ agentId: string,+ refs: string[],+ parentRef: string | null,+ ): Promise<MoveAgentDocumentResult[]> {+ const target = parentRef ? await this.resolveParent(agentId, parentRef) : undefined;+ const targetParentId = target?.documentId ?? null;+ const blockedIds = target ? await this.collectLineage(agentId, target) : new Set<string>();+ const results: MoveAgentDocumentResult[] = [];++ for (const ref of new Set(refs)) {+ const doc = await this.findReadableDocumentById(ref, agentId);+ if (!doc) {+ results.push({ error: `Document not found: ${ref}`, id: ref, status: 'failed' });+ continue;+ }++ const base = { documentId: doc.documentId, id: doc.id, title: doc.title };+ const fail = (error: string) => results.push({ ...base, error, status: 'failed' });++ if (isManagedSkillDocument(doc) || doc.fileType.startsWith('skills/')) {+ fail('Skill documents cannot be moved.');+ continue;+ }+ if ((doc.parentId ?? null) === targetParentId) {+ results.push({ ...base, status: 'unchanged' });+ continue;+ }+ if (blockedIds.has(doc.documentId)) {+ fail('Cannot move a document or folder under itself or one of its descendants.');+ continue;+ }++ const clash = await this.agentDocumentModel.findByParentAndFilename(+ agentId,+ targetParentId,+ doc.filename,+ );+ if (clash && clash.id !== doc.id) {+ fail(`"${doc.filename}" already exists in the destination folder.`);+ continue;+ }++ const moved = await this.agentDocumentModel.movePath(doc.id, {+ filename: doc.filename,+ parentId: targetParentId,+ title: doc.title,+ });+ if (moved) results.push({ ...base, status: 'moved' });+ else fail('Move failed.');+ }++ return results;+ }++ /** The target parent plus every ancestor; moving any of them into the target would loop. */+ private async collectLineage(agentId: string, parent: AgentDocument) {+ const lineage = new Set<string>([parent.documentId]);+ let parentId = parent.parentId;++ for (let depth = 0; parentId && depth < MAX_TREE_DEPTH; depth += 1) {+ if (lineage.has(parentId)) break;+ lineage.add(parentId);+ parentId =+ (await this.agentDocumentModel.findByDocumentId(agentId, parentId))?.parentId ?? null;+ }++ return lineage;}async createForTopic(@@ -690,10 +857,31 @@ export class AgentDocumentsService {return this.agentDocumentModel.delete(documentId);}- async removeDocumentById(documentId: string, expectedAgentId?: string): Promise<boolean> {+ async removeDocumentById(+ documentId: string,+ expectedAgentId?: string,+ options: { withChildren?: boolean } = {},+ ): Promise<boolean> {const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);if (!doc) return false;+ // A parent document carries its nested records (e.g. a workflow and its runs).+ // Removing only the parent would strand them under a deleted row, so the+ // caller has to choose: take the subtree, or move the children out first.+ const childCount =+ (await this.countChildren(doc.agentId, [doc.documentId])).get(doc.documentId) ?? 0;+ if (childCount > 0) {+ if (!options.withChildren) {+ throw new AgentDocumentVfsError(+ `"${doc.title}" has ${childCount} nested document(s). Remove it with withChildren: true to delete them too, or move them out first.`,+ 'CONFLICT',+ );+ }++ await this.agentDocumentModel.deleteSubtreeByDocumentId(doc.agentId, doc.documentId);+ return true;+ }+await this.deleteDocument(documentId);return true;}@@ -809,9 +997,12 @@ export class AgentDocumentsService {sourceType?: AgentDocumentListSourceType,options?: { excludeWeb?: boolean; includeArchivedToolResults?: boolean; parentId?: string },) {+ const parentId = options?.parentId+ ? (await this.resolveParent(agentId, options.parentId)).documentId+ : undefined;const docs = await this.agentDocumentModel.listByAgent(agentId, {excludeWeb: options?.excludeWeb,- parentId: options?.parentId,+ parentId,sourceType,});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.tsindex de827256807..1e5f3bb0e3b 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts@@ -77,6 +77,7 @@ describe('agentDocumentsRuntime auto-pin to task', () => {agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely.mockClear();serviceImpl = {copyDocumentById: vi.fn().mockResolvedValue(newDoc),+ countChildren: vi.fn().mockResolvedValue(new Map()),createDocument: vi.fn().mockResolvedValue(newDoc),createForTopic: vi.fn().mockResolvedValue(newDoc),getDocumentSnapshotById: vi.fn().mockResolvedValue(newDoc),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.test.tsindex 5e3cde090c6..183c069852a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.test.ts@@ -4,10 +4,12 @@ import { describe, expect, it, vi } from 'vitest';import { agentDocumentsRuntime } from './agentDocuments';const listDocuments = vi.fn();+const countChildren = vi.fn().mockResolvedValue(new Map([['documents-1', 3]]));vi.mock('@/server/services/agentDocuments', () => ({AgentDocumentsService: vi.fn().mockImplementation(function () {return {+ countChildren,listDocuments,};}),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.tsindex cd87f1f6e59..a3ea43d25f2 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts@@ -3,6 +3,7 @@ import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documentsimport { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';import { agentShareDocumentAccessScope, ordinaryDocumentAccessScope } from '@lobechat/types';+import type { AgentDocumentListItem } from '@/database/models/agentDocuments';import { TaskModel } from '@/database/models/task';import { AgentDocumentsService } from '@/server/services/agentDocuments';import { createDocumentWorkRegistrar } from '@/server/services/agentDocuments/documentWork';@@ -11,6 +12,17 @@ import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocumimport { resolveTaskWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';+const toListedDocument = (d: AgentDocumentListItem, childCounts: Map<string, number>) => ({+ childCount: childCounts.get(d.documentId) ?? 0,+ documentId: d.documentId,+ filename: d.filename,+ fileType: d.fileType,+ id: d.id,+ parentId: d.parentId,+ title: d.title,+ updatedAt: d.updatedAt,+});+export const agentDocumentsRuntime: ServerRuntimeRegistration = {factory: (context) => {if (!context.userId || !context.serverDB) {@@ -216,6 +228,21 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {);return doc;},+ createFolder: async ({ agentId, parentId, title }) => {+ if (shareTopicId) throw new Error('Creating folders is not available to share visitors');++ return withDocumentOutcome(+ {+ agentId,+ apiName: 'createFolder',+ getAgentDocumentId: (result) => result.folder.id,+ relation: 'created',+ summary: 'Agent documents created a folder.',+ toolAction: 'create',+ },+ async () => (await getService()).createFolder(agentId, title, parentId),+ );+ },listDocuments: async ({ agentId, parentId, sourceType }) => {const service = await getService();// Agents discover archived tool results via this path (see@@ -228,12 +255,8 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {includeArchivedToolResults: true,parentId,});- return docs.map((d) => ({- documentId: d.documentId,- filename: d.filename,- id: d.id,- title: d.title,- }));+ const childCounts = await service.countChildren(agentId);+ return docs.map((d) => toListedDocument(d, childCounts));},listTopicDocuments: async ({ agentId, parentId, sourceType, topicId }) => {const service = await getService();@@ -245,15 +268,29 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {includeArchivedToolResults: true,},);+ const childCounts = await service.countChildren(agentId);+ if (!parentId) return docs.map((d) => toListedDocument(d, childCounts));+// Topic listing joins through topic associations rather than the agent- // folder tree, so the folder filter is applied in-memory here.- const filtered = parentId ? docs.filter((d) => d.parentId === parentId) : docs;- return filtered.map((d) => ({- documentId: d.documentId,- filename: d.filename,- id: d.id,- title: d.title,- }));+ // folder tree, so the parent filter is applied in-memory here.+ const parent = await service.resolveParent(agentId, parentId);+ return docs+ .filter((d) => d.parentId === parent.documentId)+ .map((d) => toListedDocument(d, childCounts));+ },+ moveDocuments: async ({ agentId, ids, parentId }) => {+ if (shareTopicId) throw new Error('Moving documents is not available to share visitors');++ return withDocumentOutcome(+ {+ agentId,+ apiName: 'moveDocuments',+ relation: 'updated',+ summary: `Agent documents moved ${ids.length} document(s).`,+ toolAction: 'move',+ },+ async () => (await getService()).moveDocuments(agentId, ids, parentId),+ );},modifyNodes: async ({ agentId, id, operations }) => {const doc = await withDocumentOutcome(@@ -271,7 +308,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {},readDocument: async ({ agentId, id }) =>(await getService()).getDocumentSnapshotById(id, agentId),- removeDocument: ({ agentId, id }) =>+ removeDocument: ({ agentId, id, withChildren }) =>withDocumentOutcome({agentId,@@ -281,7 +318,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents removed a document.',toolAction: 'remove',},- async () => (await getService()).removeDocumentById(id, agentId),+ async () => (await getService()).removeDocumentById(id, agentId, { withChildren }),),renameDocument: async ({ agentId, id, newTitle }) => {const doc = await withDocumentOutcome(diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 2d98a65f5c4..270dc6001ca 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2627,6 +2627,7 @@"workflow.toolDisplayName.crawlSinglePage": "Crawled a page","workflow.toolDisplayName.createAgent": "Created an agent","workflow.toolDisplayName.createDocument": "Created a document",+ "workflow.toolDisplayName.createFolder": "Created a folder","workflow.toolDisplayName.createPlan": "Created a plan","workflow.toolDisplayName.createTodos": "Created todos","workflow.toolDisplayName.deleteAgent": "Deleted an agent",@@ -2652,6 +2653,7 @@"workflow.toolDisplayName.listLocalFiles": "Listed files","workflow.toolDisplayName.listOnlineDevices": "Listed devices","workflow.toolDisplayName.modifyNodes": "Modified Page",+ "workflow.toolDisplayName.moveDocuments": "Moved documents","workflow.toolDisplayName.moveLocalFiles": "Moved files","workflow.toolDisplayName.readDocument": "Read a document","workflow.toolDisplayName.readKnowledge": "Read knowledge",@@ -3108,6 +3110,7 @@"workingPanel.resources.tree.moveError": "Failed to move","workingPanel.resources.tree.newDocument": "New document","workingPanel.resources.tree.newFolder": "New folder",+ "workingPanel.resources.tree.newSubDocument": "New sub-document","workingPanel.resources.tree.parentMissing": "Parent folder is unavailable","workingPanel.resources.tree.rename": "Rename","workingPanel.resources.tree.untitledDocument": "Untitled document",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 0cbf59f4ff9..4cff53feafe 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -145,19 +145,33 @@"builtins.lobe-agent-builder.title": "Agent Builder Expert","builtins.lobe-agent-documents.apiName.copyDocument": "Copy document","builtins.lobe-agent-documents.apiName.createDocument": "Create document",+ "builtins.lobe-agent-documents.apiName.createFolder": "Create folder","builtins.lobe-agent-documents.apiName.listDocuments": "List documents","builtins.lobe-agent-documents.apiName.modifyNodes": "Modify document",+ "builtins.lobe-agent-documents.apiName.moveDocuments": "Move documents","builtins.lobe-agent-documents.apiName.readDocument": "Read document","builtins.lobe-agent-documents.apiName.removeDocument": "Remove document","builtins.lobe-agent-documents.apiName.renameDocument": "Rename document","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "Replace document content","builtins.lobe-agent-documents.apiName.updateLoadRule": "Update load rule",+ "builtins.lobe-agent-documents.createFolder.created": "Created",+ "builtins.lobe-agent-documents.createFolder.reused": "Already existed, reused","builtins.lobe-agent-documents.inspector.chars": "{{count}} chars","builtins.lobe-agent-documents.inspector.docCount": "{{count}} docs",+ "builtins.lobe-agent-documents.inspector.failedCount": "{{count}} failed","builtins.lobe-agent-documents.inspector.opsCount": "{{count}} ops","builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} ops","builtins.lobe-agent-documents.inspector.scope.agent": "in agent","builtins.lobe-agent-documents.inspector.scope.currentTopic": "in topic",+ "builtins.lobe-agent-documents.moveDocuments.destination": "Move to",+ "builtins.lobe-agent-documents.moveDocuments.from": "From {{parent}}",+ "builtins.lobe-agent-documents.moveDocuments.itemsToMove": "{{count}} item(s) to move",+ "builtins.lobe-agent-documents.moveDocuments.status.failed": "Failed",+ "builtins.lobe-agent-documents.moveDocuments.status.moved": "Moved",+ "builtins.lobe-agent-documents.moveDocuments.status.unchanged": "Already there",+ "builtins.lobe-agent-documents.ref.location": "Location",+ "builtins.lobe-agent-documents.ref.root": "Root",+ "builtins.lobe-agent-documents.ref.unknown": "Unknown document {{id}}","builtins.lobe-agent-documents.title": "Agent Documents","builtins.lobe-agent-management.apiName.callAgent": "Call agent","builtins.lobe-agent-management.apiName.createAgent": "Create agent",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 8e0d2577b64..0c52731c536 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2627,6 +2627,7 @@"workflow.toolDisplayName.crawlSinglePage": "抓取了页面","workflow.toolDisplayName.createAgent": "创建了助理","workflow.toolDisplayName.createDocument": "创建了文档",+ "workflow.toolDisplayName.createFolder": "创建了文件夹","workflow.toolDisplayName.createPlan": "创建了计划","workflow.toolDisplayName.createTodos": "创建了待办","workflow.toolDisplayName.deleteAgent": "删除了助理",@@ -2652,6 +2653,7 @@"workflow.toolDisplayName.listLocalFiles": "列出了文件","workflow.toolDisplayName.listOnlineDevices": "列出了在线设备","workflow.toolDisplayName.modifyNodes": "修改了文稿",+ "workflow.toolDisplayName.moveDocuments": "移动了文档","workflow.toolDisplayName.moveLocalFiles": "移动了文件","workflow.toolDisplayName.readDocument": "读取了文档","workflow.toolDisplayName.readKnowledge": "读取了知识",@@ -3108,6 +3110,7 @@"workingPanel.resources.tree.moveError": "移动失败","workingPanel.resources.tree.newDocument": "新建文档","workingPanel.resources.tree.newFolder": "新建文件夹",+ "workingPanel.resources.tree.newSubDocument": "新建子文档","workingPanel.resources.tree.parentMissing": "上级目录不可用","workingPanel.resources.tree.rename": "重命名","workingPanel.resources.tree.untitledDocument": "未命名文档",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 6a8ce63884c..ff22de78c6f 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -145,19 +145,33 @@"builtins.lobe-agent-builder.title": "助理构建专家","builtins.lobe-agent-documents.apiName.copyDocument": "复制文档","builtins.lobe-agent-documents.apiName.createDocument": "创建文档",+ "builtins.lobe-agent-documents.apiName.createFolder": "创建文件夹","builtins.lobe-agent-documents.apiName.listDocuments": "列出文档","builtins.lobe-agent-documents.apiName.modifyNodes": "修改文档",+ "builtins.lobe-agent-documents.apiName.moveDocuments": "移动文档","builtins.lobe-agent-documents.apiName.readDocument": "读取文档","builtins.lobe-agent-documents.apiName.removeDocument": "删除文档","builtins.lobe-agent-documents.apiName.renameDocument": "重命名文档","builtins.lobe-agent-documents.apiName.replaceDocumentContent": "替换文档内容","builtins.lobe-agent-documents.apiName.updateLoadRule": "更新加载规则",+ "builtins.lobe-agent-documents.createFolder.created": "已创建",+ "builtins.lobe-agent-documents.createFolder.reused": "已存在,直接复用","builtins.lobe-agent-documents.inspector.chars": "{{count}} 字","builtins.lobe-agent-documents.inspector.docCount": "{{count}} 篇",+ "builtins.lobe-agent-documents.inspector.failedCount": "{{count}} 个失败","builtins.lobe-agent-documents.inspector.opsCount": "{{count}} 项操作","builtins.lobe-agent-documents.inspector.opsResult": "{{success}}/{{total}} 项","builtins.lobe-agent-documents.inspector.scope.agent": "在代理中","builtins.lobe-agent-documents.inspector.scope.currentTopic": "在主题中",+ "builtins.lobe-agent-documents.moveDocuments.destination": "移动到",+ "builtins.lobe-agent-documents.moveDocuments.from": "原位置:{{parent}}",+ "builtins.lobe-agent-documents.moveDocuments.itemsToMove": "共 {{count}} 项待移动",+ "builtins.lobe-agent-documents.moveDocuments.status.failed": "失败",+ "builtins.lobe-agent-documents.moveDocuments.status.moved": "已移动",+ "builtins.lobe-agent-documents.moveDocuments.status.unchanged": "已在目标位置",+ "builtins.lobe-agent-documents.ref.location": "位置",+ "builtins.lobe-agent-documents.ref.root": "根目录",+ "builtins.lobe-agent-documents.ref.unknown": "未找到的文档 {{id}}","builtins.lobe-agent-documents.title": "Agent 文档","builtins.lobe-agent-management.apiName.callAgent": "呼叫代理","builtins.lobe-agent-management.apiName.createAgent": "创建代理",diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.tsindex 47cf30686d8..ffc517f984d 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts@@ -6,10 +6,12 @@ const createRuntime = (overrides = {}) =>new AgentDocumentsExecutionRuntime({copyDocument: vi.fn(),createDocument: vi.fn(),+ createFolder: vi.fn(),createTopicDocument: vi.fn(),listDocuments: vi.fn(),listTopicDocuments: vi.fn(),modifyNodes: vi.fn(),+ moveDocuments: vi.fn(),readDocument: vi.fn(),removeDocument: vi.fn(),renameDocument: vi.fn(),@@ -70,6 +72,214 @@ describe('AgentDocumentsExecutionRuntime', () => {});});+ // A flat listing used to give no way to tell folders from files or what was+ // already filed, so an agent organizing documents had to fall back to a CLI.+ describe('listDocuments folder metadata', () => {+ const docs = [+ {+ documentId: 'docs_folder',+ fileType: 'custom/folder',+ filename: 'P95 Reports',+ id: 'row-folder',+ parentId: null,+ title: 'P95 Reports',+ updatedAt: new Date('2026-10-11T03:54:00.000Z'),+ },+ {+ documentId: 'docs_a',+ fileType: 'agent/document',+ filename: 'P95 Report 2026-10-10',+ id: 'row-a',+ parentId: 'docs_folder',+ title: 'P95 Report 2026-10-10',+ updatedAt: '2026-10-10T04:24:52.758Z',+ },+ {+ documentId: 'docs_b',+ fileType: 'agent/document',+ filename: 'Tick log',+ id: 'row-b',+ parentId: null,+ title: 'Tick log',+ },+ ];++ it('reports type, parentId and updatedAt for each entry', async () => {+ const runtime = createRuntime({ listDocuments: vi.fn().mockResolvedValue(docs) });++ const result = await runtime.listDocuments({}, { agentId: 'agent-1' });++ expect(result.state?.documents).toEqual([+ expect.objectContaining({+ id: 'row-folder',+ parentId: null,+ type: 'folder',+ updatedAt: '2026-10-11T03:54:00.000Z',+ }),+ expect.objectContaining({+ id: 'row-a',+ parentId: 'docs_folder',+ type: 'file',+ updatedAt: '2026-10-10T04:24:52.758Z',+ }),+ expect.objectContaining({ id: 'row-b', parentId: null, type: 'file' }),+ ]);+ });++ it('filters by title before paging and keeps the filter in the next-page arguments', async () => {+ const many = Array.from({ length: 30 }, (_, i) => ({+ documentId: `docs_${i}`,+ filename: `doc-${i}`,+ id: `row-${i}`,+ title: i % 2 === 0 ? `LobeHub Cloud P95 Report ${i}` : `Tick log ${i}`,+ }));+ const runtime = createRuntime({ listDocuments: vi.fn().mockResolvedValue(many) });++ const result = await runtime.listDocuments(+ { limit: 10, titleContains: 'p95 report' },+ { agentId: 'agent-1' },+ );++ expect(result.state?.documents).toHaveLength(10);+ expect(result.state?.documents.every((d: { title: string }) => d.title.includes('P95'))).toBe(+ true,+ );+ expect(result.content).toContain(+ 'Showing documents 1-10 of 15. For the next page call listDocuments with {"limit":10,"offset":10,"scope":"agent","sourceType":"all","titleContains":"p95 report"}.',+ );+ });+ });++ describe('createFolder', () => {+ it('returns the folder id to use as parentId', async () => {+ const createFolder = vi.fn().mockResolvedValue({+ created: true,+ folder: { documentId: 'docs_folder', id: 'row-folder', title: 'P95 Reports' },+ });+ const runtime = createRuntime({ createFolder });++ const result = await runtime.createFolder(+ { parentId: 'docs_parent', title: ' P95 Reports ' },+ { agentId: 'agent-1' },+ );++ expect(createFolder).toHaveBeenCalledWith({+ agentId: 'agent-1',+ parentId: 'docs_parent',+ title: ' P95 Reports ',+ });+ expect(result.success).toBe(true);+ expect(result.content).toContain('Created folder "P95 Reports" (folder id: docs_folder)');+ expect(result.state).toEqual({+ agentDocumentId: 'row-folder',+ agentId: 'agent-1',+ created: true,+ documentId: 'docs_folder',+ title: 'P95 Reports',+ });+ });++ it('says when an existing folder was reused', async () => {+ const runtime = createRuntime({+ createFolder: vi.fn().mockResolvedValue({+ created: false,+ folder: { documentId: 'docs_folder', id: 'row-folder', title: 'P95 Reports' },+ }),+ });++ const result = await runtime.createFolder({ title: 'P95 Reports' }, { agentId: 'agent-1' });++ expect(result.content).toContain('Reused existing folder "P95 Reports"');+ });++ it('rejects an empty title without calling the service', async () => {+ const createFolder = vi.fn();+ const runtime = createRuntime({ createFolder });++ const result = await runtime.createFolder({ title: ' ' }, { agentId: 'agent-1' });++ expect(result.success).toBe(false);+ expect(createFolder).not.toHaveBeenCalled();+ });+ });++ describe('moveDocuments', () => {+ it('moves every id in one service call and summarizes the outcome', async () => {+ const moveDocuments = vi.fn().mockResolvedValue([+ { documentId: 'docs_a', id: 'row-a', status: 'moved', title: 'A' },+ { documentId: 'docs_b', id: 'row-b', status: 'unchanged', title: 'B' },+ { error: 'Document not found: missing', id: 'missing', status: 'failed' },+ ]);+ const runtime = createRuntime({ moveDocuments });++ const result = await runtime.moveDocuments(+ { ids: ['row-a', 'docs_b', 'missing', ''], parentId: 'docs_folder' },+ { agentId: 'agent-1' },+ );++ expect(moveDocuments).toHaveBeenCalledWith({+ agentId: 'agent-1',+ ids: ['row-a', 'docs_b', 'missing'],+ parentId: 'docs_folder',+ });+ // A partial move changed the tree, so the call is still a success.+ expect(result.success).toBe(true);+ expect(result.content).toContain(+ 'Moved 1 item(s) to folder docs_folder; 1 already there; 1 failed.',+ );+ expect(result.content).toContain('- missing: Document not found: missing');+ expect(result.state).toMatchObject({ failedCount: 1, movedCount: 1 });+ });++ it.each([null, '', 'root'])('treats parentId %j as the root', async (parentId) => {+ const moveDocuments = vi+ .fn()+ .mockResolvedValue([{ id: 'row-a', status: 'moved', title: 'A' }]);+ const runtime = createRuntime({ moveDocuments });++ const result = await runtime.moveDocuments(+ { ids: ['row-a'], parentId: parentId as string | null },+ { agentId: 'agent-1' },+ );++ expect(moveDocuments).toHaveBeenCalledWith(expect.objectContaining({ parentId: null }));+ expect(result.content).toContain('to the root');+ });++ it('fails when every move failed', async () => {+ const runtime = createRuntime({+ moveDocuments: vi+ .fn()+ .mockResolvedValue([+ { error: 'Skill documents cannot be moved.', id: 'x', status: 'failed' },+ ]),+ });++ const result = await runtime.moveDocuments(+ { ids: ['x'], parentId: 'docs_folder' },+ { agentId: 'agent-1' },+ );++ expect(result.success).toBe(false);+ });++ it('rejects an empty or oversized id list without calling the service', async () => {+ const moveDocuments = vi.fn();+ const runtime = createRuntime({ moveDocuments });++ const empty = await runtime.moveDocuments({ ids: [], parentId: null }, { agentId: 'a' });+ const oversized = await runtime.moveDocuments(+ { ids: Array.from({ length: 201 }, (_, i) => `row-${i}`), parentId: null },+ { agentId: 'a' },+ );++ expect(empty.success).toBe(false);+ expect(oversized.success).toBe(false);+ expect(oversized.content).toContain('at most 200 ids');+ expect(moveDocuments).not.toHaveBeenCalled();+ });+ });+it('returns agentDocumentId and documentId when creating hinted documents', async () => {const createDocument = vi.fn().mockResolvedValue({documentId: 'backing-doc-1',diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.tsindex ed6cd51c5b4..bebf6ddc351 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts@@ -1,7 +1,9 @@import {formatCopyDocumentResult,formatCreateDocumentResult,+ formatCreateFolderResult,formatModifyDocumentResult,+ formatMoveDocumentsResult,formatRemoveDocumentResult,formatRenameDocumentResult,formatReplaceDocumentResult,@@ -13,9 +15,13 @@ import type { BuiltinServerRuntimeOutput } from '@lobechat/types';import type {CopyDocumentArgs,CreateDocumentArgs,+ CreateFolderArgs,ListDocumentsArgs,+ ListedAgentDocument,ModifyDocumentNodesArgs,ModifyDocumentOperation,+ MoveDocumentResultItem,+ MoveDocumentsArgs,ReadDocumentArgs,RemoveDocumentArgs,RenameDocumentArgs,@@ -26,6 +32,7 @@ import {LIST_DOCUMENTS_DEFAULT_LIMIT,LIST_DOCUMENTS_MAX_LIMIT,MAX_READ_DOCUMENT_CONTENT_CHARS,+ MOVE_DOCUMENTS_MAX_IDS,} from '../types';const clampListLimit = (limit: unknown): number => {@@ -35,6 +42,8 @@ const clampListLimit = (limit: unknown): number => {};interface AgentDocumentRecord {+ /** Entries nested directly under this one (folders and documents can both be parents). */+ childCount?: number;content?: string;/*** The underlying `documents` table id. Used for portal rendering@@ -44,15 +53,22 @@ interface AgentDocumentRecord {*/documentId?: string;filename?: string;+ /** `custom/folder` marks a folder; anything else is a file. */+ fileType?: string;/*** The `agentDocuments` association row id. This is what the LLM receives* and uses for subsequent operations (read/edit/remove/...).*/id: string;litexml?: string;+ /** `documentId` of the containing folder or document; null at the root. */+ parentId?: string | null;title?: string;+ updatedAt?: Date | string;}+const FOLDER_FILE_TYPE = 'custom/folder';+interface AgentDocumentOperationContext {agentId?: string | null;currentDocumentId?: string | null;@@ -111,6 +127,9 @@ export interface AgentDocumentsRuntimeService {agentId: string;} & AgentDocumentToolTriggerInput,) => Promise<AgentDocumentRecord | undefined>;+ createFolder: (+ params: CreateFolderArgs & { agentId: string },+ ) => Promise<{ created: boolean; folder: AgentDocumentRecord }>;createTopicDocument: (params: CreateDocumentArgs & {agentId: string;@@ -133,6 +152,9 @@ export interface AgentDocumentsRuntimeService {agentId: string;} & AgentDocumentToolTriggerInput,) => Promise<AgentDocumentRecord | undefined>;+ moveDocuments: (+ params: MoveDocumentsArgs & { agentId: string },+ ) => Promise<MoveDocumentResultItem[]>;readDocument: (params: ReadDocumentArgs & {agentId: string;@@ -454,17 +476,32 @@ export class AgentDocumentsExecutionRuntime {topicId: topicId!,}): await this.service.listDocuments({ agentId, parentId, scope, sourceType });+ const titleQuery = args.titleContains?.trim().toLowerCase();+ const matched = titleQuery+ ? docs.filter((d) => (d.title ?? d.filename ?? '').toLowerCase().includes(titleQuery))+ : docs;const limit = clampListLimit(args.limit);const offset = Math.max(0, Math.floor(Number(args.offset) || 0));- const page = docs.slice(offset, offset + limit);- const list = await Promise.all(+ const page = matched.slice(offset, offset + limit);+ const list: ListedAgentDocument[] = await Promise.all(page.map(async (d) => {const url = await this.buildDocumentUrl(agentId, d.documentId);+ const updatedAt = d.updatedAt ? new Date(d.updatedAt) : undefined;return {...(d.documentId ? { documentId: d.documentId } : {}),filename: d.filename ?? d.title ?? '',id: d.id,+ // Folder membership lets the agent see what is filed where without a+ // second listing per folder; null marks a root entry.+ ...(d.parentId !== undefined ? { parentId: d.parentId } : {}),+ ...(d.childCount ? { childCount: d.childCount } : {}),title: d.title,+ ...(d.fileType !== undefined+ ? { type: d.fileType === FOLDER_FILE_TYPE ? 'folder' : 'file' }+ : {}),+ ...(updatedAt && !Number.isNaN(updatedAt.getTime())+ ? { updatedAt: updatedAt.toISOString() }+ : {}),// The clickable link lets the agent reference any listed document to// the user; omitted when no url builder is configured....(url ? { url } : {}),@@ -481,10 +518,11 @@ export class AgentDocumentsExecutionRuntime {...(parentId ? { parentId } : {}),scope,sourceType,+ ...(titleQuery ? { titleContains: args.titleContains } : {}),});const pagingNote =- nextOffset < docs.length- ? `\n\nShowing documents ${offset + 1}-${nextOffset} of ${docs.length}. For the next page call listDocuments with ${nextArgs}.`+ nextOffset < matched.length+ ? `\n\nShowing documents ${offset + 1}-${nextOffset} of ${matched.length}. For the next page call listDocuments with ${nextArgs}.`: '';return {@@ -555,6 +593,77 @@ export class AgentDocumentsExecutionRuntime {};}+ async createFolder(+ args: CreateFolderArgs,+ context?: AgentDocumentOperationContext,+ ): Promise<BuiltinServerRuntimeOutput> {+ const agentId = this.resolveAgentId(context);+ if (!agentId) {+ return { content: 'Cannot create a folder without agentId context.', success: false };+ }+ if (!nonEmptyString(args.title)) {+ return { content: 'createFolder requires a non-empty `title`.', success: false };+ }++ const { created, folder } = await this.service.createFolder({+ agentId,+ ...(nonEmptyString(args.parentId) ? { parentId: args.parentId } : {}),+ title: args.title,+ });+ const folderId = folder.documentId ?? folder.id;+ const title = folder.title || args.title.trim();++ return {+ content: formatCreateFolderResult({ created, folderId, title }),+ state: {+ agentDocumentId: folder.id,+ agentId,+ created,+ documentId: folder.documentId,+ title,+ },+ success: true,+ };+ }++ async moveDocuments(+ args: MoveDocumentsArgs,+ context?: AgentDocumentOperationContext,+ ): Promise<BuiltinServerRuntimeOutput> {+ const agentId = this.resolveAgentId(context);+ if (!agentId) {+ return { content: 'Cannot move agent documents without agentId context.', success: false };+ }++ const ids = Array.isArray(args.ids) ? args.ids.filter(nonEmptyString) : [];+ if (ids.length === 0) {+ return {+ content: 'moveDocuments requires `ids`: the ids of the documents or folders to move.',+ success: false,+ };+ }+ if (ids.length > MOVE_DOCUMENTS_MAX_IDS) {+ return {+ content: `moveDocuments accepts at most ${MOVE_DOCUMENTS_MAX_IDS} ids per call; split the rest into another call. Nothing was moved.`,+ success: false,+ };+ }++ // Models send "", "root" or omit the field to mean the root; only a real id targets a folder.+ const parentId =+ nonEmptyString(args.parentId) && args.parentId !== 'root' ? args.parentId : null;+ const results = await this.service.moveDocuments({ agentId, ids, parentId });+ const movedCount = results.filter((r) => r.status === 'moved').length;+ const failedCount = results.filter((r) => r.status === 'failed').length;++ return {+ content: formatMoveDocumentsResult({ parentId, results }),+ state: { agentId, failedCount, movedCount, parentId, results },+ // A partial move still changed the tree; only an all-failed call is a failure.+ success: failedCount < results.length,+ };+ }+async readDocument(rawArgs: ReadDocumentArgs,context?: AgentDocumentOperationContext,diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/CreateFolder/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/CreateFolder/index.tsxnew file mode 100644index 00000000000..7196d039659--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/CreateFolder/index.tsx@@ -0,0 +1,43 @@+'use client';++import type { BuiltinInspectorProps } from '@lobechat/types';+import { cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { inspectorTextStyles, shinyTextStyles } from '@/styles';++import type { CreateFolderArgs, CreateFolderState } from '../../../types';+import { inspectorChipStyles } from '../_styles';++export const CreateFolderInspector = memo<+ BuiltinInspectorProps<CreateFolderArgs, CreateFolderState>+>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {+ const { t } = useTranslation('plugin');++ const title = args?.title || partialArgs?.title;+ const styles = inspectorChipStyles;++ if (isArgumentsStreaming && !title) {+ return (+ <div className={inspectorTextStyles.root}>+ <span className={shinyTextStyles.shinyText}>+ {t('builtins.lobe-agent-documents.apiName.createFolder')}+ </span>+ </div>+ );+ }++ return (+ <div className={inspectorTextStyles.root} style={{ flexWrap: 'wrap', gap: 4 }}>+ <span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>+ {t('builtins.lobe-agent-documents.apiName.createFolder')}+ </span>+ {title && <span className={styles.chip}>{title}</span>}+ </div>+ );+});++CreateFolderInspector.displayName = 'CreateFolderInspector';++export default CreateFolderInspector;diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/MoveDocuments/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/MoveDocuments/index.tsxnew file mode 100644index 00000000000..ce13f75e6b3--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/MoveDocuments/index.tsx@@ -0,0 +1,45 @@+'use client';++import type { BuiltinInspectorProps } from '@lobechat/types';+import { cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { inspectorTextStyles, shinyTextStyles } from '@/styles';++import type { MoveDocumentsArgs, MoveDocumentsState } from '../../../types';+import { inspectorChipStyles } from '../_styles';++export const MoveDocumentsInspector = memo<+ BuiltinInspectorProps<MoveDocumentsArgs, MoveDocumentsState>+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const { t } = useTranslation('plugin');++ const ids = args?.ids || partialArgs?.ids;+ const styles = inspectorChipStyles;+ const count = pluginState?.movedCount ?? ids?.length;++ return (+ <div className={inspectorTextStyles.root} style={{ flexWrap: 'wrap', gap: 4 }}>+ <span className={cx((isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText)}>+ {t('builtins.lobe-agent-documents.apiName.moveDocuments')}+ </span>+ {count !== undefined && (+ <span className={styles.chip}>+ {t('builtins.lobe-agent-documents.inspector.docCount', { count })}+ </span>+ )}+ {!!pluginState?.failedCount && (+ <span className={styles.subdued}>+ {t('builtins.lobe-agent-documents.inspector.failedCount', {+ count: pluginState.failedCount,+ })}+ </span>+ )}+ </div>+ );+});++MoveDocumentsInspector.displayName = 'MoveDocumentsInspector';++export default MoveDocumentsInspector;diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/index.ts b/packages/builtin-tool-agent-documents/src/client/Inspector/index.tsindex 5cb31b4a8be..014615c68a0 100644--- a/packages/builtin-tool-agent-documents/src/client/Inspector/index.ts+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/index.ts@@ -3,8 +3,10 @@ import type { BuiltinInspector } from '@lobechat/types';import { AgentDocumentsApiName } from '../../types';import { CopyDocumentInspector } from './CopyDocument';import { CreateDocumentInspector } from './CreateDocument';+import { CreateFolderInspector } from './CreateFolder';import { ListDocumentsInspector } from './ListDocuments';import { ModifyNodesInspector } from './ModifyNodes';+import { MoveDocumentsInspector } from './MoveDocuments';import { ReadDocumentInspector } from './ReadDocument';import { RemoveDocumentInspector } from './RemoveDocument';import { RenameDocumentInspector } from './RenameDocument';@@ -14,8 +16,10 @@ import { UpdateLoadRuleInspector } from './UpdateLoadRule';export const AgentDocumentsInspectors: Record<string, BuiltinInspector> = {[AgentDocumentsApiName.copyDocument]: CopyDocumentInspector as BuiltinInspector,[AgentDocumentsApiName.createDocument]: CreateDocumentInspector as BuiltinInspector,+ [AgentDocumentsApiName.createFolder]: CreateFolderInspector as BuiltinInspector,[AgentDocumentsApiName.listDocuments]: ListDocumentsInspector as BuiltinInspector,[AgentDocumentsApiName.modifyNodes]: ModifyNodesInspector as BuiltinInspector,+ [AgentDocumentsApiName.moveDocuments]: MoveDocumentsInspector as BuiltinInspector,[AgentDocumentsApiName.readDocument]: ReadDocumentInspector as BuiltinInspector,[AgentDocumentsApiName.removeDocument]: RemoveDocumentInspector as BuiltinInspector,[AgentDocumentsApiName.renameDocument]: RenameDocumentInspector as BuiltinInspector,diff --git a/packages/builtin-tool-agent-documents/src/client/Intervention/CreateFolder/index.tsx b/packages/builtin-tool-agent-documents/src/client/Intervention/CreateFolder/index.tsxnew file mode 100644index 00000000000..ca88ed21acd--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Intervention/CreateFolder/index.tsx@@ -0,0 +1,36 @@+'use client';++import type { BuiltinInterventionProps } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { FolderPlusIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { CreateFolderArgs } from '../../../types';+import DocumentRef from '../../shared/DocumentRef';+import { cardStyles } from '../../shared/styles';+import { useAgentDocumentLookup } from '../../shared/useAgentDocumentLookup';++/** Approval for createFolder: which folder, and where it will appear. */+const CreateFolderIntervention = memo<BuiltinInterventionProps<CreateFolderArgs>>(({ args }) => {+ const { t } = useTranslation('plugin');+ const { lookup } = useAgentDocumentLookup();++ return (+ <Flexbox className={cardStyles.card} gap={6}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon className={cardStyles.arrow} icon={FolderPlusIcon} size={16} />+ <Text strong>{args?.title}</Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text className={cardStyles.label}>{t('builtins.lobe-agent-documents.ref.location')}</Text>+ <DocumentRef lookup={lookup} refId={args?.parentId} />+ </Flexbox>+ </Flexbox>+ );+});++CreateFolderIntervention.displayName = 'AgentDocumentsCreateFolderIntervention';++export default CreateFolderIntervention;diff --git a/packages/builtin-tool-agent-documents/src/client/Intervention/MoveDocuments/index.tsx b/packages/builtin-tool-agent-documents/src/client/Intervention/MoveDocuments/index.tsxnew file mode 100644index 00000000000..0734c64fbd6--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Intervention/MoveDocuments/index.tsx@@ -0,0 +1,61 @@+'use client';++import type { BuiltinInterventionProps } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { MoveDocumentsArgs } from '../../../types';+import { describeCurrentParent, type DocumentRefView } from '../../shared/describeDocumentRef';+import DocumentRef from '../../shared/DocumentRef';+import { cardStyles } from '../../shared/styles';+import { useAgentDocumentLookup } from '../../shared/useAgentDocumentLookup';++/**+ * Approval for moveDocuments: the documents by title, where each sits now, and+ * the destination — the raw ids the model sends say nothing to the user.+ */+const MoveDocumentsIntervention = memo<BuiltinInterventionProps<MoveDocumentsArgs>>(({ args }) => {+ const { t } = useTranslation('plugin');+ const { lookup } = useAgentDocumentLookup();+ const ids = Array.isArray(args?.ids) ? args.ids : [];+ const parentLabel = (view: DocumentRefView) => {+ if (view.kind === 'root') return t('builtins.lobe-agent-documents.ref.root');+ return view.kind === 'unknown' ? view.id : view.title;+ };++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} className={cardStyles.card} gap={8}>+ <Text className={cardStyles.label}>+ {t('builtins.lobe-agent-documents.moveDocuments.destination')}+ </Text>+ <DocumentRef strong lookup={lookup} refId={args?.parentId} />+ </Flexbox>+ <Text type={'secondary'}>+ {t('builtins.lobe-agent-documents.moveDocuments.itemsToMove', { count: ids.length })}+ </Text>+ <Flexbox gap={2}>+ {ids.map((id) => (+ <Flexbox horizontal align={'center'} className={cardStyles.row} gap={8} key={id}>+ <Flexbox flex={2} style={{ minWidth: 0 }}>+ <DocumentRef lookup={lookup} refId={id} />+ </Flexbox>+ <Flexbox align={'flex-end'} flex={1} style={{ minWidth: 0 }}>+ <Text ellipsis type={'secondary'}>+ {t('builtins.lobe-agent-documents.moveDocuments.from', {+ parent: parentLabel(describeCurrentParent(lookup, id)),+ })}+ </Text>+ </Flexbox>+ </Flexbox>+ ))}+ </Flexbox>+ </Flexbox>+ );+});++MoveDocumentsIntervention.displayName = 'AgentDocumentsMoveDocumentsIntervention';++export default MoveDocumentsIntervention;diff --git a/packages/builtin-tool-agent-documents/src/client/Intervention/index.ts b/packages/builtin-tool-agent-documents/src/client/Intervention/index.tsnew file mode 100644index 00000000000..e582fc4d873--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Intervention/index.ts@@ -0,0 +1,9 @@+import { AgentDocumentsApiName } from '../../types';+import CreateFolder from './CreateFolder';+import MoveDocuments from './MoveDocuments';++/** Approval cards for the APIs whose raw arguments are ids the user cannot read. */+export const AgentDocumentsInterventions = {+ [AgentDocumentsApiName.createFolder]: CreateFolder,+ [AgentDocumentsApiName.moveDocuments]: MoveDocuments,+};diff --git a/packages/builtin-tool-agent-documents/src/client/Render/CreateFolder/index.tsx b/packages/builtin-tool-agent-documents/src/client/Render/CreateFolder/index.tsxnew file mode 100644index 00000000000..4f9e5b87127--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Render/CreateFolder/index.tsx@@ -0,0 +1,49 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { FolderIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { CreateFolderArgs, CreateFolderState } from '../../../types';+import DocumentRef from '../../shared/DocumentRef';+import { cardStyles } from '../../shared/styles';+import { useAgentDocumentLookup } from '../../shared/useAgentDocumentLookup';++/** Result of createFolder: the folder, where it lives, and whether it was reused. */+const CreateFolderRender = memo<+ Pick<BuiltinRenderProps<CreateFolderArgs, CreateFolderState>, 'args' | 'pluginState'>+>(({ args, pluginState }) => {+ const { t } = useTranslation('plugin');+ const { lookup } = useAgentDocumentLookup();+ const title = pluginState?.title || args?.title;+ if (!title) return null;++ return (+ <Flexbox className={cardStyles.card} gap={6}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon className={cardStyles.arrow} icon={FolderIcon} size={16} />+ <Text strong>{title}</Text>+ {pluginState && (+ <Text className={cardStyles.status} type={'secondary'}>+ {t(+ pluginState.created+ ? 'builtins.lobe-agent-documents.createFolder.created'+ : 'builtins.lobe-agent-documents.createFolder.reused',+ )}+ </Text>+ )}+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text className={cardStyles.label}>{t('builtins.lobe-agent-documents.ref.location')}</Text>+ <DocumentRef lookup={lookup} refId={args?.parentId} />+ </Flexbox>+ </Flexbox>+ );+});++CreateFolderRender.displayName = 'AgentDocumentsCreateFolderRender';++export default CreateFolderRender;diff --git a/packages/builtin-tool-agent-documents/src/client/Render/MoveDocuments/index.tsx b/packages/builtin-tool-agent-documents/src/client/Render/MoveDocuments/index.tsxnew file mode 100644index 00000000000..0481b608656--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/Render/MoveDocuments/index.tsx@@ -0,0 +1,66 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { MoveDocumentsArgs, MoveDocumentsState } from '../../../types';+import DocumentRef from '../../shared/DocumentRef';+import { cardStyles } from '../../shared/styles';+import { useAgentDocumentLookup } from '../../shared/useAgentDocumentLookup';++const STATUS_TYPE = { failed: 'danger', moved: 'success', unchanged: 'secondary' } as const;++/** Result of moveDocuments: destination, then each document with its outcome. */+const MoveDocumentsRender = memo<+ Pick<BuiltinRenderProps<MoveDocumentsArgs, MoveDocumentsState>, 'args' | 'pluginState'>+>(({ args, pluginState }) => {+ const { t } = useTranslation('plugin');+ const { lookup } = useAgentDocumentLookup();+ const results =+ pluginState?.results ??+ (Array.isArray(args?.ids) ? args.ids.map((id) => ({ id, status: undefined })) : []);+ if (results.length === 0) return null;++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} className={cardStyles.card} gap={8}>+ <Text className={cardStyles.label}>+ {t('builtins.lobe-agent-documents.moveDocuments.destination')}+ </Text>+ <DocumentRef strong lookup={lookup} refId={pluginState?.parentId ?? args?.parentId} />+ </Flexbox>+ <Flexbox gap={2}>+ {results.map((item) => (+ <Flexbox gap={2} key={item.id}>+ <Flexbox horizontal align={'center'} className={cardStyles.row} gap={8}>+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ <DocumentRef+ fallbackTitle={'title' in item ? item.title : undefined}+ lookup={lookup}+ refId={item.id}+ />+ </Flexbox>+ {item.status && (+ <Text className={cardStyles.status} type={STATUS_TYPE[item.status]}>+ {t(`builtins.lobe-agent-documents.moveDocuments.status.${item.status}`)}+ </Text>+ )}+ </Flexbox>+ {'error' in item && item.error && (+ <Text style={{ paddingInline: 12 }} type={'danger'}>+ {item.error}+ </Text>+ )}+ </Flexbox>+ ))}+ </Flexbox>+ </Flexbox>+ );+});++MoveDocumentsRender.displayName = 'AgentDocumentsMoveDocumentsRender';++export default MoveDocumentsRender;diff --git a/packages/builtin-tool-agent-documents/src/client/Render/index.ts b/packages/builtin-tool-agent-documents/src/client/Render/index.tsindex 9dbc514a88b..194478a06dd 100644--- a/packages/builtin-tool-agent-documents/src/client/Render/index.ts+++ b/packages/builtin-tool-agent-documents/src/client/Render/index.ts@@ -1,7 +1,11 @@import CreateDocument from './CreateDocument';+import CreateFolder from './CreateFolder';+import MoveDocuments from './MoveDocuments';export const AgentDocumentsRenders = {createDocument: CreateDocument,+ createFolder: CreateFolder,+ moveDocuments: MoveDocuments,};export { default as CreateDocument } from './CreateDocument';diff --git a/packages/builtin-tool-agent-documents/src/client/index.ts b/packages/builtin-tool-agent-documents/src/client/index.tsindex 63a1eb3bc13..d5ec5cbb3e4 100644--- a/packages/builtin-tool-agent-documents/src/client/index.ts+++ b/packages/builtin-tool-agent-documents/src/client/index.ts@@ -1,5 +1,6 @@export { AgentDocumentsManifest } from '../manifest';export * from '../types';export { AgentDocumentsInspectors } from './Inspector';+export { AgentDocumentsInterventions } from './Intervention';export { AgentDocumentsRenders } from './Render';export { AgentDocumentsStreamings } from './Streaming';diff --git a/packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx b/packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsxnew file mode 100644index 00000000000..258b6906ddb--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/shared/DocumentRef.tsx@@ -0,0 +1,61 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { FileTextIcon, FolderIcon, HomeIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { describeDocumentRef } from './describeDocumentRef';+import type { AgentDocumentLookup } from './useAgentDocumentLookup';++const styles = createStaticStyles(({ css, cssVar }) => ({+ icon: css`+ flex: none;+ color: ${cssVar.colorTextDescription};+ `,+ id: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ `,+}));++interface DocumentRefProps {+ /** Title to show when the id no longer resolves (e.g. from a tool result). */+ fallbackTitle?: string;+ lookup: AgentDocumentLookup;+ /** A document/folder id, or null/undefined for the root. */+ refId?: string | null;+ strong?: boolean;+}++/** One document, folder or the root, shown as the user knows it: glyph + title. */+const DocumentRef = memo<DocumentRefProps>(({ fallbackTitle, lookup, refId, strong }) => {+ const { t } = useTranslation('plugin');+ const view = describeDocumentRef(lookup, refId, fallbackTitle);++ if (view.kind === 'unknown') {+ return (+ <Text className={styles.id} type={'secondary'}>+ {t('builtins.lobe-agent-documents.ref.unknown', { id: view.id })}+ </Text>+ );+ }++ const icon = view.kind === 'root' ? HomeIcon : view.kind === 'folder' ? FolderIcon : FileTextIcon;+ const title = view.kind === 'root' ? t('builtins.lobe-agent-documents.ref.root') : view.title;++ return (+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>+ <Icon className={styles.icon} icon={icon} size={14} />+ <Text ellipsis strong={strong}>+ {title}+ </Text>+ </Flexbox>+ );+});++DocumentRef.displayName = 'AgentDocumentRef';++export default DocumentRef;diff --git a/packages/builtin-tool-agent-documents/src/client/shared/describeDocumentRef.test.ts b/packages/builtin-tool-agent-documents/src/client/shared/describeDocumentRef.test.tsnew file mode 100644index 00000000000..0a2152b79f6--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/shared/describeDocumentRef.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { describeCurrentParent, describeDocumentRef } from './describeDocumentRef';++const rows = [+ {+ documentId: 'docs_sop',+ fileType: 'agent/document',+ id: 'row-sop',+ parentId: null,+ title: 'SOP',+ },+ {+ documentId: 'docs_folder',+ fileType: 'custom/folder',+ id: 'row-folder',+ parentId: null,+ title: 'Reports',+ },+ {+ documentId: 'docs_run',+ fileType: 'agent/document',+ id: 'row-run',+ parentId: 'docs_sop',+ title: 'Run',+ },+];+const lookup = (ref?: string | null) => rows.find((r) => r.id === ref || r.documentId === ref);++// Approval and result cards show titles, never the raw ids the model sends.+describe('describeDocumentRef', () => {+ it('reads a missing id as the root', () => {+ expect(describeDocumentRef(lookup, null)).toEqual({ kind: 'root' });+ expect(describeDocumentRef(lookup, undefined)).toEqual({ kind: 'root' });+ });++ it('resolves either id of a row to its title and kind', () => {+ expect(describeDocumentRef(lookup, 'docs_folder')).toEqual({+ kind: 'folder',+ title: 'Reports',+ });+ expect(describeDocumentRef(lookup, 'row-sop')).toEqual({ kind: 'document', title: 'SOP' });+ });++ it('falls back to the title a result carried, then to an unknown id', () => {+ expect(describeDocumentRef(lookup, 'row-gone', 'Deleted run')).toEqual({+ kind: 'document',+ title: 'Deleted run',+ });+ expect(describeDocumentRef(lookup, 'row-gone')).toEqual({ id: 'row-gone', kind: 'unknown' });+ });++ it('describes where a document sits now, the root when it has no parent', () => {+ expect(describeCurrentParent(lookup, 'row-run')).toEqual({ kind: 'document', title: 'SOP' });+ expect(describeCurrentParent(lookup, 'row-folder')).toEqual({ kind: 'root' });+ });+});diff --git a/packages/builtin-tool-agent-documents/src/client/shared/describeDocumentRef.ts b/packages/builtin-tool-agent-documents/src/client/shared/describeDocumentRef.tsnew file mode 100644index 00000000000..0b150c3eb30--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/shared/describeDocumentRef.ts@@ -0,0 +1,35 @@+export interface DocumentRefRow {+ documentId: string;+ fileType?: string | null;+ id: string;+ parentId?: string | null;+ title?: string | null;+}++export type DocumentRefLookup = (ref?: string | null) => DocumentRefRow | undefined;++export type DocumentRefView =+ | { kind: 'root' }+ | { kind: 'document' | 'folder'; title: string }+ | { id: string; kind: 'unknown' };++/**+ * How a tool-call id reads to the user: the root, a folder or document by its+ * title, or — when the id no longer resolves and no title came with the result —+ * an unknown id. Tool arguments carry either the row `id` or the `docs_…` id.+ */+export const describeDocumentRef = (+ lookup: DocumentRefLookup,+ ref?: string | null,+ fallbackTitle?: string,+): DocumentRefView => {+ if (!ref) return { kind: 'root' };+ const doc = lookup(ref);+ const title = doc?.title || fallbackTitle;+ if (!title) return { id: ref, kind: 'unknown' };+ return { kind: doc?.fileType === 'custom/folder' ? 'folder' : 'document', title };+};++/** Where a document sits now: its parent's view, the root when it has none. */+export const describeCurrentParent = (lookup: DocumentRefLookup, ref: string): DocumentRefView =>+ describeDocumentRef(lookup, lookup(ref)?.parentId ?? null);diff --git a/packages/builtin-tool-agent-documents/src/client/shared/styles.ts b/packages/builtin-tool-agent-documents/src/client/shared/styles.tsnew file mode 100644index 00000000000..7ce4a4bed47--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/shared/styles.ts@@ -0,0 +1,32 @@+import { createStaticStyles } from 'antd-style';++export const cardStyles = createStaticStyles(({ css, cssVar }) => ({+ arrow: css`+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ `,+ card: css`+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadius};+ background: ${cssVar.colorFillQuaternary};+ `,+ label: css`+ flex: none;+ min-width: 40px;+ color: ${cssVar.colorTextDescription};+ `,+ row: css`+ padding-block: 4px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadius};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ status: css`+ flex: none;+ font-size: 12px;+ `,+}));diff --git a/packages/builtin-tool-agent-documents/src/client/shared/useAgentDocumentLookup.ts b/packages/builtin-tool-agent-documents/src/client/shared/useAgentDocumentLookup.tsnew file mode 100644index 00000000000..752870b539c--- /dev/null+++ b/packages/builtin-tool-agent-documents/src/client/shared/useAgentDocumentLookup.ts@@ -0,0 +1,36 @@+import { useMemo } from 'react';++import { useClientDataSWR } from '@/libs/swr';+import {+ type AgentDocumentListItem,+ agentDocumentService,+ agentDocumentSWRKeys,+} from '@/services/agentDocument';+import { useAgentStore } from '@/store/agent';++export type AgentDocumentLookup = (ref?: string | null) => AgentDocumentListItem | undefined;++/**+ * Resolve the document ids a tool call carries (either the row `id` or the+ * `docs_…` documentId) to the rows the user knows by title. Reads the active+ * agent's document list under the sidebar's SWR key, so it adds no request+ * while the documents panel is mounted.+ */+export const useAgentDocumentLookup = (): { isLoading: boolean; lookup: AgentDocumentLookup } => {+ const agentId = useAgentStore((s) => s.activeAgentId);+ const { data, isLoading } = useClientDataSWR(+ agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,+ () => agentDocumentService.listDocuments({ agentId: agentId! }),+ );++ const lookup = useMemo<AgentDocumentLookup>(() => {+ const byRef = new Map<string, AgentDocumentListItem>();+ for (const doc of data ?? []) {+ byRef.set(doc.id, doc);+ byRef.set(doc.documentId, doc);+ }+ return (ref) => (ref ? byRef.get(ref) : undefined);+ }, [data]);++ return { isLoading, lookup };+};diff --git a/packages/builtin-tool-agent-documents/src/executor/index.test.ts b/packages/builtin-tool-agent-documents/src/executor/index.test.tsindex 91faeeec22b..3c69341a8aa 100644--- a/packages/builtin-tool-agent-documents/src/executor/index.test.ts+++ b/packages/builtin-tool-agent-documents/src/executor/index.test.ts@@ -31,7 +31,11 @@ describe('AgentDocumentsExecutor.onAfterCall', () => {expect(onDocumentsMutated).toHaveBeenCalledWith({ documentId: undefined });});+ // Folders and moves change what the sidebar tree shows; a tool_end for them+ // (client or server runtime) must refresh it without a reload.it.each([+ AgentDocumentsApiName.createFolder,+ AgentDocumentsApiName.moveDocuments,AgentDocumentsApiName.removeDocument,AgentDocumentsApiName.renameDocument,AgentDocumentsApiName.copyDocument,diff --git a/packages/builtin-tool-agent-documents/src/executor/index.ts b/packages/builtin-tool-agent-documents/src/executor/index.tsindex 87da941f7cd..cd58357d8b5 100644--- a/packages/builtin-tool-agent-documents/src/executor/index.ts+++ b/packages/builtin-tool-agent-documents/src/executor/index.ts@@ -11,8 +11,10 @@ import {AgentDocumentsIdentifier,type CopyDocumentArgs,type CreateDocumentArgs,+ type CreateFolderArgs,type ListDocumentsArgs,type ModifyDocumentNodesArgs,+ type MoveDocumentsArgs,type ReadDocumentArgs,type RemoveDocumentArgs,type RenameDocumentArgs,@@ -24,6 +26,8 @@ import {// visible title). Read-only calls are excluded — they don't alter the list.const LIST_MUTATING_APIS = new Set<string>([AgentDocumentsApiName.createDocument,+ AgentDocumentsApiName.createFolder,+ AgentDocumentsApiName.moveDocuments,AgentDocumentsApiName.removeDocument,AgentDocumentsApiName.renameDocument,AgentDocumentsApiName.copyDocument,@@ -165,6 +169,20 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp});};+ createFolder = async (+ params: CreateFolderArgs,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return this.runtime.createFolder(params, { agentId: ctx.agentId, scope: ctx.scope });+ };++ moveDocuments = async (+ params: MoveDocumentsArgs,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return this.runtime.moveDocuments(params, { agentId: ctx.agentId, scope: ctx.scope });+ };+renameDocument = async (params: RenameDocumentArgs,ctx: BuiltinToolContext,@@ -218,8 +236,12 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsApconst fallbackRuntime = new AgentDocumentsExecutionRuntime({copyDocument: async ({ agentId: _agentId }) => undefined,createDocument: async () => undefined,+ createFolder: async () => {+ throw new Error('Agent document folders are unavailable in this runtime.');+ },createTopicDocument: async () => undefined,listDocuments: async () => [],+ moveDocuments: async () => [],listTopicDocuments: async () => [],modifyNodes: async ({ agentId: _agentId }) => undefined,readDocument: async ({ agentId: _agentId }) => undefined,diff --git a/packages/builtin-tool-agent-documents/src/index.ts b/packages/builtin-tool-agent-documents/src/index.tsindex 54b9cb976c3..fc6afe4fe03 100644--- a/packages/builtin-tool-agent-documents/src/index.ts+++ b/packages/builtin-tool-agent-documents/src/index.ts@@ -10,12 +10,19 @@ export {type CopyDocumentState,type CreateDocumentArgs,type CreateDocumentState,+ type CreateFolderArgs,+ type CreateFolderState,type ListDocumentsArgs,type ListDocumentsState,+ type ListedAgentDocument,MAX_READ_DOCUMENT_CONTENT_CHARS,type ModifyDocumentNodesArgs,type ModifyDocumentNodesState,type ModifyDocumentOperation,+ MOVE_DOCUMENTS_MAX_IDS,+ type MoveDocumentResultItem,+ type MoveDocumentsArgs,+ type MoveDocumentsState,type ReadDocumentArgs,type ReadDocumentState,type RemoveDocumentArgs,diff --git a/packages/builtin-tool-agent-documents/src/manifest.ts b/packages/builtin-tool-agent-documents/src/manifest.tsindex a279ea84fac..b6ef19f1e9b 100644--- a/packages/builtin-tool-agent-documents/src/manifest.ts+++ b/packages/builtin-tool-agent-documents/src/manifest.ts@@ -6,6 +6,7 @@ import {AgentDocumentsIdentifier,LIST_DOCUMENTS_DEFAULT_LIMIT,LIST_DOCUMENTS_MAX_LIMIT,+ MOVE_DOCUMENTS_MAX_IDS,} from './types';const AGENT_DOCUMENT_ID_DESCRIPTION =@@ -32,7 +33,7 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {},parentId: {description:- 'Parent folder document ID. Use the "documentId" field returned for a folder by listDocuments. Omit to create at the root.',+ 'Parent to create the document under: a folder, or a document such as the workflow/SOP whose run this document records. Pass its "documentId" (or "id") from listDocuments or createFolder. Omit to create at the root. Fails if the parent does not exist.',type: 'string',},scope: {@@ -179,7 +180,8 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {},},{- description: 'Remove an existing agent document by ID (similar intent to rm/delete).',+ description:+ 'Remove an existing agent document or folder by ID (similar intent to rm). A document or folder with nested children is refused unless withChildren is true.',name: AgentDocumentsApiName.removeDocument,parameters: {properties: {@@ -187,6 +189,11 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {description: AGENT_DOCUMENT_ID_DESCRIPTION,type: 'string',},+ withChildren: {+ description:+ 'Also delete every document nested under it. Only set this when the user wants the children gone too; otherwise move them out first.',+ type: 'boolean',+ },},required: ['id'],type: 'object',@@ -243,7 +250,50 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {},{description:- "List agent documents (this agent's own notes/skills/structured docs). Use this to discover documents that are not auto-injected (e.g. web-crawled pages), to expand a folder collapsed in the agent_documents_index, or to resolve a title to a document ID. Do NOT use this to find the user's uploaded files (PDFs, images, general uploads) — those live in the resource library and are covered by the Knowledge Base tool's listFiles, not here.",+ 'Create a folder for organizing agent documents (similar intent to mkdir -p). Idempotent: if a folder with the same name already exists in that location it is returned instead of creating a duplicate, so it is safe to call on every scheduled run.',+ name: AgentDocumentsApiName.createFolder,+ parameters: {+ properties: {+ parentId: {+ description:+ 'Parent folder or document ("documentId" or "id" from listDocuments/createFolder). Omit to create at the root.',+ type: 'string',+ },+ title: {+ description: 'Folder name. Cannot contain "/" or "\\".',+ type: 'string',+ },+ },+ required: ['title'],+ type: 'object',+ },+ },+ {+ description: `Move documents and/or folders under a folder or a document, or back to the root (similar intent to mv). Accepts up to ${MOVE_DOCUMENTS_MAX_IDS} ids per call, so a whole set can be filed in one call. Titles, ids, content, history and load rules are kept. Each id is reported as moved, unchanged (already there) or failed with a reason; one failure does not stop the rest.`,+ name: AgentDocumentsApiName.moveDocuments,+ parameters: {+ properties: {+ ids: {+ description:+ 'Documents or folders to move: the "id" (or "documentId") of each entry from listDocuments.',+ items: { type: 'string' },+ maxItems: MOVE_DOCUMENTS_MAX_IDS,+ minItems: 1,+ type: 'array',+ },+ parentId: {+ description:+ 'Destination folder or document ("documentId" or "id" from listDocuments/createFolder). Pass null to move to the root.',+ type: ['string', 'null'],+ },+ },+ required: ['ids', 'parentId'],+ type: 'object',+ },+ },+ {+ description:+ "List agent documents (this agent's own notes/skills/structured docs). Use this to discover documents that are not auto-injected (e.g. web-crawled pages), to expand a folder collapsed in the agent_documents_index, or to resolve a title to a document ID. Each entry reports its type (file or folder), parentId (null at the root), childCount when something is nested under it (documents can hold children too) and updatedAt. Do NOT use this to find the user's uploaded files (PDFs, images, general uploads) — those live in the resource library and are covered by the Knowledge Base tool's listFiles, not here.",name: AgentDocumentsApiName.listDocuments,parameters: {properties: {@@ -258,7 +308,7 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {},parentId: {description:- 'Restrict the listing to the direct children of this folder. Pass the folder id shown on a collapsed 📁 row in the agent_documents_index to expand that folder.',+ 'Restrict the listing to the direct children of this parent — a folder or a document. Pass the id shown on a collapsed row in the agent_documents_index, or a "documentId"/"id" from a previous listing. Fails if the parent does not exist. Without parentId every document is listed, including nested ones; use each entry\'s "parentId" (null = root) to tell where it sits.',type: 'string',},scope: {@@ -274,6 +324,11 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {enum: ['all', 'file', 'web'],type: 'string',},+ titleContains: {+ description:+ 'Only list documents whose title contains this text (case-insensitive). Applied before paging, so it finds every match, e.g. all daily reports that share a title prefix.',+ type: 'string',+ },},required: [],type: 'object',@@ -315,7 +370,7 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {meta: {avatar: '🗂️',description:- "Manage agent-scoped documents (list/create/read/edit/remove/rename/copy/upsert) and load rules. Not for the user's uploaded files — use the Knowledge Base tool for those.",+ "Manage agent-scoped documents and folders (list/create/read/edit/remove/rename/copy/move, create folders) and load rules. Not for the user's uploaded files — use the Knowledge Base tool for those.",title: 'Documents',},systemRole: systemPrompt,diff --git a/packages/builtin-tool-agent-documents/src/systemRole.test.ts b/packages/builtin-tool-agent-documents/src/systemRole.test.tsindex 415eee6d065..72e02552019 100644--- a/packages/builtin-tool-agent-documents/src/systemRole.test.ts+++ b/packages/builtin-tool-agent-documents/src/systemRole.test.ts@@ -6,7 +6,7 @@ describe('systemPrompt', () => {it('should distinguish agent document ids from folder navigation ids', () => {expect(systemPrompt).toContain("For read and mutation calls, pass the result's `id`.");expect(systemPrompt).toContain(- "For folder navigation, pass the folder's `documentId` (or the ID shown in a collapsed folder row) as `listDocuments.parentId`.",+ "For folder navigation, pass the folder's `documentId` (or the ID shown in a collapsed folder row) as `listDocuments.parentId`; the same works for a document that has nested docs.",);});@@ -22,4 +22,17 @@ describe('systemPrompt', () => {);expect(systemPrompt).toContain('do not simply refuse');});++ it('should route document organization to folder APIs instead of a CLI', () => {+ expect(systemPrompt).toContain('8. Create folder (createFolder)');+ expect(systemPrompt).toContain('9. Move documents (moveDocuments)');+ expect(systemPrompt).toContain('Do not fall back to a CLI or sandbox for this.');+ expect(systemPrompt).toContain('createDocument(parentId=…) instead of the root');+ });++ it('should make documents the default parent for records produced by following them', () => {+ expect(systemPrompt).toContain('A **document** can be a parent.');+ expect(systemPrompt).toContain('a workflow/SOP document with its execution records');+ expect(systemPrompt).toContain('removeDocument refuses an entry that has children');+ });});diff --git a/packages/builtin-tool-agent-documents/src/systemRole.ts b/packages/builtin-tool-agent-documents/src/systemRole.tsindex ede58c0b1a2..fd9e066554d 100644--- a/packages/builtin-tool-agent-documents/src/systemRole.ts+++ b/packages/builtin-tool-agent-documents/src/systemRole.ts@@ -12,11 +12,31 @@ Only use listDocuments/readDocument when the user is asking about agent document3. Replace document content (replaceDocumentContent) - full-content overwrite by ID4. Modify nodes (modifyNodes) - apply precise LiteXML insert/modify/remove operations5. Remove document (removeDocument) - equivalent to rm/delete-6. Rename document (renameDocument) - equivalent to mv/rename+6. Rename document (renameDocument) - title only, equivalent to a same-folder mv7. Copy document (copyDocument) - equivalent to cp/copy-8. Update load rule (updateLoadRule) - modify how agent documents are loaded into context+8. Create folder (createFolder) - equivalent to mkdir -p+9. Move documents (moveDocuments) - equivalent to mv under a folder or a document; batch, up to 200 ids per call+10. List documents (listDocuments) - equivalent to ls; filter by folder or title text+11. Update load rule (updateLoadRule) - modify how agent documents are loaded into context</core_capabilities>+<ids>+Every entry has two ids: \`id\` (the agent-document uuid) and \`documentId\` (the \`docs_…\` id). Read/edit calls take \`id\`; parent parameters (\`parentId\`) are documented with \`documentId\`. Every parameter accepts either one, and an unknown parent id is an error rather than an empty result, so if a call reports "Parent not found", re-list instead of assuming the parent is empty.+</ids>++<hierarchy>+Documents form a tree, and two kinds of entry can hold children:+- A **document** can be a parent. Nest records under the document they belong to — a workflow/SOP document with its execution records, a spec with its revisions — so the procedure and its runs read as one unit. This is the default for anything produced by following a document.+- A **folder** only groups. Use one when there is no natural parent document (e.g. a set of daily reports that no single document describes).++Working with the tree:+- listDocuments entries carry \`type\` ("file" | "folder"), \`parentId\` (null = at the root), \`childCount\` (present when something is nested under the entry — documents included) and \`updatedAt\`. Without \`parentId\` the listing is flat and includes nested entries; pass \`parentId\` (a folder or a document) to list its direct children.+- Organizing existing documents: (1) listDocuments with \`titleContains\` to find every match (it filters before paging; follow the paging note if one is shown), (2) pick the parent — the document they belong to, or createFolder (reuses an existing folder of the same name) when there is none, (3) one moveDocuments call with all the ids, (4) report moved / unchanged / failed counts from its result. Do not fall back to a CLI or sandbox for this.+- Recurring output (scheduled tasks, daily or weekly reports, run logs): file each new document directly under its parent with createDocument(parentId=…) instead of the root. When setting up such a task, record the parent's id (the workflow document it follows, or a folder) in the task instructions so every run writes there.+- moveDocuments keeps titles, ids, content, history and load rules. It refuses to move an entry under itself or one of its descendants, to overwrite a same-named entry at the destination, and to move skill documents. Skills and web clips cannot be parents.+- removeDocument refuses an entry that has children; move them out first, or pass withChildren: true only when the user wants them deleted too.+</hierarchy>+<workflow>1. Understand the exact document operation intent.2. Select the correct API based on the requested action.@@ -27,16 +47,18 @@ Only use listDocuments/readDocument when the user is asking about agent document<tool_selection_guidelines>- By default, if the user does not explicitly specify otherwise, and the relevant Agent Documents tool is available for the task, prefer Agent Documents over Cloud Sandbox because it is easier for collaboration and multi-agent coordination.-- **createDocument**: create a new document with title + content. To create it inside a folder, pass that folder's \`documentId\` from listDocuments as \`parentId\`; omit parentId to create at the root. Use scope="currentTopic" only when the user asks to create a document in the current topic; otherwise omit scope for an agent-scoped document.+- **createDocument**: create a new document with title + content. To nest it, pass the parent's \`documentId\` (a document such as the workflow it records, or a folder) as \`parentId\`; omit parentId to create at the root. Recurring outputs belong under their parent, not the root. Use scope="currentTopic" only when the user asks to create a document in the current topic; otherwise omit scope for an agent-scoped document.- Set hintIsSkill=true only when creating a document that contains reusable procedural knowledge, workflow instructions, tool usage guidance, or durable agent behavior. Leave ordinary notes unhinted.- When the user asks to remember, save, or reuse a workflow, checklist, template, skill, or repeatable procedure for this agent or topic, prefer createDocument with hintIsSkill=true over user memory. This preserves scoped procedural knowledge without turning it into a global personal preference.- Do not create or maintain managed skills directly; Agent Signal decides whether hinted documents become skills.-- **listDocuments**: list agent documents. Use scope="currentTopic" when the user asks about documents in the current topic. The default agent_documents_index hides web-crawled documents; pass sourceType="web" here to enumerate them, or sourceType="all" to see everything. The index also collapses folders into a single 📁 row — pass parentId=<folder id from that row> to expand a folder and see its documents. Use this to resolve a title to a document ID before reading. For read and mutation calls, pass the result's \`id\`. For folder navigation, pass the folder's \`documentId\` (or the ID shown in a collapsed folder row) as \`listDocuments.parentId\`.+- **listDocuments**: list agent documents. Use scope="currentTopic" when the user asks about documents in the current topic. The default agent_documents_index hides web-crawled documents; pass sourceType="web" here to enumerate them, or sourceType="all" to see everything. The index also collapses folders into a single 📁 row, and the docs nested under a document into a single 📄 row — pass parentId=<id from that row> to expand it. Use this to resolve a title to a document ID before reading. For read and mutation calls, pass the result's \`id\`. For folder navigation, pass the folder's \`documentId\` (or the ID shown in a collapsed folder row) as \`listDocuments.parentId\`; the same works for a document that has nested docs.- **readDocument**: retrieve current content by agent document ID. Pass the \`id\` field returned by listDocuments, not \`documentId\`. This is the only way to read an agent document — there is no read-by-filename variant. Prefer format="xml" when you may edit content, because XML includes stable node IDs. If the response contains empty content, the document is genuinely empty; do not retry with a different format or filename.- **modifyNodes**: preferred content-edit API. Use LiteXML insert/modify/remove operations after reading XML. For modify operations, include the existing node ID in the LiteXML and keep its tag (a <span> id stays a <span>, an <li> id stays an <li>). A modify gives the replaced node a new id and inserts create new nodes; every other node keeps its id, so readDocument again only when you need to address a node you just replaced or inserted.- **replaceDocumentContent**: overwrite the full content of an existing document only when replacing most or all content.-- **removeDocument**: permanently remove a document by ID.+- **removeDocument**: remove a document or folder by ID. Refused when it has children unless withChildren is true.- **renameDocument**: change document title only.+- **createFolder**: create a folder by name, optionally inside another folder. Safe to call repeatedly; an existing folder with the same name is reused.+- **moveDocuments**: move documents and folders under a folder or a document (\`parentId\`), or back to the root (\`parentId: null\`). Pass every id in one call rather than one call per document.- **copyDocument**: duplicate a document, optionally with a new title.- **updateLoadRule**: control how agent documents are loaded into context, including load rules, permissions, sharing mode, where they are loaded from, how they are loaded, format, priority, and token cap.</tool_selection_guidelines>diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.tsindex 2d0ceeeae7b..18b39e38da8 100644--- a/packages/builtin-tool-agent-documents/src/types.ts+++ b/packages/builtin-tool-agent-documents/src/types.ts@@ -14,9 +14,11 @@ export const MAX_READ_DOCUMENT_CONTENT_CHARS = 200_000;export const AgentDocumentsApiName = {createDocument: 'createDocument',+ createFolder: 'createFolder',copyDocument: 'copyDocument',listDocuments: 'listDocuments',modifyNodes: 'modifyNodes',+ moveDocuments: 'moveDocuments',readDocument: 'readDocument',removeDocument: 'removeDocument',renameDocument: 'renameDocument',@@ -40,7 +42,7 @@ export const AGENT_SHARE_DOCUMENT_API_NAMES = new Set<string>([export interface CreateDocumentArgs {content: string;hintIsSkill?: boolean;- /** Parent folder's underlying `documents.id`, as returned by listDocuments.documentId. */+ /** Parent folder or document — its `documentId` (or `id`) from listDocuments. */parentId?: string;scope?: 'agent' | 'currentTopic';title: string;@@ -137,6 +139,8 @@ export interface ModifyDocumentNodesState {export interface RemoveDocumentArgs {id: string;+ /** Also delete everything nested under it. Without it, a parent with children is refused. */+ withChildren?: boolean;}export interface RemoveDocumentState {@@ -223,18 +227,60 @@ export interface AgentDocumentReference {}export interface ListDocumentsArgs {- /**- * Restrict the listing to the direct children of this folder document- * (the folder's `documentId`). The progressive index collapses folders and- * surfaces this id so the model can expand a folder on demand.- *//** Page size; defaults to {@link LIST_DOCUMENTS_DEFAULT_LIMIT}. */limit?: number;/** Number of documents to skip, for paging past the first page. */offset?: number;+ /**+ * Restrict the listing to the direct children of this parent — a folder or a+ * document. Either id works; the progressive index surfaces its `documentId`.+ */parentId?: string;scope?: 'agent' | 'currentTopic';sourceType?: 'all' | 'file' | 'web';+ /** Case-insensitive substring filter on the title, applied before paging. */+ titleContains?: string;+}++export interface CreateFolderArgs {+ /** Parent folder or document (either id); omit to create at the root. */+ parentId?: string;+ title: string;+}++export interface CreateFolderState {+ agentDocumentId?: string;+ agentId?: string;+ /** False when a folder with this name already existed and was reused. */+ created: boolean;+ documentId?: string;+ title: string;+}++/** Upper bound on ids per moveDocuments call. */+export const MOVE_DOCUMENTS_MAX_IDS = 200;++export interface MoveDocumentsArgs {+ /** Documents or folders to move; either id of each works. */+ ids: string[];+ /** Destination folder or document (either id), or null to move to the root. */+ parentId: string | null;+}++export interface MoveDocumentResultItem {+ documentId?: string;+ error?: string;+ id: string;+ status: 'failed' | 'moved' | 'unchanged';+ title?: string;+}++export interface MoveDocumentsState {+ agentId?: string;+ failedCount: number;+ movedCount: number;+ parentId: string | null;+ results: MoveDocumentResultItem[];}/**@@ -251,5 +297,19 @@ export interface ListDocumentsState {* and a count is all it shows.*/documentCount?: number;- documents: { documentId?: string; filename: string; id: string; title?: string }[];+ documents: ListedAgentDocument[];+}++export interface ListedAgentDocument {+ /** Entries nested directly under this one; documents can hold children too. */+ childCount?: number;+ documentId?: string;+ filename: string;+ id: string;+ /** `documentId` of the folder or document this entry sits under; null at the root. */+ parentId?: string | null;+ title?: string;+ type?: 'file' | 'folder';+ /** ISO timestamp of the last change. */+ updatedAt?: string;}diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.tsindex 916b35dbb2f..b7a52fea8f2 100644--- a/packages/builtin-tools/src/register.ts+++ b/packages/builtin-tools/src/register.ts@@ -12,6 +12,7 @@ import {} from '@lobechat/builtin-tool-agent-builder/client';import {AgentDocumentsInspectors,+ AgentDocumentsInterventions,AgentDocumentsManifest,AgentDocumentsRenders,AgentDocumentsStreamings,@@ -416,6 +417,10 @@ export const registerBuiltinToolSurfaces = (): void => {string,BuiltinIntervention>,+ [AgentDocumentsManifest.identifier]: AgentDocumentsInterventions as Record<+ string,+ BuiltinIntervention+ >,[ClaudeCodeIdentifier]: ClaudeCodeInterventions as Record<string, BuiltinIntervention>,[DROID_IDENTIFIER]: {[ClaudeCodeApiName.AskUserQuestion]:diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.tsindex e1d5335cc76..919b3c47379 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts@@ -33,10 +33,10 @@ export interface AgentContextDocument {description?: string;filename: string;/**- * Title of the containing `custom/folder` document, resolved at the- * DB→context mapping boundary (folder rows themselves never reach the- * injector). Present only when the doc lives in a folder; used by the- * progressive index to fold same-folder siblings into one summary row.+ * Title of the containing parent — a `custom/folder`, or an ordinary document+ * that holds nested docs (e.g. a workflow with its run records) — resolved at+ * the DB→context mapping boundary. Present only when the doc has such a+ * parent; used by the progressive index to fold siblings into one summary row.*/folderTitle?: string;id?: string;@@ -48,6 +48,8 @@ export interface AgentContextDocument {* model passes to `listDocuments(parentId=…)` to expand a folded folder.*/parentId?: string | null;+ /** What `parentId` points at; `document` parents fold under a 📄 row instead of 📁. */+ parentKind?: 'document' | 'folder';policyId?: string | null;policyLoad?: AgentDocumentPolicyLoad;policyLoadFormat?: AgentDocumentLoadFormat;@@ -255,9 +257,11 @@ function buildIndexTable(}const FOLDER_ICON = '📁';+const PARENT_DOCUMENT_ICON = '📄';interface FolderGroup {docs: AgentContextDocument[];+ kind: 'document' | 'folder';parentId: string;title: string;}@@ -295,8 +299,14 @@ function partitionFolders(docs: AgentContextDocument[]): {const folders: FolderGroup[] = [];for (const [parentId, group] of byParent) {- if (group.length >= 2) folders.push({ docs: group, parentId, title: group[0].folderTitle! });- else flat.push(...group);+ if (group.length >= 2) {+ folders.push({+ docs: group,+ kind: group[0].parentKind ?? 'folder',+ parentId,+ title: group[0].folderTitle!,+ });+ } else flat.push(...group);}return { flat, folders };}@@ -334,7 +344,7 @@ function buildFolderTable(folders: FolderGroup[], context: AgentDocumentFilterCof.docs.filter((doc) => isNewSinceUserMessage(doc, context)).length,),time: newestTime(f.docs),- title: `${FOLDER_ICON} ${truncate(f.title, TITLE_MAX_WIDTH)}`,+ title: `${f.kind === 'document' ? PARENT_DOCUMENT_ICON : FOLDER_ICON} ${truncate(f.title, TITLE_MAX_WIDTH)}`,})).sort((a, b) => b.time - a.time);@@ -418,9 +428,16 @@ export function combineDocuments(`Docs marked ${NEW_SINCE_USER_MESSAGE_MARK} (or counted that way in a folder row) were created after the user's latest message — by you or elsewhere (another topic, or the user). A marked doc you created was new; creating it did not overwrite an existing doc.`,);}- if (folders.length > 0) {+ const folderCount = folders.filter((f) => f.kind === 'folder').length;+ const parentDocCount = folders.length - folderCount;+ if (folderCount > 0) {headerLines.push(- `${folders.length} folder${folders.length === 1 ? '' : 's'} collapsed (${FOLDER_ICON}) — call listDocuments(parentId=<id>) to list a folder's docs.`,+ `${folderCount} folder${folderCount === 1 ? '' : 's'} collapsed (${FOLDER_ICON}) — call listDocuments(parentId=<id>) to list a folder's docs.`,+ );+ }+ if (parentDocCount > 0) {+ headerLines.push(+ `${parentDocCount} document${parentDocCount === 1 ? '' : 's'} with nested docs collapsed (${PARENT_DOCUMENT_ICON}, e.g. a workflow and its run records) — the parent itself is listed by title; call listDocuments(parentId=<id>) to list what is nested under it.`,);}diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.tsindex b091bc8e59f..9671e5d4cc5 100644--- a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts@@ -304,6 +304,37 @@ describe('AgentDocumentInjector', () => {expect(content).toMatch(/📁 Reports\s+folder-1\s+2 docs \(1 new since last user message\)/);});+ it('folds the docs nested under a document into a 📄 row', async () => {+ const run = (id: string, updatedAt: string) => ({+ filename: `${id}.md`,+ folderTitle: 'Fix-round SOP',+ id,+ loadPosition: 'before-first-user' as const,+ loadRules: { rule: 'always' as const },+ parentId: 'docs_sop',+ parentKind: 'document' as const,+ policyLoad: 'progressive' as const,+ title: id,+ updatedAt: new Date(updatedAt),+ });+ const provider = new AgentDocumentContextInjector({+ documents: [+ run('tick-1', '2026-10-10T05:10:00.000Z'),+ run('tick-2', '2026-10-11T05:10:00.000Z'),+ ],+ });++ const result = await provider.process(+ createContext([{ content: 'go', id: 'user-1', role: 'user' }]),+ );+ const content = result.messages[0].content as string;++ expect(content).toMatch(/📄 Fix-round SOP\s+docs_sop\s+2 docs/);+ expect(content).toContain('1 document with nested docs collapsed (📄');+ expect(content).not.toContain('folder collapsed');+ expect(content).not.toContain('tick-1');+ });+// The document query is agent-scoped, so a doc created after the latest// user message may come from another topic or tab: the marker must state the// known timestamp fact instead of claiming the current run created it.diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.tsindex e1dece1b0e2..61968ace5ff 100644--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts@@ -719,6 +719,48 @@ describe('AgentDocumentModel', () => {expect(doc?.source).toBe(`agent-document://${agentId}/${encodeURIComponent('new.md')}`);});+ it('should count live children per parent, for documents as well as folders', async () => {+ const folder = await agentDocumentModel.create(agentId, 'count-folder', '', {+ fileType: DOCUMENT_FOLDER_TYPE,+ title: 'count-folder',+ });+ const sop = await agentDocumentModel.create(agentId, 'sop', 'steps');+ await agentDocumentModel.create(agentId, 'in-folder', 'a', { parentId: folder.documentId });+ await agentDocumentModel.create(agentId, 'run-1', 'b', { parentId: sop.documentId });+ const run2 = await agentDocumentModel.create(agentId, 'run-2', 'c', {+ parentId: sop.documentId,+ });+ await agentDocumentModel.delete(run2.id);++ const all = await agentDocumentModel.countChildrenByParentIds(agentId);+ const scoped = await agentDocumentModel.countChildrenByParentIds(agentId, [sop.documentId]);++ expect(all.get(folder.documentId)).toBe(1);+ expect(all.get(sop.documentId)).toBe(1);+ expect([...scoped.entries()]).toEqual([[sop.documentId, 1]]);+ expect((await agentDocumentModel.countChildrenByParentIds(agentId, [])).size).toBe(0);+ });++ it('should keep the title when a move passes it explicitly', async () => {+ const folder = await agentDocumentModel.create(agentId, 'keep-title-folder', '', {+ fileType: DOCUMENT_FOLDER_TYPE,+ title: 'keep-title-folder',+ });+ const created = await agentDocumentModel.create(agentId, 'daily-report', 'body', {+ title: 'Daily Report — 2026/10/10',+ });++ const moved = await agentDocumentModel.movePath(created.id, {+ filename: created.filename,+ parentId: folder.documentId,+ title: created.title,+ });++ expect(moved?.parentId).toBe(folder.documentId);+ expect(moved?.filename).toBe('daily-report');+ expect(moved?.title).toBe('Daily Report — 2026/10/10');+ });+it('should allow moving a document over an existing live sibling filename', async () => {const folder = await agentDocumentModel.create(agentId, 'move-folder', '', {fileType: DOCUMENT_FOLDER_TYPE,diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex 343e67bcb1e..eb080541846 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -333,6 +333,37 @@ export class AgentDocumentModel {return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));}+ /**+ * Counts live children per parent `documentId`, for listings that show which+ * entries (folders or documents) have something nested under them. Omit+ * `parentIds` to count every parent of the agent in one grouped query.+ * Parents without children are absent from the map.+ */+ async countChildrenByParentIds(+ agentId: string,+ parentIds?: string[],+ ): Promise<Map<string, number>> {+ if (parentIds?.length === 0) return new Map();++ const rows = await this.db+ .select({ count: sql<number>`count(*)::int`, parentId: documents.parentId })+ .from(agentDocuments)+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))+ .where(+ and(+ this.agentDocOwnership(),+ eq(agentDocuments.agentId, agentId),+ parentIds ? inArray(documents.parentId, parentIds) : isNotNull(documents.parentId),+ isNull(agentDocuments.deletedAt),+ ),+ )+ .groupBy(documents.parentId);++ return new Map(+ rows.flatMap((row) => (row.parentId ? [[row.parentId, Number(row.count)] as const] : [])),+ );+ }+/*** Associates an existing document row with an agent document binding.*@@ -909,6 +940,8 @@ export class AgentDocumentModel {* - `filename` is already validated as a single VFS path segment* - `parentId` points to a document row owned by the same user, or `null` for root* - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately+ * - `title` defaults to `filename` (path-style rename); id-based moves pass the current title+ * so relocating a document never rewrites what the user sees** Returns:* - The same agent document binding after the backing document row is moved@@ -916,7 +949,7 @@ export class AgentDocumentModel {*/async movePath(documentId: string,- params: { filename: string; parentId: string | null },+ params: { filename: string; parentId: string | null; title?: string },): Promise<AgentDocument | undefined> {const existing = await this.findById(documentId);if (!existing) return undefined;@@ -933,7 +966,7 @@ export class AgentDocumentModel {filename,parentId: params.parentId,source,- title: filename,+ title: params.title ?? filename,}).where(and(eq(documents.id, existing.documentId), this.documentOwnership()));});diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex a0410f74bda..3d6765b2332 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2998,6 +2998,7 @@ export default {'workflow.toolDisplayName.crawlSinglePage': 'Crawled a page','workflow.toolDisplayName.createAgent': 'Created an agent','workflow.toolDisplayName.createDocument': 'Created a document',+ 'workflow.toolDisplayName.createFolder': 'Created a folder','workflow.toolDisplayName.createPlan': 'Created a plan','workflow.toolDisplayName.createTodos': 'Created todos','workflow.toolDisplayName.deleteAgent': 'Deleted an agent',@@ -3024,6 +3025,7 @@ export default {'workflow.toolDisplayName.listLocalFiles': 'Listed files','workflow.toolDisplayName.listOnlineDevices': 'Listed devices','workflow.toolDisplayName.modifyNodes': 'Modified Page',+ 'workflow.toolDisplayName.moveDocuments': 'Moved documents','workflow.toolDisplayName.moveLocalFiles': 'Moved files','workflow.toolDisplayName.readDocument': 'Read a document','workflow.toolDisplayName.readKnowledge': 'Read knowledge',@@ -3182,6 +3184,7 @@ export default {'workingPanel.resources.tree.parentMissing': 'Parent folder is unavailable','workingPanel.resources.tree.create': 'Create','workingPanel.resources.tree.newDocument': 'New document',+ 'workingPanel.resources.tree.newSubDocument': 'New sub-document','workingPanel.resources.tree.newFolder': 'New folder','workingPanel.resources.tree.rename': 'Rename','workingPanel.resources.tree.untitledDocument': 'Untitled document',diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 16fecdd96d1..1337b5fe3f2 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -433,15 +433,29 @@ export default {'builtins.lobe-local-system.title': 'Local System','builtins.lobe-agent-documents.apiName.copyDocument': 'Copy document','builtins.lobe-agent-documents.apiName.createDocument': 'Create document',+ 'builtins.lobe-agent-documents.apiName.createFolder': 'Create folder','builtins.lobe-agent-documents.apiName.listDocuments': 'List documents','builtins.lobe-agent-documents.apiName.modifyNodes': 'Modify document',+ 'builtins.lobe-agent-documents.apiName.moveDocuments': 'Move documents','builtins.lobe-agent-documents.apiName.readDocument': 'Read document','builtins.lobe-agent-documents.apiName.removeDocument': 'Remove document','builtins.lobe-agent-documents.apiName.renameDocument': 'Rename document','builtins.lobe-agent-documents.apiName.replaceDocumentContent': 'Replace document content','builtins.lobe-agent-documents.apiName.updateLoadRule': 'Update load rule',+ 'builtins.lobe-agent-documents.createFolder.created': 'Created',+ 'builtins.lobe-agent-documents.createFolder.reused': 'Already existed, reused',+ 'builtins.lobe-agent-documents.moveDocuments.destination': 'Move to',+ 'builtins.lobe-agent-documents.moveDocuments.from': 'From {{parent}}',+ 'builtins.lobe-agent-documents.moveDocuments.itemsToMove': '{{count}} item(s) to move',+ 'builtins.lobe-agent-documents.moveDocuments.status.failed': 'Failed',+ 'builtins.lobe-agent-documents.moveDocuments.status.moved': 'Moved',+ 'builtins.lobe-agent-documents.moveDocuments.status.unchanged': 'Already there',+ 'builtins.lobe-agent-documents.ref.location': 'Location',+ 'builtins.lobe-agent-documents.ref.root': 'Root',+ 'builtins.lobe-agent-documents.ref.unknown': 'Unknown document {{id}}','builtins.lobe-agent-documents.inspector.chars': '{{count}} chars','builtins.lobe-agent-documents.inspector.docCount': '{{count}} docs',+ 'builtins.lobe-agent-documents.inspector.failedCount': '{{count}} failed','builtins.lobe-agent-documents.inspector.opsCount': '{{count}} ops','builtins.lobe-agent-documents.inspector.opsResult': '{{success}}/{{total}} ops','builtins.lobe-agent-documents.inspector.scope.agent': 'in agent',diff --git a/packages/prompts/src/prompts/agentDocuments/formatResults.test.ts b/packages/prompts/src/prompts/agentDocuments/formatResults.test.tsindex 18f45deadd9..dc1b9c41082 100644--- a/packages/prompts/src/prompts/agentDocuments/formatResults.test.ts+++ b/packages/prompts/src/prompts/agentDocuments/formatResults.test.ts@@ -3,7 +3,9 @@ import { describe, expect, it } from 'vitest';import {formatCopyDocumentResult,formatCreateDocumentResult,+ formatCreateFolderResult,formatModifyDocumentResult,+ formatMoveDocumentsResult,formatRemoveDocumentResult,formatRenameDocumentResult,formatReplaceDocumentResult,@@ -70,4 +72,29 @@ describe('agentDocuments formatResults', () => {it('reports removal with only the id (no live url to share)', () => {expect(formatRemoveDocumentResult({ id: 'assoc-id' })).toBe('Removed document assoc-id.');});++ describe('folder results', () => {+ it('hands back the folder id for parentId and marks reuse', () => {+ expect(formatCreateFolderResult({ created: true, folderId: 'docs_f', title: 'P95' })).toBe(+ 'Created folder "P95" (folder id: docs_f). Pass this id as parentId to createDocument, moveDocuments or listDocuments. It is an internal handle; never show it to the user.',+ );+ expect(+ formatCreateFolderResult({ created: false, folderId: 'docs_f', title: 'P95' }),+ ).toMatch(/^Reused existing folder "P95"/);+ });++ it('summarizes a move and lists only the failures', () => {+ expect(+ formatMoveDocumentsResult({+ parentId: null,+ results: [+ { id: 'a', status: 'moved', title: 'A' },+ { error: 'Skill documents cannot be moved.', id: 'b', status: 'failed', title: 'B' },+ ],+ }),+ ).toBe(+ 'Moved 1 item(s) to the root; 0 already there; 1 failed.\nFailed:\n- "B" (b): Skill documents cannot be moved.',+ );+ });+ });});diff --git a/packages/prompts/src/prompts/agentDocuments/formatResults.ts b/packages/prompts/src/prompts/agentDocuments/formatResults.tsindex dfea0ad7d4c..257acbfad1d 100644--- a/packages/prompts/src/prompts/agentDocuments/formatResults.ts+++ b/packages/prompts/src/prompts/agentDocuments/formatResults.ts@@ -92,3 +92,47 @@ export const formatUpdateLoadRuleResult = ({/** A removed document has no live url to share, so only the id is reported. */export const formatRemoveDocumentResult = ({ id }: { id: string }): string =>`Removed document ${id}.`;++export interface FormatCreateFolderResultParams {+ /** False when an existing folder with the same name was reused. */+ created: boolean;+ /** The folder's `documents` id — what createDocument / moveDocuments take as `parentId`. */+ folderId: string;+ title: string;+}++export const formatCreateFolderResult = ({+ created,+ folderId,+ title,+}: FormatCreateFolderResultParams): string =>+ `${created ? 'Created' : 'Reused existing'} folder "${title}" (folder id: ${folderId}). ` ++ 'Pass this id as parentId to createDocument, moveDocuments or listDocuments. ' ++ 'It is an internal handle; never show it to the user.';++export interface FormatMoveDocumentsResultParams {+ /** Destination folder id, or null for the root. */+ parentId: string | null;+ results: Array<{+ error?: string;+ id: string;+ status: 'failed' | 'moved' | 'unchanged';+ title?: string;+ }>;+}++export const formatMoveDocumentsResult = ({+ parentId,+ results,+}: FormatMoveDocumentsResultParams): string => {+ const count = (status: string) => results.filter((r) => r.status === status).length;+ const destination = parentId ? `folder ${parentId}` : 'the root';+ const summary =+ `Moved ${count('moved')} item(s) to ${destination}; ` ++ `${count('unchanged')} already there; ${count('failed')} failed.`;+ const failures = results+ .filter((r) => r.status === 'failed')+ .map((r) => `- ${r.title ? `"${r.title}" (${r.id})` : r.id}: ${r.error ?? 'unknown error'}`);++ return failures.length > 0 ? `${summary}\nFailed:\n${failures.join('\n')}` : summary;+};diff --git a/src/features/AgentDocumentPage/Header/useMenu.tsx b/src/features/AgentDocumentPage/Header/useMenu.tsxindex bf61cc360de..91a7b7cfe76 100644--- a/src/features/AgentDocumentPage/Header/useMenu.tsx+++ b/src/features/AgentDocumentPage/Header/useMenu.tsx@@ -97,7 +97,13 @@ export const useMenu = ({okText: t('delete', { ns: 'common' }),onOk: async () => {try {- await agentDocumentService.removeDocument({ agentId, documentId, id: agentDocumentId });+ await agentDocumentService.removeDocument({+ agentId,+ documentId,+ id: agentDocumentId,+ // Documents nested under it go with it, as a folder's contents do.+ withChildren: true,+ });toast.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));onDeleted();} catch (error) {diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsxindex 103f4050d90..2d9dd56caf4 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx@@ -7,7 +7,8 @@ import { useTranslation } from 'react-i18next';const styles = createStaticStyles(({ css, cssVar }) => ({toolbar: css`- margin-inline: 6px;+ /* Title on the column of the panel tabs' icons; the + stays on the row edge. */+ padding-inline-start: 6px;color: ${cssVar.colorTextSecondary};`,title: css`diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsxindex 1efbabbb47b..b3728f14f81 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx@@ -10,6 +10,7 @@ import { MemoryRouter } from 'react-router';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ExplorerTreeNode } from '@/features/ExplorerTree';+import type * as EventPathModule from '@/features/ExplorerTree/view/eventPath';import DocumentExplorerTree from './DocumentExplorerTree';import type { AgentDocumentItem } from './types';@@ -78,7 +79,11 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({useWorkspaceAwareNavigate: () => navigateMock,}));-vi.mock('@/features/ExplorerTree', () => {+vi.mock('@/features/ExplorerTree', async () => {+ const { isItemToggleEventPath } = await vi.importActual<typeof EventPathModule>(+ '@/features/ExplorerTree/view/eventPath',+ );+interface MockExplorerTreeProps {canDrag?: (node: ExplorerTreeNode<unknown>) => boolean;defaultExpandedIds?: string[];@@ -109,6 +114,7 @@ vi.mock('@/features/ExplorerTree', () => {const menuItems = (getContextMenuItems?.(node) ?? []) as MockMenuItem[];return (<div+ data-appearance={node.appearance ?? 'default'}data-can-drag={String(canDrag?.(node) ?? true)}data-folder={String(!!node.isFolder)}data-menu-count={String(menuItems.length)}@@ -119,6 +125,14 @@ vi.mock('@/features/ExplorerTree', () => {data-testid={`tree-node-button-${node.id}`}onClick={(event) => onNodeClick?.(node, event)}>+ <span+ data-item-section="icon"+ data-testid={`tree-node-toggle-${node.id}`}+ onClick={(event) => {+ event.stopPropagation();+ onNodeClick?.(node, event);+ }}+ />{node.name}</button>{node.isFolder && (@@ -154,6 +168,8 @@ vi.mock('@/features/ExplorerTree', () => {DISABLE_ROW_TEXT_SELECTION_CSS: '',DOCUMENT_TREE_ROW_CSS: '',DOCUMENT_TREE_ICON_CSS: '',+ DOCUMENT_TREE_PARENT_DOCUMENT_GLYPH_CSS: '',+ isItemToggleEventPath,DOCUMENT_TREE_LAYOUT: {fontSize: 14,iconGap: 8,@@ -240,6 +256,69 @@ describe('DocumentExplorerTree', () => {);});+ // A workflow document holding its run records must stay expandable in the+ // tree; before, nested children of a document were dropped from the panel.+ it('shows the documents nested under a document and still opens the parent', () => {+ const data = [+ createDocument({+ documentId: 'sop-doc',+ filename: 'Fix-round SOP',+ id: 'sop-row',+ title: 'Fix-round SOP',+ }),+ createDocument({+ documentId: 'run-doc',+ filename: 'Run 1',+ id: 'run-row',+ parentId: 'sop-doc',+ title: 'Run 1',+ }),+ ];+ const onOpenDocument = vi.fn();++ render(+ <DocumentExplorerTree+ agentId="agent-1"+ data={data}+ mutate={vi.fn()}+ onOpenDocument={onOpenDocument}+ />,+ { wrapper: MemoryRouter },+ );++ const parent = screen.getByTestId('tree-node-sop-row');+ expect(parent).toHaveAttribute('data-folder', 'true');+ expect(parent).toHaveAttribute('data-appearance', 'file');+ expect(+ within(screen.getByTestId('tree-node-children-sop-row')).getByTestId('tree-node-run-row'),+ ).toBeInTheDocument();+ expect(screen.getByTestId('tree-node-run-row')).toHaveAttribute('data-appearance', 'default');++ // The chevron only expands or collapses; the title opens the document.+ fireEvent.click(screen.getByTestId('tree-node-toggle-sop-row'));+ expect(onOpenDocument).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId('tree-node-button-sop-row'));+ expect(onOpenDocument).toHaveBeenCalledWith('sop-doc', 'sop-row');++ // Still a document: it can be opened as a page and gain more sub-documents,+ // but does not grow the folder-only entries.+ expect(screen.getByTestId('tree-menu-sop-row-open-as-page')).toBeInTheDocument();+ expect(screen.getByTestId('tree-menu-sop-row-new-sub-document')).toBeInTheDocument();+ expect(screen.queryByTestId('tree-menu-sop-row-new-folder')).not.toBeInTheDocument();+ });++ it('offers a sub-document entry on a plain document', () => {+ render(+ <DocumentExplorerTree agentId="agent-1" data={[createDocument({})]} mutate={vi.fn()} />,+ { wrapper: MemoryRouter },+ );++ expect(screen.getByTestId('tree-node-agent-doc-1')).toHaveAttribute('data-folder', 'false');+ expect(screen.getByTestId('tree-menu-agent-doc-1-new-sub-document')).toBeInTheDocument();+ // A folder can be nested under a document too, e.g. to group a workflow's runs.+ expect(screen.getByTestId('tree-menu-agent-doc-1-new-sub-folder')).toBeInTheDocument();+ });+it('offers upload on a folder context menu', () => {const data = [createDocument({@@ -445,6 +524,7 @@ describe('DocumentExplorerTree', () => {documentId: 'skill-bundle-doc',id: 'skill-bundle-row',topicId: undefined,+ withChildren: true,});});expect(messageSuccess).not.toHaveBeenCalled();diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex f11986a0b0a..cb83df9eec3 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -2,8 +2,16 @@ import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';import { createStaticStyles } from 'antd-style';-import { FileTextIcon, Maximize2Icon, PenLineIcon, Trash2Icon } from 'lucide-react';-import type { ChangeEvent, CSSProperties } from 'react';+import {+ FilePlusIcon,+ FileTextIcon,+ FileUpIcon,+ FolderPlusIcon,+ Maximize2Icon,+ PenLineIcon,+ Trash2Icon,+} from 'lucide-react';+import type { ChangeEvent, CSSProperties, MouseEvent } from 'react';import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import type { KeyedMutator } from 'swr';@@ -18,10 +26,12 @@ import {DISABLE_ROW_TEXT_SELECTION_CSS,DOCUMENT_TREE_ICON_CSS,DOCUMENT_TREE_LAYOUT,+ DOCUMENT_TREE_PARENT_DOCUMENT_GLYPH_CSS,DOCUMENT_TREE_ROW_CSS,ExplorerTree,getExplorerTreeStyleVars,HIDE_POINTER_FOCUS_RING_CSS,+ isItemToggleEventPath,} from '@/features/ExplorerTree';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import type { NativeContextMenuItem } from '@/libs/contextMenu/types';@@ -84,9 +94,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({--trees-font-size-override: ${DOCUMENT_TREE_LAYOUT.fontSize}px;--trees-level-gap-override: ${DOCUMENT_TREE_LAYOUT.levelGap}px;--trees-item-row-gap-override: ${DOCUMENT_TREE_LAYOUT.iconGap}px;- --trees-item-padding-x-override: 8px;- --trees-item-margin-x-override: 4px;- --trees-padding-inline-override: 4px;++ /* No horizontal gutter of its own: a row's hover fill spans the panel's+ content edges. Rows start without leading padding (DOCUMENT_TREE_ROW_CSS)+ so the chevron glyph lines up with the 「文档」 title, which in turn sits on+ the column of the panel tabs (技能 / 文档) above. */+ --trees-item-padding-x-override: 6px;+ --trees-item-margin-x-override: 0px;+ --trees-padding-inline-override: 0px;--trees-border-radius-override: 8px;/* Consumed by DOCUMENT_TREE_ICON_CSS inside the shadow root. */@@ -157,16 +172,29 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen[t],);+ // A plain document can be a parent too (a workflow with its run records+ // nested under it). The tree only lets containers hold children, so such a+ // document becomes a container drawn as a document.+ const parentDocumentIds = useMemo(() => {+ const ids = new Set<string>();+ for (const doc of documents) if (doc.parentId) ids.add(doc.parentId);+ return ids;+ }, [documents]);+const nodes = useMemo<ExplorerTreeNode<AgentDocumentItem>[]>(() =>- documents.map((doc) => ({- data: doc,- id: doc.id,- isFolder: doc.isFolder,- name: resolveNodeName(doc),- parentId: resolveParentRowId(doc.parentId),- })),- [documents, resolveNodeName, resolveParentRowId],+ documents.map((doc) => {+ const isParentDocument = !doc.isFolder && parentDocumentIds.has(doc.documentId);+ return {+ ...(isParentDocument && { appearance: 'file' as const }),+ data: doc,+ id: doc.id,+ isFolder: doc.isFolder || isParentDocument,+ name: resolveNodeName(doc),+ parentId: resolveParentRowId(doc.parentId),+ };+ }),+ [documents, parentDocumentIds, resolveNodeName, resolveParentRowId],);const treeStyleVars = useMemo(@@ -277,9 +305,14 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen);const handleNodeClick = useCallback(- (node: ExplorerTreeNode<AgentDocumentItem>) => {+ (node: ExplorerTreeNode<AgentDocumentItem>, event: MouseEvent<HTMLElement>) => {const doc = node.data;- if (!doc || node.isFolder) return;+ // A parent document is a container in the tree but still opens on click.+ if (!doc || doc.isFolder) return;+ // Its chevron only expands or collapses; the title opens the document.+ if (node.appearance === 'file' && isItemToggleEventPath(event.nativeEvent.composedPath())) {+ return;+ }if (onOpenDocument) {onOpenDocument(doc.documentId, doc.id);return;@@ -335,8 +368,12 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumenreturn [];}- const isFolder = !!node.isFolder;+ // `node.isFolder` also covers a document holding nested documents; menu+ // entries that depend on the row being a real folder read the data flag.+ const isFolder = !!node.data?.isFolder;const targetParentId = isFolder ? node.id : (node.parentId ?? null);+ const isPlainDocument =+ !isFolder && !isSkill && node.data?.category === AGENT_DOCUMENT_CATEGORY;// Right-click on a row that's part of the current multi-selection acts// on the whole selection; otherwise it targets only the right-clicked@@ -351,18 +388,21 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumenif (isFolder && !isSkill && !isMulti) {items.push({+ icon: <FolderPlusIcon size={14} />,key: 'new-folder',label: t('workingPanel.resources.tree.newFolder'),onClick: () => handleCreateFolder(targetParentId),sfSymbol: 'folder.badge.plus',},{+ icon: <FilePlusIcon size={14} />,key: 'new-document',label: t('workingPanel.resources.tree.newDocument'),onClick: () => handleCreateDocument(targetParentId),sfSymbol: 'doc.badge.plus',},{+ icon: <FileUpIcon size={14} />,key: 'upload-file',label: t('workingPanel.resources.tree.uploadFile'),onClick: () => openFolderFilePicker(targetParentId),@@ -372,6 +412,28 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen);}+ // Any document can hold sub-documents and folders, e.g. the run records+ // of a workflow grouped under it.+ if (isPlainDocument && !isMulti) {+ items.push(+ {+ icon: <FilePlusIcon size={14} />,+ key: 'new-sub-document',+ label: t('workingPanel.resources.tree.newSubDocument'),+ onClick: () => handleCreateDocument(node.id),+ sfSymbol: 'doc.badge.plus',+ },+ {+ icon: <FolderPlusIcon size={14} />,+ key: 'new-sub-folder',+ label: t('workingPanel.resources.tree.newFolder'),+ onClick: () => handleCreateFolder(node.id),+ sfSymbol: 'folder.badge.plus',+ },+ { key: 'div-sub', type: 'divider' },+ );+ }+if (!isSkill && !isMulti) {items.push({icon: <PenLineIcon size={14} />,@@ -470,6 +532,8 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumencanDrag={canDrag}canDrop={canDrop}canRename={canRename}+ fileAppearanceCSS={DOCUMENT_TREE_PARENT_DOCUMENT_GLYPH_CSS}+ flattenEmptyDirectories={false}getContextMenuItems={getContextMenuItems}header={toolbar}iconSet="complete"diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.tsindex cd8a9542519..be3ec7f171f 100644--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts@@ -11,16 +11,25 @@ const importFileMock = vi.hoisted(() => vi.fn());const removeUnreferencedFileMock = vi.hoisted(() => vi.fn());const uploadWithProgressMock = vi.hoisted(() => vi.fn());const dispatchDockFileListMock = vi.hoisted(() => vi.fn());+const createDocumentMock = vi.hoisted(() => vi.fn());+const createFolderByIdMock = vi.hoisted(() => vi.fn());+const moveDocumentsByIdMock = vi.hoisted(() => vi.fn());+const removeDocumentMock = vi.hoisted(() => vi.fn());+const confirmModalMock = vi.hoisted(() => vi.fn());vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({...(await importOriginal<object>()),- confirmModal: vi.fn(),+ confirmModal: confirmModalMock,toast: { error: toastError, success: vi.fn() },}));vi.mock('@/services/agentDocument', () => ({agentDocumentService: {+ createDocument: createDocumentMock,+ createFolderById: createFolderByIdMock,importFile: importFileMock,+ moveDocumentsById: moveDocumentsByIdMock,+ removeDocument: removeDocumentMock,},}));@@ -175,3 +184,95 @@ describe('useDocumentTreeOps.uploadFiles', () => {expect(importFileMock).not.toHaveBeenCalled();});});++// Parents are addressed by id, so a plain document can hold children — paths+// could not reach anything nested under a document.+describe('useDocumentTreeOps id-based tree edits', () => {+ const mutate = vi.fn();+ const sop = createDoc({+ documentId: 'sop-doc',+ fileType: 'custom/document',+ filename: 'SOP',+ id: 'sop-row',+ isFolder: false,+ title: 'SOP',+ });+ const run = createDoc({+ documentId: 'run-doc',+ fileType: 'custom/document',+ filename: 'Run 1',+ id: 'run-row',+ isFolder: false,+ title: 'Run 1',+ });++ beforeEach(() => {+ toastError.mockReset();+ mutate.mockReset();+ createDocumentMock.mockReset().mockResolvedValue({ id: 'new-row' });+ createFolderByIdMock.mockReset().mockResolvedValue({ created: true, folder: { id: 'f-row' } });+ moveDocumentsByIdMock.mockReset().mockResolvedValue([{ id: 'run-row', status: 'moved' }]);+ removeDocumentMock.mockReset().mockResolvedValue({ deleted: true, id: 'sop-row' });+ confirmModalMock.mockReset();+ });++ const renderOps = (data: AgentDocumentItem[]) =>+ renderHook(() => useDocumentTreeOps({ agentId: 'agent-1', data, mutate })).result.current;++ it('creates a sub-document under a document parent', async () => {+ await renderOps([sop]).createDocument('sop-row');++ expect(createDocumentMock).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', parentId: 'sop-doc' }),+ );+ });++ it('creates a root document without a parent', async () => {+ await renderOps([sop]).createDocument(null);++ expect(createDocumentMock.mock.calls[0][0]).not.toHaveProperty('parentId');+ });++ it('creates a folder by parent id', async () => {+ await renderOps([sop]).createFolder('sop-row');++ expect(createFolderByIdMock).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', parentId: 'sop-doc' }),+ );+ });++ it('moves rows under a document in one call and reports failures', async () => {+ moveDocumentsByIdMock.mockResolvedValue([+ {+ id: 'run-row',+ status: 'failed',+ error: '"Run 1" already exists in the destination folder.',+ },+ ]);++ await renderOps([sop, run]).moveDocument({+ sourceIds: ['run-row'],+ sourceNodes: [{ data: run }],+ targetId: 'sop-row',+ });++ expect(moveDocumentsByIdMock).toHaveBeenCalledWith({+ agentId: 'agent-1',+ ids: ['run-row'],+ parentId: 'sop-doc',+ });+ expect(toastError).toHaveBeenCalledWith(expect.stringContaining('already exists'));+ });++ it('deletes a parent document together with what is nested under it', async () => {+ const nested = { ...run, parentId: 'sop-doc' };+ renderOps([sop, nested]).deleteDocuments(['sop-row', 'run-row']);+ const [{ onOk }] = confirmModalMock.mock.calls[0];+ onOk();++ await vi.waitFor(() => expect(removeDocumentMock).toHaveBeenCalledTimes(1));+ expect(removeDocumentMock).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'sop-row', withChildren: true }),+ );+ });+});diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.tsindex 649c064d81c..931a52cbcc6 100644--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts@@ -22,15 +22,9 @@ interface UseDocumentTreeOpsArgs {topicId?: string;}-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.+// Service mutations return the agent-document row with its id 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>;@@ -81,44 +75,22 @@ export const useDocumentTreeOps = ({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;+ // Resolves a tree-node parent id (= row id, null for the root) to the parent's+ // documentId. Folders and plain documents can both hold children; `undefined`+ // means the parent is gone or cannot hold children (skills).+ const resolveParentDocumentId = useCallback(+ (parentRowId: string | null): string | null | undefined => {+ if (parentRowId === null) return null;const parent = byRowId.get(parentRowId);- if (!parent) return null;- if (parent.category === 'skill') return null;- return buildItemPath(parent);+ if (!parent || parent.category === 'skill') return undefined;+ return parent.documentId;},- [byRowId, buildItemPath],+ [byRowId],);// 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. When an extension is provided, the+ // dedup of "Untitled" rows because createFolder is idempotent (same name+ // re-uses the existing folder). When an extension is provided, the// numeric suffix is inserted before the extension so the file keeps its// type (e.g. `Untitled document 2.md`).const pickUniqueFilename = useCallback(@@ -138,16 +110,14 @@ export const useDocumentTreeOps = ({const createFolder = useCallback(async (parentId: string | null, opts?: CreateOptions) => {- const parentPath = buildParentPathFromRowId(parentId);- if (parentPath === null) {+ const parentDocumentId = resolveParentDocumentId(parentId);+ if (parentDocumentId === undefined) {toast.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);const pending = makePendingDocument({agentId,@@ -160,9 +130,13 @@ export const useDocumentTreeOps = ({const createPromise = (async (): Promise<string | null> => {try {- const result = await agentDocumentService.createFolder({ agentId, path: targetPath });+ const result = await agentDocumentService.createFolderById({+ agentId,+ parentId: parentDocumentId,+ title: filename,+ });await mutate();- return extractRowId(result);+ return extractRowId(result?.folder);} catch (error) {mutate((prev) => (prev ?? []).filter((doc) => doc.id !== pending.id), {revalidate: false,@@ -181,19 +155,18 @@ export const useDocumentTreeOps = ({pendingCreates.set(pending.id, createPromise);await createPromise;},- [agentId, buildParentPathFromRowId, byRowId, mutate, pendingCreates, pickUniqueFilename, t],+ [agentId, mutate, pendingCreates, pickUniqueFilename, resolveParentDocumentId, t],);const createDocument = useCallback(async (parentId: string | null, opts?: CreateOptions) => {- const parentPath = buildParentPathFromRowId(parentId);- if (parentPath === null) {+ const parentDocumentId = resolveParentDocumentId(parentId);+ if (parentDocumentId === undefined) {toast.error(t('workingPanel.resources.tree.parentMissing'));return;}const baseStem = t('workingPanel.resources.tree.untitledDocument');- const parentDocumentId = parentId ? (byRowId.get(parentId)?.documentId ?? null) : null;const pendingFilename = pickUniqueFilename(parentDocumentId, baseStem);const pending = makePendingDocument({@@ -207,19 +180,12 @@ export const useDocumentTreeOps = ({const createPromise = (async (): Promise<string | null> => {try {- const result =- parentPath === ROOT_PATH- ? await agentDocumentService.createDocument({- agentId,- content: '',- title: pendingFilename,- })- : await agentDocumentService.writeByPath({- agentId,- content: '',- createMode: 'always-new',- path: joinPath(parentPath, pendingFilename),- });+ const result = await agentDocumentService.createDocument({+ agentId,+ content: '',+ ...(parentDocumentId && { parentId: parentDocumentId }),+ title: pendingFilename,+ });await mutate();return extractRowId(result);} catch (error) {@@ -240,13 +206,13 @@ export const useDocumentTreeOps = ({pendingCreates.set(pending.id, createPromise);await createPromise;},- [agentId, buildParentPathFromRowId, byRowId, mutate, pendingCreates, pickUniqueFilename, t],+ [agentId, mutate, pendingCreates, pickUniqueFilename, resolveParentDocumentId, t],);const uploadFiles = useCallback(async (parentId: string | null, files: File[]) => {- const parentPath = buildParentPathFromRowId(parentId);- if (parentPath === null) {+ const parentDocumentId = resolveParentDocumentId(parentId);+ if (parentDocumentId === undefined) {toast.error(t('workingPanel.resources.tree.parentMissing'));return;}@@ -254,7 +220,6 @@ export const useDocumentTreeOps = ({const accepted = files.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));if (accepted.length === 0) return;- const parentDocumentId = parentId ? (byRowId.get(parentId)?.documentId ?? null) : null;const { dispatchDockFileList, uploadWithProgress } = useFileStore.getState();for (const file of accepted) {@@ -303,7 +268,7 @@ export const useDocumentTreeOps = ({}}},- [agentId, buildParentPathFromRowId, byRowId, mutate, t],+ [agentId, mutate, resolveParentDocumentId, t],);const renameDocument = useCallback(@@ -368,33 +333,27 @@ export const useDocumentTreeOps = ({async ({ sourceIds, sourceNodes, targetId }) => {if (sourceIds.length === 0) return;- const targetParentPath = buildParentPathFromRowId(targetId);- if (targetParentPath === null) {+ const targetItem = targetId ? byRowId.get(targetId) : null;+ if (targetItem?.isSkillBundle) return;+ const targetParentDocId = resolveParentDocumentId(targetId);+ if (targetParentDocId === undefined) {toast.error(t('workingPanel.resources.tree.parentMissing'));return;}- const targetItem = targetId ? byRowId.get(targetId) : null;- if (targetItem?.isSkillBundle) return;-- const targetParentDocId = targetItem ? targetItem.documentId : null;-- const moves: Array<{ fromPath: string; id: string; toPath: string }> = [];+ const ids: string[] = [];for (const id of sourceIds) {const node = sourceNodes.find((n) => n.data?.id === id)?.data;if (!node) continue;if (node.category === 'skill') return;- const fromPath = buildItemPath(node);- if (!fromPath) continue;- const toPath = joinPath(targetParentPath, node.filename);- if (fromPath === toPath) continue;- moves.push({ fromPath, id, toPath });+ if ((node.parentId ?? null) === targetParentDocId) continue;+ ids.push(id);}- if (moves.length === 0) return;+ if (ids.length === 0) return;// Optimistic: reparent each source row to the new parent's documentId.- const movedIds = new Set(moves.map((m) => m.id));+ const movedIds = new Set(ids);mutate((prev) =>(prev ?? []).map((doc) =>@@ -403,27 +362,27 @@ export const useDocumentTreeOps = ({{ 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)));- }+ let failures: string[];+ try {+ const results = await agentDocumentService.moveDocumentsById({+ agentId,+ ids,+ parentId: targetParentDocId,+ });+ failures = (results ?? [])+ .filter((result) => result.status === 'failed')+ .map((result) => result.error ?? result.title ?? result.id);+ } catch (error) {+ failures = [error instanceof Error ? error.message : String(error)];}await mutate();- if (errors.length > 0) {- const detail = errors.map((e) => e.message).join('; ');- toast.error(`${t('workingPanel.resources.tree.moveError')}: ${detail}`);+ if (failures.length > 0) {+ toast.error(`${t('workingPanel.resources.tree.moveError')}: ${failures.join('; ')}`);}},- [agentId, buildItemPath, buildParentPathFromRowId, byRowId, mutate, t],+ [agentId, byRowId, mutate, resolveParentDocumentId, t],);const deleteDocuments = useCallback(@@ -436,12 +395,11 @@ export const useDocumentTreeOps = ({if (resolved.length === 0) return;- // When a selected folder is an ancestor of another selection, skip the- // descendant — the folder's recursive delete already covers it.+ // When a selected entry is an ancestor of another selection, skip the+ // descendant — the ancestor's subtree delete already covers it. Folders and+ // documents with nested documents both delete their subtree.const docById = new Map(dataRef.current.map((doc) => [doc.documentId, doc]));- const folderDocIds = new Set(- resolved.filter((doc) => doc.isFolder && !doc.isSkillBundle).map((doc) => doc.documentId),- );+ const folderDocIds = new Set(resolved.map((doc) => doc.documentId));const hasAncestorIn = (item: AgentDocumentItem, ancestors: Set<string>): boolean => {let cursor = item.parentId;while (cursor) {@@ -461,35 +419,16 @@ export const useDocumentTreeOps = ({okText: t('delete', { ns: 'common' }),onOk: () => {const removedIds = new Set<string>();- const plans: Array<- | { kind: 'folder'; path: string; target: AgentDocumentItem }- | { kind: 'row'; target: AgentDocumentItem }- > = [];for (const target of targets) {- // Skill bundles are removed via the bundle row, not path-based- // recursive removal.- const isFolder = target.isFolder && !target.isSkillBundle;- if (isFolder) {- const folderPath = buildItemPath(target);- if (!folderPath) {- toast.error(t('workingPanel.resources.tree.parentMissing'));- return;- }- plans.push({ kind: 'folder', path: folderPath, target });- } else {- plans.push({ kind: 'row', target });- }removedIds.add(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);- }+ 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);}}}@@ -503,29 +442,23 @@ export const useDocumentTreeOps = ({void (async () => {const errors: Error[] = [];await Promise.all(- plans.map(async (plan) => {+ targets.map(async (target) => {try {- if (plan.kind === 'folder') {- await agentDocumentService.deleteByPath({- agentId,- path: plan.path,- recursive: true,- });- } else {- await agentDocumentService.removeDocument({- agentId,- documentId: plan.target.documentId,- id: plan.target.id,- topicId,- });- }+ // The user confirmed deleting the entry with everything under it.+ await agentDocumentService.removeDocument({+ agentId,+ documentId: target.documentId,+ id: target.id,+ topicId,+ withChildren: true,+ });} catch (error) {errors.push(error instanceof Error ? error : new Error(String(error)));}}),);- if (errors.length === plans.length) {+ if (errors.length === targets.length) {mutate(snapshot, { revalidate: false });const detail = errors.map((e) => e.message).join('; ');toast.error(`${t('workingPanel.resources.deleteError')}: ${detail}`);@@ -545,7 +478,7 @@ export const useDocumentTreeOps = ({: t('workingPanel.resources.deleteTitle'),});},- [agentId, buildItemPath, mutate, t, topicId],+ [agentId, mutate, t, topicId],);return useMemo(diff --git a/src/features/Conversation/Messages/AssistantGroup/constants.ts b/src/features/Conversation/Messages/AssistantGroup/constants.tsindex a8d5fb4cf53..ce1a1fe2f4a 100644--- a/src/features/Conversation/Messages/AssistantGroup/constants.ts+++ b/src/features/Conversation/Messages/AssistantGroup/constants.ts@@ -86,7 +86,9 @@ export const TOOL_API_DISPLAY_NAMES: Record<string, string> = {// Agent documentscopyDocument: 'workflow.toolDisplayName.copyDocument',+ createFolder: 'workflow.toolDisplayName.createFolder',listDocuments: 'workflow.toolDisplayName.listDocuments',+ moveDocuments: 'workflow.toolDisplayName.moveDocuments',readDocument: 'workflow.toolDisplayName.readDocument',removeDocument: 'workflow.toolDisplayName.removeDocument',renameDocument: 'workflow.toolDisplayName.renameDocument',diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsxindex 7300145888c..e8051edc03d 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx@@ -616,6 +616,7 @@ describe('AgentDocumentsGroup', () => {agentId: 'agent-1',documentId: 'doc-content-2',id: 'doc-2',+ withChildren: true,});expect(mutate).toHaveBeenCalled();expect(navigateMock).not.toHaveBeenCalled();diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsxindex 23c4b884251..b5f23314651 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx@@ -176,6 +176,7 @@ const DocumentItem = memo<DocumentItemProps>(agentId,documentId: document.documentId,id: document.id,+ withChildren: true,});await mutate();if (isActive) onCurrentDeleted?.();@@ -492,7 +493,12 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(okText: tCommon('delete'),onOk: async () => {try {- await agentDocumentService.removeDocument({ agentId: agentId!, id: rowId });+ // A skill bundle always holds its SKILL.md and resources.+ await agentDocumentService.removeDocument({+ agentId: agentId!,+ id: rowId,+ withChildren: true,+ });await mutate();toast.success(t('workingPanel.skills.delete.success'));} catch (error) {diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-documents.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-documents.tsindex 0f04b0026d1..b30481a5835 100644--- a/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-documents.ts+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-agent-documents.ts@@ -15,5 +15,31 @@ export default defineFixtures({documentId: 'doc_devtools_preview_plan',},}),+ createFolder: single({+ args: { title: 'Patrol reports' },+ pluginState: {+ agentDocumentId: 'agent_doc_folder_patrol',+ created: true,+ documentId: 'doc_folder_patrol',+ title: 'Patrol reports',+ },+ }),+ moveDocuments: single({+ args: { ids: ['agent_doc_run_1', 'agent_doc_run_2'], parentId: 'doc_folder_patrol' },+ pluginState: {+ failedCount: 1,+ movedCount: 1,+ parentId: 'doc_folder_patrol',+ results: [+ { id: 'agent_doc_run_1', status: 'moved', title: 'Run record 2026-10-10' },+ {+ error: '"Run record 2026-10-11" already exists in the destination folder.',+ id: 'agent_doc_run_2',+ status: 'failed',+ title: 'Run record 2026-10-11',+ },+ ],+ },+ }),},});diff --git a/src/features/ExplorerTree/documentTreeStyle.ts b/src/features/ExplorerTree/documentTreeStyle.tsindex 0057c92bf11..6e6dedacffb 100644--- a/src/features/ExplorerTree/documentTreeStyle.ts+++ b/src/features/ExplorerTree/documentTreeStyle.ts@@ -61,6 +61,13 @@ const maskGlyph = (glyph: string) => `mask-size: ${iconSize}px ${iconSize}px;`;+/**+ * Label glyph for a document that has records nested under it: it sits in the+ * tree as a container (chevron, children) but must still read as a document.+ * Passed as ExplorerTree's `fileAppearanceCSS`.+ */+export const DOCUMENT_TREE_PARENT_DOCUMENT_GLYPH_CSS = maskGlyph(FILE_TEXT_ICON_SVG);+export const DOCUMENT_TREE_ICON_CSS = `[data-item-type='folder'] [data-item-section='content'] {display: flex;@@ -149,6 +156,14 @@ export const DOCUMENT_TREE_ROW_CSS = `font-weight: 500;}+ /* The chevron glyph sits centered in its 16px slot, ~6px in from the slot's+ edge. Starting rows with no leading padding puts that glyph on the same line+ as the section title and the panel tabs above it, while the hover fill still+ reaches the panel edge. The trailing padding (the action lane) stays. */+ [data-type='item'] {+ padding-inline-start: 0;+ }+${DOCUMENT_TREE_NO_FOCUS_BORDER_CSS}${DOCUMENT_TREE_TRAILING_ELLIPSIS_CSS}`;diff --git a/src/features/ExplorerTree/folderIconStyle.ts b/src/features/ExplorerTree/folderIconStyle.tsindex f37e2218711..52c8574e6f9 100644--- a/src/features/ExplorerTree/folderIconStyle.ts+++ b/src/features/ExplorerTree/folderIconStyle.ts@@ -111,7 +111,7 @@ const MATERIAL_FILE_PREFIX_RULES = [{ iconName: 'vite', prefixes: ['vite.config.'] },] satisfies { iconName: string; prefixes: string[] }[];-const cssString = (value: string) => value.replaceAll('\\', '\\\\').replaceAll('"', '\\"');+export const cssString = (value: string) => value.replaceAll('\\', '\\\\').replaceAll('"', '\\"');const cssUrl = (url: string) => `url("${cssString(url)}")`;diff --git a/src/features/ExplorerTree/index.tsx b/src/features/ExplorerTree/index.tsxindex 08541434841..8b420caa0c0 100644--- a/src/features/ExplorerTree/index.tsx+++ b/src/features/ExplorerTree/index.tsx@@ -1,6 +1,7 @@export {DOCUMENT_TREE_ICON_CSS,DOCUMENT_TREE_LAYOUT,+ DOCUMENT_TREE_PARENT_DOCUMENT_GLYPH_CSS,DOCUMENT_TREE_ROW_CSS,} from './documentTreeStyle';export {@@ -21,4 +22,5 @@ export type {ExplorerTreeProps,ExplorerTreeRowDecorationCtx,} from './types';+export { isItemToggleEventPath } from './view/eventPath';export { default as ExplorerTree } from './view/ExplorerTree';diff --git a/src/features/ExplorerTree/types.ts b/src/features/ExplorerTree/types.tsindex 1f0c774214f..2f15ecfe632 100644--- a/src/features/ExplorerTree/types.ts+++ b/src/features/ExplorerTree/types.ts@@ -4,6 +4,13 @@ import type { CSSProperties, DragEvent, KeyboardEvent, MouseEvent, ReactNode } fimport type { NativeContextMenuItem } from '@/libs/contextMenu/types';export interface ExplorerTreeNode<TData = unknown> {+ /**+ * Draw a node that holds children (`isFolder`) as a file — e.g. a document+ * with records nested under it. It keeps its chevron and accepts drops, but+ * its label carries `fileAppearanceCSS` instead of the folder glyph, and a+ * click on the row opens it rather than toggling: only the chevron expands it.+ */+ appearance?: 'file';children?: ExplorerTreeNode<TData>[];data?: TData;id: string;@@ -92,6 +99,18 @@ export interface ExplorerTreeProps<TData = unknown> {defaultSelectedIds?: string[];density?: 'compact' | 'default' | 'relaxed' | number;expandedIds?: string[];+ /**+ * CSS declarations painted on the label of every folder node whose+ * `appearance` is `file` (inside the shadow root, so it can override the+ * folder glyph `unsafeCSS` draws).+ */+ fileAppearanceCSS?: string;+ /**+ * Collapse a chain of single-child folders into one row (`a/b/c`). On by+ * default, as in the code trees; a document tree turns it off because a+ * document holding a single folder would otherwise vanish into that row.+ */+ flattenEmptyDirectories?: boolean;/** Menu for a right click that lands on no row (the blank area under the rows). */getBlankContextMenuItems?: () => NativeContextMenuItem[];getContextMenuItems?: (node: ExplorerTreeNode<TData>) => NativeContextMenuItem[];diff --git a/src/features/ExplorerTree/view/ExplorerTree.test.tsx b/src/features/ExplorerTree/view/ExplorerTree.test.tsxindex d1d3cc48f7e..dae45388bc0 100644--- a/src/features/ExplorerTree/view/ExplorerTree.test.tsx+++ b/src/features/ExplorerTree/view/ExplorerTree.test.tsx@@ -11,7 +11,8 @@ import { canGoNative } from '@/libs/contextMenu/canGoNative';import { toNativeTemplate } from '@/libs/contextMenu/toNativeTemplate';import type { ExplorerTreeHandle, ExplorerTreeNode } from '../types';-import ExplorerTree, { getItemPathFromEventPath } from './ExplorerTree';+import { isItemToggleEventPath } from './eventPath';+import ExplorerTree, { buildFileAppearanceCSS, getItemPathFromEventPath } from './ExplorerTree';const showContextMenu = vi.hoisted(() => vi.fn());@@ -402,3 +403,79 @@ describe('ExplorerTree blank area and keys', () => {});});});++describe('ExplorerTree file appearance', () => {+ it('builds one rule over every path and escapes quotes', () => {+ expect(buildFileAppearanceCSS(['SOP/', 'a "b"/'], 'mask-image: x;')).toBe(+ `[data-item-type='folder'][data-item-path="SOP/"] [data-item-section='content']::before,\n` ++ `[data-item-type='folder'][data-item-path="a \\"b\\"/"] [data-item-section='content']::before {\nmask-image: x;\n}`,+ );+ expect(buildFileAppearanceCSS([], 'mask-image: x;')).toBe('');+ });++ // A document holding run records is a container in the tree but must not+ // wear the folder glyph; the rule follows the nodes as they change.+ it('paints file-appearance containers and drops the rule when none remain', async () => {+ const nodes: ExplorerTreeNode[] = [+ { appearance: 'file', id: 'sop', isFolder: true, name: 'SOP', parentId: null },+ { id: 'run', name: 'Run 1', parentId: 'sop' },+ { id: 'folder', isFolder: true, name: 'Reports', parentId: null },+ ];+ const view = render(<ExplorerTree fileAppearanceCSS="mask-image: x;" nodes={nodes} />);+ const style = () =>+ getHost(view.container).shadowRoot?.querySelector('style[data-explorer-file-appearance]');++ await waitFor(() => expect(style()?.textContent).toContain('[data-item-path="SOP/"]'));+ expect(style()?.textContent).not.toContain('Reports');++ view.rerender(+ <ExplorerTree+ fileAppearanceCSS="mask-image: x;"+ nodes={[{ id: 'sop', name: 'SOP', parentId: null }]}+ />,+ );+ await waitFor(() => expect(style()).toBeNull());+ });+});++describe('isItemToggleEventPath', () => {+ const row = () => {+ const el = document.createElement('div');+ el.dataset.type = 'item';+ el.dataset.itemPath = 'SOP/';+ return el;+ };+ const section = (name: string) => {+ const el = document.createElement('div');+ el.dataset.itemSection = name;+ return el;+ };++ // The chevron of a document holding records toggles; its title opens it.+ it('is true only when the event passed through the row icon slot', () => {+ const chevron = document.createElement('svg');+ expect(isItemToggleEventPath([chevron, section('icon'), row()])).toBe(true);+ expect(isItemToggleEventPath([section('content'), row()])).toBe(false);+ expect(isItemToggleEventPath([row(), section('icon')])).toBe(false);+ });+});++describe('ExplorerTree flattenEmptyDirectories', () => {+ // A document holding only a folder is a single-child chain; flattened, the+ // document would disappear into a combined "SOP/Runs" row.+ it('keeps each container on its own row when flattening is off', async () => {+ const nodes: ExplorerTreeNode[] = [+ { appearance: 'file', id: 'sop', isFolder: true, name: 'SOP', parentId: null },+ { id: 'runs', isFolder: true, name: 'Runs', parentId: 'sop' },+ { id: 'run', name: 'Run 1', parentId: 'runs' },+ ];+ const view = render(+ <ExplorerTree defaultExpandedIds={['sop']} flattenEmptyDirectories={false} nodes={nodes} />,+ );+ const root = () => getHost(view.container).shadowRoot;++ await waitFor(() => expect(root()?.querySelector('[data-item-path="SOP/"]')).not.toBeNull());+ expect(root()?.querySelector('[data-item-path="SOP/Runs/"]')).not.toBeNull();+ expect(root()?.querySelector('[data-item-flattened-subitems]')).toBeNull();+ });+});diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsxindex 6486d601d5c..906f9321021 100644--- a/src/features/ExplorerTree/view/ExplorerTree.tsx+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx@@ -23,6 +23,7 @@ import { useSingleton } from '@/hooks/useSingleton';import { arrayEqual, normalizeTree, remapIdsToPaths, remapPathsToIds } from '../adapter';import { extractName, toCanonicalTreePath } from '../adapter/path';+import { cssString } from '../folderIconStyle';import type {ExplorerTreeHandle,ExplorerTreeMoveEvent,@@ -30,7 +31,7 @@ import type {ExplorerTreeProps,} from '../types';import { openExplorerContextMenu } from './ContextMenu';-import { getItemPathFromEventPath } from './eventPath';+import { getItemPathFromEventPath, isItemToggleEventPath } from './eventPath';import NameInputHint from './NameInputHint';import { type PendingCreate, useInlineNameEdit } from './useInlineNameEdit';@@ -51,6 +52,24 @@ type FileTreeModel = ReturnType<typeof useFileTree>['model'];// a beat behind the store — the tree applies renames and drops optimistically,// and a data refresh can turn a folder into a file under the same name — so a// stale lookup has to degrade to null instead of taking down the whole route.+const FILE_APPEARANCE_STYLE_ATTRIBUTE = 'data-explorer-file-appearance';++/**+ * Per-row rules for folder nodes drawn as files. `unsafeCSS` is fixed when the+ * tree is constructed, but these rows change with the data (a document turns+ * into a parent when its first child lands), so the rules are keyed on each+ * row's path and rewritten into the shadow root whenever the nodes change.+ */+export const buildFileAppearanceCSS = (paths: string[], declarations: string): string =>+ paths.length === 0+ ? ''+ : `${paths+ .map(+ (path) =>+ `[data-item-type='folder'][data-item-path="${cssString(path)}"] [data-item-section='content']::before`,+ )+ .join(',\n')} {\n${declarations}\n}`;+const getItemSafely = (model: FileTreeModel, path: string): FileTreeItemHandle | null => {try {return model.getItem(path);@@ -120,6 +139,7 @@ function ExplorerTreeInner<TData>(return {density: props.density,+ flattenEmptyDirectories: props.flattenEmptyDirectories,dragAndDrop: {canDrag: (paths) => {const fn = propsRef.current.canDrag;@@ -492,6 +512,49 @@ function ExplorerTreeInner<TData>(}}, [adapterRef, props.nodes, model, requestTreeRebuild]);+ // Runs after the nodes effect above, so it reads the paths just applied. On+ // first mount the shadow root can attach a frame after this effect, so the+ // write retries for a few frames instead of silently skipping.+ useLayoutEffect(() => {+ const declarations = props.fileAppearanceCSS;+ const a = adapterRef.current;+ const paths = declarations+ ? [...a.nodeById.values()]+ .filter((node) => node.isFolder && node.appearance === 'file')+ .flatMap((node) => a.pathById.get(node.id) ?? [])+ : [];+ const css = declarations ? buildFileAppearanceCSS(paths, declarations) : '';++ const apply = (): boolean => {+ const shadowRoot = model.getFileTreeContainer()?.shadowRoot;+ if (!shadowRoot) return false;+ let style = shadowRoot.querySelector<HTMLStyleElement>(+ `style[${FILE_APPEARANCE_STYLE_ATTRIBUTE}]`,+ );+ if (!css) {+ style?.remove();+ return true;+ }+ if (!style) {+ style = document.createElement('style');+ style.setAttribute(FILE_APPEARANCE_STYLE_ATTRIBUTE, '');+ shadowRoot.append(style);+ }+ if (style.textContent !== css) style.textContent = css;+ return true;+ };++ if (apply()) return;+ let frame = 0;+ let attempts = 10;+ const retry = () => {+ attempts -= 1;+ if (!apply() && attempts > 0) frame = requestAnimationFrame(retry);+ };+ frame = requestAnimationFrame(retry);+ return () => cancelAnimationFrame(frame);+ }, [adapterRef, model, props.fileAppearanceCSS, props.nodes]);+useImperativeHandle(ref,(): ExplorerTreeHandle => ({@@ -566,8 +629,6 @@ function ExplorerTreeInner<TData>(};const handleClick = (event: MouseEvent<HTMLElement>) => {- const onNodeClick = propsRef.current.onNodeClick;- if (!onNodeClick) return;const itemPath = getItemPathFromHostEvent(event);if (!itemPath) return;const a = adapterRef.current;@@ -575,7 +636,17 @@ function ExplorerTreeInner<TData>(if (!id) return;const node = a.nodeById.get(id);if (!node) return;- onNodeClick(node, event);+ // The tree toggles any container on a row click, before the click reaches+ // this host listener. A file-appearance container opens on click instead, so+ // only its chevron may expand or collapse it: undo the row-click toggle.+ if (+ node.isFolder &&+ node.appearance === 'file' &&+ !isItemToggleEventPath(getComposedPath(event))+ ) {+ asDirectory(getItemSafely(model, itemPath))?.toggle();+ }+ propsRef.current.onNodeClick?.(node, event);};const handleDropCapture = (event: DragEvent<HTMLElement>) => {diff --git a/src/features/ExplorerTree/view/eventPath.ts b/src/features/ExplorerTree/view/eventPath.tsindex 3dab8e639bd..efef09db1c5 100644--- a/src/features/ExplorerTree/view/eventPath.ts+++ b/src/features/ExplorerTree/view/eventPath.ts@@ -13,3 +13,18 @@ export const getItemPathFromEventPath = (path: EventTarget[]): string | null =>return null;};++/**+ * Whether an event landed on a row's icon slot — the chevron on a container row.+ * Lets a container that also opens on click (a document with nested documents)+ * keep the chevron as a pure expand/collapse toggle.+ */+export const isItemToggleEventPath = (path: EventTarget[]): boolean => {+ for (const target of path) {+ if (!isHTMLElement(target)) continue;+ if (target.dataset.itemSection === 'icon') return true;+ if (target.dataset.type === 'item') return false;+ }++ return false;+};diff --git a/src/features/Portal/Document/useMoreMenu.test.ts b/src/features/Portal/Document/useMoreMenu.test.tsindex c1957328f6a..2409867c996 100644--- a/src/features/Portal/Document/useMoreMenu.test.ts+++ b/src/features/Portal/Document/useMoreMenu.test.ts@@ -117,6 +117,7 @@ describe('useDocumentMoreMenu', () => {agentId: 'agt_1',documentId: 'doc_1',id: 'adoc_1',+ withChildren: true,});expect(mocks.closeDocument).toHaveBeenCalledOnce();});diff --git a/src/features/Portal/Document/useMoreMenu.ts b/src/features/Portal/Document/useMoreMenu.tsindex f19f0454db1..521110f131a 100644--- a/src/features/Portal/Document/useMoreMenu.ts+++ b/src/features/Portal/Document/useMoreMenu.ts@@ -32,7 +32,13 @@ export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {okText: t('delete', { ns: 'common' }),onOk: async () => {try {- await agentDocumentService.removeDocument({ agentId, documentId, id: agentDocumentId });+ await agentDocumentService.removeDocument({+ agentId,+ documentId,+ id: agentDocumentId,+ // Documents nested under it go with it, as a folder's contents do.+ withChildren: true,+ });toast.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));// The panel is showing a document that no longer exists; popping it// returns the user to whatever the panel was opened over.diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex d91d2d1d6dc..fcbbdc4e102 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -67,6 +67,7 @@ class AgentDocumentService {scope?: 'agent' | 'currentTopic';sourceType?: 'all' | 'file' | 'web';topicId?: string;+ withChildCount?: boolean;}) => {return lambdaClient.agentDocument.listDocuments.query(params);};@@ -210,14 +211,17 @@ class AgentDocumentService {documentId?: string;id: string;topicId?: string;+ /** Also delete documents nested under it; a parent with children is refused otherwise. */+ withChildren?: boolean;} & AgentDocumentToolTriggerInput,) => {- const { agentId, documentId, id, topicId, toolContext, trigger } = params;+ const { agentId, documentId, id, topicId, toolContext, trigger, withChildren } = params;const result = await lambdaClient.agentDocument.removeDocument.mutate({agentId,id,toolContext,trigger,+ withChildren,});await invalidateDocumentMutation({agentDocumentId: id,@@ -310,39 +314,25 @@ class AgentDocumentService {}};- 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: {+ /** Tool-oriented: create a folder by name under the root or a parent folder id. */+ createFolderById = async (params: {agentId: string;- force?: boolean;- fromPath: string;- toPath: string;+ parentId?: string | null;+ title: string;}) => {- const result = await lambdaClient.agentDocument.renameDocumentByPath.mutate(params);+ const result = await lambdaClient.agentDocument.createFolder.mutate(params);await revalidateAgentDocuments(params.agentId);return result;};- writeByPath = async (params: {+ /** Tool-oriented: move documents/folders by id into a folder, or to the root with null. */+ moveDocumentsById = async (params: {agentId: string;- content: string;- createMode?: 'always-new' | 'if-missing' | 'must-exist';- path: string;+ ids: string[];+ parentId: string | null;}) => {- 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);+ const result = await lambdaClient.agentDocument.moveDocuments.mutate(params);await revalidateAgentDocuments(params.agentId);return result;diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.tsindex 58cc9f8878c..6c7f2078982 100644--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts@@ -81,6 +81,26 @@ const stashDocumentRegisterIntent = (input: {});};+const toListedDocument = (d: {+ childCount?: number;+ documentId: string;+ filename: string;+ fileType: string;+ id: string;+ parentId: string | null;+ title: string;+ updatedAt: Date;+}) => ({+ childCount: d.childCount,+ documentId: d.documentId,+ filename: d.filename,+ fileType: d.fileType,+ id: d.id,+ parentId: d.parentId,+ title: d.title,+ updatedAt: d.updatedAt,+});+const runtime = new AgentDocumentsExecutionRuntime({copyDocument: async ({ agentId, id, newTitle, toolContext, trigger }) => {@@ -131,6 +151,11 @@ const runtime = new AgentDocumentsExecutionRuntime(});return doc;},+ createFolder: async ({ agentId, parentId, title }) => {+ const result = await agentDocumentService.createFolderById({ agentId, parentId, title });+ if (!result) throw new Error(`Failed to create folder "${title}".`);+ return result;+ },createTopicDocument: async ({agentId,content,@@ -170,13 +195,9 @@ const runtime = new AgentDocumentsExecutionRuntime(includeArchivedToolResults: true,parentId,sourceType,+ withChildCount: true,});- return docs.map((d) => ({- documentId: d.documentId,- filename: d.filename,- id: d.id,- title: d.title,- }));+ return docs.map(toListedDocument);},listTopicDocuments: async ({ agentId, parentId, sourceType, topicId }) => {const docs = await agentDocumentService.listDocuments({@@ -186,14 +207,12 @@ const runtime = new AgentDocumentsExecutionRuntime(scope: 'currentTopic',sourceType,topicId,+ withChildCount: true,});- return docs.map((d) => ({- documentId: d.documentId,- filename: d.filename,- id: d.id,- title: d.title,- }));+ return docs.map(toListedDocument);},+ moveDocuments: async ({ agentId, ids, parentId }) =>+ (await agentDocumentService.moveDocumentsById({ agentId, ids, parentId })) ?? [],modifyNodes: async ({ agentId, id, operations, toolContext, trigger }) => {const doc = await agentDocumentService.modifyNodes({agentId,@@ -218,10 +237,10 @@ const runtime = new AgentDocumentsExecutionRuntime(// Delete stays a lambda side-effect (removeDocument drops the Work server-side);// it carries no cost, so it needs no cost-stamping defer. Keep the immediate// work-cache refresh so the sidebar drops the removed doc.- removeDocument: async ({ agentId, id, toolContext, trigger }) =>+ removeDocument: async ({ agentId, id, toolContext, trigger, withChildren }) =>(await withWorkRefresh(- agentDocumentService.removeDocument({ agentId, id, toolContext, trigger }),+ agentDocumentService.removeDocument({ agentId, id, toolContext, trigger, withChildren }),toolContext,)).deleted,diff --git a/src/utils/__tests__/agentDocumentContextMapping.test.ts b/src/utils/__tests__/agentDocumentContextMapping.test.tsindex e53265e8685..e093748899e 100644--- a/src/utils/__tests__/agentDocumentContextMapping.test.ts+++ b/src/utils/__tests__/agentDocumentContextMapping.test.ts@@ -204,6 +204,38 @@ describe('toAgentContextDocuments', () => {expect(result.map((d) => d.parentId)).toEqual(['folder-doc', 'folder-doc', undefined]);});+ // A workflow document holds its run records; they fold under it like folder+ // contents, and the parent document itself stays in the index.+ it('stamps the parent title on children of an ordinary document', () => {+ const rows = [+ buildDoc({ documentId: 'sop-doc', id: 'sop', sourceType: 'file', title: 'Fix-round SOP' }),+ buildDoc({ documentId: 'run-1', id: 'run-1', parentId: 'sop-doc', sourceType: 'file' }),+ buildDoc({ documentId: 'run-2', id: 'run-2', parentId: 'sop-doc', sourceType: 'file' }),+ ];++ const result = toAgentContextDocuments(rows);++ expect(result.map((d) => d.id)).toEqual(['sop', 'run-1', 'run-2']);+ expect(result.map((d) => [d.folderTitle, d.parentKind])).toEqual([+ [undefined, undefined],+ ['Fix-round SOP', 'document'],+ ['Fix-round SOP', 'document'],+ ]);+ });++ it('does not treat web clips or skill rows as parents', () => {+ const rows = [+ buildDoc({ documentId: 'web-doc', id: 'web', sourceType: 'web' }),+ buildDoc({ documentId: 'skill-doc', fileType: 'skills/index', id: 'skill' }),+ buildDoc({ documentId: 'a', id: 'a', parentId: 'web-doc', sourceType: 'file' }),+ buildDoc({ documentId: 'b', id: 'b', parentId: 'skill-doc', sourceType: 'file' }),+ ];++ const result = toAgentContextDocuments(rows);++ expect(result.filter((d) => d.folderTitle)).toEqual([]);+ });+it('keeps non-folder skill rows such as the SKILL.md index', () => {const rows = [buildDoc({diff --git a/src/utils/agentDocumentContextMapping.ts b/src/utils/agentDocumentContextMapping.tsindex 560377f2987..4cad05fecc1 100644--- a/src/utils/agentDocumentContextMapping.ts+++ b/src/utils/agentDocumentContextMapping.ts@@ -1,4 +1,4 @@-import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';+import { CUSTOM_FOLDER_FILE_TYPE, WEB_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';import {AGENT_DOCUMENT_INJECTION_POSITIONS,type AgentContextDocument,@@ -76,16 +76,27 @@ export const toAgentContextDocument = (doc: AgentDocumentContextPayload): AgentCexport const toAgentContextDocuments = (docs: AgentDocumentContextPayload[],): AgentContextDocument[] => {- const folderTitleById = new Map<string, string>();+ // Folders and ordinary documents can both hold children (a workflow document+ // with its run records nested under it). Skill bundles keep their own layout.+ const parentById = new Map<string, { kind: 'document' | 'folder'; title: string }>();for (const doc of docs) {- if (doc.fileType === CUSTOM_FOLDER_FILE_TYPE) folderTitleById.set(doc.documentId, doc.title);+ if (doc.fileType === CUSTOM_FOLDER_FILE_TYPE) {+ parentById.set(doc.documentId, { kind: 'folder', title: doc.title });+ } else if (+ !doc.isFolder &&+ // Cached client payloads can predate `fileType`; treat a missing one as a document.+ !(doc.fileType ?? '').startsWith('skills/') &&+ doc.sourceType !== WEB_DOCUMENT_SOURCE_TYPE+ ) {+ parentById.set(doc.documentId, { kind: 'document', title: doc.title });+ }}return docs.filter((doc) => !doc.isFolder).map((doc) => {const mapped = toAgentContextDocument(doc);- const folderTitle = doc.parentId ? folderTitleById.get(doc.parentId) : undefined;- return folderTitle ? { ...mapped, folderTitle } : mapped;+ const parent = doc.parentId ? parentById.get(doc.parentId) : undefined;+ return parent ? { ...mapped, folderTitle: parent.title, parentKind: parent.kind } : mapped;});};